Skip to content
Snippets Groups Projects
Commit 5566611e authored by tuhe's avatar tuhe
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
Showing with 506 additions and 0 deletions
## This stuff relates to unitgrade and build-stuff we don't care about.
'
__pycache__
.idea
*.token
cp.egg-info
cache.db
*_grade.manifest
*.artifacts.pkl
.coveragerc
*_tests_complete_grade.py
# Lock file. DISABLE checking with gitlab (and syncing), so you *wnat* this on your computer, but *not* on the students computer.
**/unitgrade_data/dont_check_remote.lock
######################## Comment these out upon release. #############################
cp/ex05
cp/ex06
cp/ex07
cp/ex08
cp/ex09
cp/ex10
cp/ex11
cp/ex12
cp/exam
cp/project1
# cp/project2
cp/project3
cp/project4
cp/project5
cp/project6
[
{
"key": "shift+alt+e",
"command": "editor.debug.action.selectionToRepl"
}
]
\ No newline at end of file
{
"python.testing.unittestArgs": [
"-v",
"-s",
"./cp",
"-p", "*tests*.py"
],
"python.testing.pytestEnabled": false,
"python.testing.unittestEnabled": true,
}
# Exercise code for 02002/02003: Computer Programming.
This repository contains code for the exercise and projects for the course *Computer Programming*, course numbers **02002** and **02003**.
For instructions on how to install python and set up the code, please see the installation instructions at the course homepage:
- https://cp.pages.compute.dtu.dk/02002public/
The course homepage also contains information on how you can get help, as well as the exercise instructions that will allow you to complete the exercises.
""" Source code for 02466, Introduction to reinforcement learning and control, offered at DTU """
__version__ = "0.0.1"
# Do not import Matplotlib (or imports which import matplotlib) in case you have to run in headless mode.
import shutil
import inspect
import lzma, pickle
import numpy as np
import os
# Global imports from across the API. Allows imports like
# > from cp import Agent, train
# from cp.utils.irlc_plot import main_plot as main_plot
# from cp.utils.irlc_plot import plot_trajectory as plot_trajectory
# try:
# from cp.ex01.agent import Agent as Agent, train as train
# from cp.ex09.rl_agent import TabularAgent, ValueAgent
# except ImportError:
# pass
# from cp.utils.player_wrapper import interactive as interactive
# from cp.utils.lazylog import LazyLog # This one is unclear. Is it required?
# from cp.utils.timer import Timer
def get_ipp_base():
dir_path = os.path.dirname(os.path.realpath(__file__))
return dir_path
# def get_students_base():
# return os.path.join(get_ipp_base(), "../../../02465students/")
def pd2latex_(pd, index=False, escape=False, column_spec=None, **kwargs): # You can add column specs.
for c in pd.columns:
if pd[c].values.dtype == 'float64' and all(pd[c].values - np.round(pd[c].values)==0):
pd[c] = pd[c].astype(int)
ss = pd.to_latex(index=index, escape=escape, **kwargs)
return fix_bookstabs_latex_(ss,column_spec=column_spec)
def fix_bookstabs_latex_(ss, linewidth=True, first_column_left=True, column_spec=None):
to_tabular_x = linewidth
if to_tabular_x:
ss = ss.replace("tabular", "tabularx")
lines = ss.split("\n")
hd = lines[0].split("{")
if column_spec is None:
adj = (('l' if to_tabular_x else 'l') if first_column_left else 'C') + ("".join(["C"] * (len(hd[-1][:-1]) - 1)))
else:
adj = column_spec
# adj = ( ('l' if to_tabular_x else 'l') if first_column_left else 'C') + ("".join(["C"] * (len(hd[-1][:-1])-1)))
if linewidth:
lines[0] = "\\begin{tabularx}{\\linewidth}{" + adj + "}"
else:
lines[0] = "\\begin{tabular}{" + adj.lower() + "}"
ss = '\n'.join(lines)
return ss
def _savepdf_env(file, env):
from PIL import Image
import matplotlib.pyplot as plt
if hasattr(env, 'render_mode') and not env.render_mode == 'rgb_array':
env.render_mode, rmt = 'rgb_array', env.render_mode
frame = env.render()
if hasattr(env, 'render_mode') and not env.render_mode == 'rgb_array':
env.render_mode = rmt
im = Image.fromarray(frame)
snapshot_base = file
if snapshot_base.endswith(".png"):
sf = snapshot_base[:-4]
fext = 'png'
else:
fext = 'pdf'
if snapshot_base.endswith(".pdf"):
sf = snapshot_base[:-4]
else:
sf = snapshot_base
sf = f"{sf}.{fext}"
dn = os.path.dirname(sf)
if len(dn) > 0 and not os.path.isdir(dn):
os.makedirs(dn)
print("Saving snapshot of environment to", os.path.abspath(sf))
if fext == 'png':
im.save(sf)
from cp import _move_to_output_directory
_move_to_output_directory(sf)
else:
plt.figure(figsize=(16, 16))
plt.imshow(im)
plt.axis('off')
plt.tight_layout()
from cp import savepdf
savepdf(sf, verbose=True)
# plt.show()
def savepdf(pdf, verbose=False, watermark=False, env=None, _png=False):
"""
Convenience function for saving PDFs. Just call it after you have created your plot as ``savepdf('my_file.pdf')``
to save a PDF of the plot.
You can also pass an environment, in which case the environment will be stored to a pdf file.
:param pdf: The file to save to, for instance ``"my_pdf.pdf"``
:param verbose: Print output destination (optional)
:param watermark: Include a watermark (optional)
:return: Full path of the created PDF.
"""
if env is not None:
_savepdf_env(pdf, env)
return
import matplotlib.pyplot as plt
pdf = os.path.normpath(pdf.strip())
pdf = pdf+".pdf" if not pdf.endswith(".pdf") else pdf
if os.sep in pdf:
pdf = os.path.abspath(pdf)
else:
pdf = os.path.join(os.getcwd(), "pdf", pdf)
if not os.path.isdir(os.path.dirname(pdf)):
os.makedirs(os.path.dirname(pdf))
modules = [inspect.getmodule(s[0]) for s in inspect.stack()]
files = [m.__file__ for m in modules if m is not None]
if any( [f.endswith("RUN_OUTPUT_CAPTURE.py") for f in files] ):
return
# for s in stack:
# print(s)
# print(stack)
# for k in range(len(stack)-1, -1, -1):
# frame = stack[k]
# module = inspect.getmodule(frame[0])
# filename = module.__file__
# print(filename)
# if not any([filename.endswith(f) for f in ["pydev_code_executor.py", "pydevd.py", "_pydev_execfile.py", "pydevconsole.py", "pydev_ipython_console.py"] ]):
# # print("breaking c. debugger", filename)
# break
# if any( [filename.endswith(f) for f in ["pydevd.py", "_pydev_execfile.py"]]):
# print("pdf path could not be resolved due to debug mode being active in pycharm", filename)
# return
# print("Selected filename", filename)
# wd = os.path.dirname(filename)
# pdf_dir = wd +"/pdf"
# if filename.endswith("_RUN_OUTPUT_CAPTURE.py"):
# return
# if not os.path.isdir(pdf_dir):
# os.mkdir(pdf_dir)
wd = os.getcwd()
ipp_base = os.path.dirname(__file__)
if False:
pass
else:
plt.savefig(fname=pdf)
outf = os.path.normpath(os.path.abspath(pdf))
print("> [savepdf]", pdf + (f" [full path: {outf}]" if verbose else ""))
return outf
def _move_to_output_directory(file):
"""
Hidden function: Move file given file to static output dir.
"""
if not is_this_my_computer():
return
CDIR = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/')
shared_output_dir = CDIR + "/../../shared/output"
shutil.copy(file, shared_output_dir + "/"+ os.path.basename(file) )
# def bmatrix(a):
# if False:
# return a.__str__()
# else:
# np.set_printoptions(suppress=True)
# """Returns a LaTeX bmatrix
# :a: numpy array
# :returns: LaTeX bmatrix as a string
# """
# if len(a.shape) > 2:
# raise ValueError('bmatrix can at most display two dimensions')
# lines = str(a).replace('[', '').replace(']', '').splitlines()
# rv = [r'\begin{bmatrix}']
# rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines]
# rv += [r'\end{bmatrix}']
# return '\n'.join(rv)
def is_this_my_computer():
CDIR = os.path.dirname(os.path.realpath(__file__)).replace('\\', '/')
return os.path.exists(CDIR + "/../../Exercises")
# def cache_write(object, file_name, only_on_professors_computer=False, verbose=True, protocol=-1): # -1 is default protocol. Fix crash issue with large files.
# if only_on_professors_computer and not is_this_my_computer():
# """ Probably for your own good :-). """
# return
#
# dn = os.path.dirname(file_name)
# if not os.path.exists(dn):
# os.mkdir(dn)
# if verbose: print("Writing cache...", file_name)
# with lzma.open(file_name, 'wb') as f:
# pickle.dump(object, f)
# # compress_pickle.dump(object, f, compression="lzma", protocol=protocol)
# if verbose:
# print("Done!")
def cache_exists(file_name):
return os.path.exists(file_name)
# def cache_read(file_name):
# if os.path.exists(file_name):
# with lzma.open(file_name, 'rb') as f:
# return pickle.load(f)
# else:
# return None
inputs = []
def minput(ls):
"""
Higher-order function to fix input.
The function is given a list of keyboard input strings it will dutifully enter into input. If one of the inputs in the
list is None, the function will throw an error. This is useful to terminate early and show what the user sees as
part of the interaction.
This function should eventually be absorbed into unitgrade once potential kinks involving stdout has been worked out.
:param ls: Input strings.
:return: An alternative input-function (for use in mocking)
"""
inputs.clear()
for l in ls:
inputs.append(l)
def _input(x):
l = inputs[0]
if l is None:
print(x)
raise GeneratorExit()
# raise Exception()
print(x, l)
del inputs[0]
return l
return _input
"""The exercises in this folder are intended as preparation for the course start."""
"""Problem 0.1. Print out 'Hello' and 'World' on two separate lines."""
print("Hello")
# Put your code here so the program outputs
# > Hello
# > World
# on two lines.
# TODO: 1 lines missing.
"""This package represents exercise 1."""
"""A handful of python programming examples."""
# Example 1
print("Hello world")
# Example 2
print("hello")
print("world")
a = 2
b = 3
c = 1
x = 3
y = a*x**2 + b * x + c
# Example 3
def second_poly(x):
"""Compute a first order polynomial.
:param x: Input value :math:`x`
:return: :math:`y = 2x + 4`
"""
return 2 * x + 4
# example 4
def say_hello(name):
"""Print out "Hello {name}.
:param name: The name to say hello to
"""
print("Hello " + name)
"""This package represents exercise 1."""
"""Exercise 2.3: The Fibonacci sequence and recursion."""
def fibonacci_number(k):
"""Compute the :math:`k`'th Fibonacci number :math:`x_k`.
The function use the recursive relationship :math:`x_{k+1} = x_k + x_{k-1}`, along with the initial conditions
:math:`x_0 =0, x_1 = 1`, to complete the sequence up to :math:`k`.
:param k: An integer
:return: The corresponding term :math:`x_k` of the Fibonacci sequence as an integer.
"""
if k == 0:
# TODO: 1 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
elif k == 1:
# TODO: 1 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
else:
# TODO: 1 lines missing.
raise NotImplementedError("Fix this stuff")
if __name__ == "__main__":
print("The term x_0 should be 0, you got:", fibonacci_number(0))
print("The term x_1 should be 1, you got:", fibonacci_number(1))
print("The term x_2 should be 1, you got:", fibonacci_number(1))
print("The term x_6 should be 8, you got:", fibonacci_number(6))
"""Problem 1.1."""
def evaluate_taylor(x: float) -> float:
r"""Compute the third order taylor approximation.
Compute (and return) the Taylor approximation of :math:`\log(x)`. Remember the function must return a ``float``.
:param x: The input to evaluate.
:return: The taylor approximation of :math:`\log(x)`, i.e. :math:`y`
"""
# TODO: 1 lines missing.
raise NotImplementedError("Define y = (x-1) - 1/2 * ... here.")
return y
"""Problem 1.2. Implement a function that computes (and return) the third order Taylor-approximation here."""
# TODO: Code has been removed from here.
raise NotImplementedError("Insert your solution and remove this error.")
"""Problem 1.3. Compute the third order taylor approximation evaluated in x here and store it in a variable y."""
x = 1.5
# Define y = ... here.
# TODO: 1 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
# print(y) should work.
"""Exercises for week 3."""
"""Exercise 3.9: Ackermann's function."""
def ackermann(m:int, n:int):
"""Compute the Ackermann's function :math:`A(m, n)`.
Your implementation should use recursion and not loops.
:param m: the variable m.
:param n: the variable n.
:return: the computed value :math:`A(m,n)`.
"""
# TODO: 5 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
"""Exercise 3.5: BAC Calculator."""
def bac_calculator(alcohol_consumed: float, weight: float, gender: str, time: float) -> float:
"""Calculate the blood alcohol concentration based on the alcohol consumed, body weight, and time since consumption.
:param alcohol_consumed: The total amount of alcohol consumed in grams (float)
:param weight: The person's body weight in kilograms (float)
:param gender: The person's gender, which must be a string of either "male" or "female" (str)
:param time: The time elapsed since alcohol consumption in hours (float)
:return: The calculated blood alcohol concentration (BAC) as a float value.
"""
# TODO: 10 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
return bac
"""Problems for the Bisection project in week 3."""
import math
def f(x : float) -> float:
r"""Find the roots of this function.
You should implement the function :math:`f(x)` here. It is defined as:
.. math::
f(x) = \sin(3\cos(\frac{1}{2} x^2))
:param x: The value to evaluate the function in :math:`x`
:return: :math:`f(x)`.
"""
# TODO: 1 lines missing.
raise NotImplementedError("Compute f(x) here.")
return y
def is_there_a_root(a : float, b : float) -> bool:
"""Return ``True`` if we are guaranteed there is a root of ``f`` in the interval :math:`[a, b]`.
:param a: Lowest x-value to consider
:param b: Highest x-value to consider
:return: ``True`` if we are guaranteed there is a root otherwise ``False``.
"""
# TODO: 1 lines missing.
raise NotImplementedError("Compute the condition here")
return has_root
def bisect(xmin : float, xmax : float, delta : float) -> float:
"""Find a candidate root within ``xmin`` and ``xmax`` within the given tolerance.
:param xmin: The minimum x-value to consider
:param xmax: The maximum x-value to consider
:param delta: The tolerance.
:return: The first value :math:`x` which is within ``delta`` distance of a root according to the bisection algorithm
"""
# TODO: 6 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
if __name__ == "__main__":
print("Are we guaranteed there is a zero within the interval [1, 3]?", is_there_a_root(1, 3), "(this should be True)")
print("Are we guaranteed there is a zero within the interval [1, 3.5]?", is_there_a_root(1, 3.5), "(this should be False)")
print("Find a zero within tolerance 0.1 in the interval [1, 2]")
print(bisect(1, 2, 0.1))
print("Same, but with a tolerance of 0.5")
print(bisect(1, 2, 0.1))
print("Should return math.nan")
print(bisect(1, 3.5, 0.1))
"""Exercise 3.4: Body Temperature."""
def body_temperature(temperature : float) -> str:
"""Calculate the body's response based on the given temperature.
:param temperature: The temperature in degrees Celsius.
:return: The body's response as a string.
"""
# TODO: 10 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
return response
"""Exercise 3.3: Compare numbers."""
def compare_numbers(first_number:int, second_number:int) -> str:
"""Return a string based on which number has the greatest numerical value.
:param first_number: first number.
:param second_number: second number.
:return: string stating which number is the greatest.
"""
# TODO: 6 lines missing.
raise NotImplementedError("Insert your solution and remove this error.")
return comparison
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment