I am working on the file "Level_01/Level_1.ipynb".
The first task is:
Oben sind die wichtigsten Operatoren für Werte des Integer Typs aufgelistet. Bemerkenswert ist, dass es drei Arten der Divison gibt: die ganzzahlige Division, die (ganzzahlige) Division mit Rest und die "normale" Division. Die ganzzahlige Division liefert ein abgerundetes Ergebnis als Integer, die Division mit Rest liefert den Rest der ganzzahligen Divison und die "normale" Division liefert einen Wert des Typen float.
Can you write Python code for it?


I am working on the file "Level_01/Level_1.ipynb".
The first task is:
Python besitzt eine streng dynamische Typisierung, das heißt:

Eine Variable kann auf Werte verschiedenen Typs zeigen.
Jedes Objekt hat einen Typ.

Bei jeder neuen Zuweisung wird der Wert einer Variable überschrieben, dabei kann sich der Typ des Werts ändern.
Can you write Python code for it?

s = "String"
print(type(s))
s = 4
print(type(s))


I am working on the file "Level_01/Level_1.ipynb".
The first task is:
Strings
Ein String ist eine Zeichenkette und wird repräsentiert Text. Ein String kann mit "" oder '' definiert werden.
Can you write Python code for it?

hallo = 'Hallo Welt!'
text = "Programmieren mit Python."
print(hallo, text, sep="\n")


I am working on the file "Level_01/Level_1.ipynb".
The first task is:
Strings sind allerdings nicht auf eine Zeile begrenzt. Multiline strings werden durch dreifache Anführungszeichen definiert.
Can you write Python code for it?

multiline = """
Dies ist ein
mehrzeiliger
String
    mit Einrückung.
"""
print(multiline)

# Strings können wir miteinander "addieren", man spricht auch von konkatinieren
foo = "foo"
bar = "bar"
foobar = foo + bar
print(foobar)

# Strings können wir auch "multiplizieren":
print(10*"#" + " foo " + 10*"#")

# len() liefert uns die Länge eines Objektes:
text = "Programmieren mit Python."
length = len(text)

print(text)
print(length*"*")
print(length)

# mit der str() Funktion lassen sich Objekte in einen String umwandeln:
s = str(12)
print(s)


I am working on the file "Level_01/Level_1.ipynb".
The first task is:
Variablen

Readability counts. - Zen of Python

Variablen werden benutzt, um Werte für die spätere Wiederbenutzung zu speichern. Dabei zeigt die Variable lediglich auf einen Wert. Eine Variable hat dabei keinen festen Typ, nur die Werte
Can you write Python code for it?

ham = 4
egg = 12
ham_price = 2.99
egg_price = 0.49
print(ham, egg)
print(ham_price, egg_price)
print()
print("ham: ", ham * ham_price)
print("egg: ", egg * egg_price)
summ = ham * ham_price + egg * egg_price
print("sum: ", summ)


I am working on the file "Level_01/Level_1.ipynb".
The first task is:
Zen of Python
Der "Zen of Python" bietet einige Leitlinien, an denen sich Python als Sprache orientiert und an denen wir uns auch beim Programmieren mit Python orientieren können. In bisherigen Abschnitten wurden Teile bereits zitiert, unten sind einmal alle Punkte aufgelistet.
Can you write Python code for it?


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
"==" und "is"
== prüft, ob die Objekte, auf die die Variablen zeigen, äquivalent sind. <br>
is prüft, ob die Variablen auf dasselbe Objekt zeigen.
Can you write Python code for it?


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
Das Schlüsselwort else kann nicht nur in einer if-Bedingung, sonder auch in Verbindung mit einer while-Schleife benutzt werden. Dabei wird der else-Zweig ans Ende der entsprechenden while-Schleife angefügt. Der Code des else-Zweiges wird dann nur ausgeführt, wenn die Schleife nicht durch ein break abgebrochen wurde.
Can you write Python code for it?

# Zahlen raten
gesucht = 56
versuche = 10
zähler = 0
print("Die gesuchte Zahl x ist 0 < x < 100.")

while zähler < versuche:
    eingabe = input(": ")
    zähler += 1
    # eingabe überprüfen
    if eingabe.isdigit():
        zahl = int(eingabe)
    else:
        print("Ungültige Eingabe.")
        continue

    # Benutzer Feedback
    if zahl == gesucht:
        print("Richtig!")
        break
    else:
        if zahl > gesucht:
            print("Kleiner.")
        else:
            print("Größer")
        print("Noch", versuche-zähler, "Versuche.")

else:
    # kein break <=> zahl wurde nicht erraten
    print("Die Zahl wurde nicht erraten.")
    print("Die richtige Zahl war:", gesucht)


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
Der Typ eines Objektes bestimmt, wie dieses in einen boolean umgewandelt wird. Für die bisherigen Typen integer, float und string gilt:
* ein integer ist True, solange er nicht 0 ist
* ein float ist True, solange er nicht 0.0 ist
* ein string ist True, solange er nicht leer, d.h. '' ist
Can you write Python code for it?


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
Genauso wie integer und floats gibt es auch für booleans Operatoren:
* and das logische "und"
* or das logische "oder"
* not die logische Negation
Außerdem lässt sich auch xor (^) auf booleans anwenden.
Can you write Python code for it?

print("not True:", not True)
print("True or False:", True or False)
print("True and False:", True and False)
print("True ^ False:", True ^ False)


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
Im obigen Codebeispiel prüft die if-Bedingung, ob der String eingabe leer ist. Dies geschieht implizit, d.h. es wird ausgenutzt, dass der Interpreter die Bedingung in einen boolean umwandelt. In dem Kommentar sind alternative Bedingungen beschrieben, die daselbe erreichen, allerdings umständlicher sind. <br>
Wenn wir uns aber an unser Problem aus der Einleitung erinnern, war unser Ziel eine Zahl aus der Eingabe zu lesen und Fehler durch falsche Benutzereingaben abzufangen. Wir wollen also darauf reagieren, wenn nichts eingegeben wurde, wenn eine Zahl eingegeben wurde und wenn eine Zeichenkette eingegeben wurde, die nicht als integer interpretiert werden kann.
Can you write Python code for it?

eingabe = input("Bitte etwas eingeben: ")

if eingabe.isdigit():
    zahl = int(eingabe)
    print(zahl)

else:
    print("Ungültige Eingabe:", eingabe)


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
Schauen wir uns obigen Code an. Wir erwarten eine Eingabe und versuchen aus dieser Eingabe einen integer zu entnehmen. Dies klappt auch, wenn der Benutzer eine ganze Zahl eingibt - gibt er jedoch stattdessen zum Beispiel eine Zeichenkette ein, wird ein ValueError geworfen. Ebenso wird ein Fehler geworfen, wenn der Benutzer nichts eingibt.
Im Verlauf dieses Levels werden wir, lernen Benutzereingaben zu prüfen und entsprechend zu reagieren.
Der Typ boolean
Der boolean ist ein Typ, der genau zwei Werte besitzt: True und False. In Python3 sind diese beiden Literale Schlüsselwörter und können somit nicht als Variablennamen benutzt werden. Mit der bool()Funktion kann ein Wert in einen boolean umgewandelt werden.
Can you write Python code for it?

b1 = True
b2 = False
print(type(b1))
print(type(b2))


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
Wie wir sehen können, passiert im obigen Codebeispiel eine Menge auf einmal, gehen wir es also in Ruhe durch.
In der if-Abfrage wird mit der str.isdigit() Methode geprüft, ob der string eingabe nicht leer ist und nur aus Ziffern besteht; wenn dem so ist, erstellen wir einen integer zahl aus der Eingabe und geben diesen aus. In einem else Zweig, der ausgeführt wird, wenn die Bedingung der if-Abfrage nicht zutraf, geben wir dem Benutzer Feedback über seine falsche Eingabe zurück.
Can you write Python code for it?

eingabe = input("Bitte eine Zahl eingeben: ")

if eingabe:
    # die Eingabe ist nicht leer.
    if eingabe.isdigit():
        zahl = int(eingabe)
        print(zahl, "ist eine gültige Zahl.")
    else:
        print("Die Eingabe ''" + eingabe + "' ist keine gültige Zahl")
else:
    print("Die Eingabe ist leer.")


I am working on the file "Level_02/Level_2.ipynb".
The first task is:
if-Bedingung
Nun da wir gelernt haben, was boolean-Werte sind, können wir diese in einer if-Abfrage benutzen: Codeteile nur dann ausführen, wenn eine Bedingung erfüllt ist. Sehen wir uns zunächst die Syntax einer if-Abfrage in Python an:
python
if Bedingung:
    Befehle
Wir starten mit dem Schlüsselwort if, dann kommt eine Bedingung, diese sollte einen boolschen Ausdruck zurückgeben, wir können diesen explizit angeben, der Interpreter ruft allerdings auf unsere Bedingung bool() auf und führt unsere Befehle aus, wenn dies Truezurück gibt. Nach der Bedingung folgt ein Doppelpunkt :. Die nächste Zeile wird nun eingerückt, hierbei hat man sich auf vier Leerzeichen geeinigt.
Can you write Python code for it?

eingabe = input("Bitte etwas eingeben: ")
if eingabe:  # alternativ: bool(eingabe) oder eingabe != ""
    print(eingabe)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Aber vorsicht:
Can you write Python code for it?

liste = [0, True, 4.2, False, "spam", "egg", 42]
print("1:", 1 in liste)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Als Schlüssel sind Werte aller unveränderlichen Typen erlaubt, in einem Dictionary müssen die Schlüssel auch nicht denselben Typen haben, es ergibt sich meistens aber, dass die Schlüssel denselben Typen haben.
Can you write Python code for it?

beispiel_dict = {0:"integer", True:"boolean", (0,0):"tuple", "s":"strings"}
print(beispiel_dict)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Alternativ kann für den Zugriff die dict.get() Methode benutzt werden. Diese ermöglicht es auch einen Standardwert anzugeben, wenn der Schlüssel in dem Dictionary nicht vorhanden ist.
Can you write Python code for it?

Max = {"name": "Max", "nachname": "Mustermann", "alter": 42}
Martha = {"name": "Martha", "nachname": "Musterfrau"}
print("Alter:")
print("Max:", Max.get("alter", 0))
print("Martha:", Martha.get("alter", 0))


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Alternativ können wir auch die set.difference() Methode benutzen.
Can you write Python code for it?

s1 = {1, 3, 4, 5, 2}
s2 = {4, 5}
differenz = s1.difference(s2)
print(differenz)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Alternativ können wir auch die set.intersection() Methode benutzen.
Can you write Python code for it?

# Schnittmenge zweier Mengen:
set1 = {1, 3, 4, 5, 2}
set2 = {5, 8, 1, 3, 7, 9}
schnittmenge = set1.intersection(set2)
print(schnittmenge)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Alternativ können wir auch die set.union() Methode benutzen.
Can you write Python code for it?

# Vereinigungsmenge zweier Mengen:
set1 = {1, 3, 4, 5, 2}
set2 = {5, 8, 1, 3, 7, 9}
vereinigung = set1.union(set2)
print(vereinigung)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Da uns die dir() Funktion eine Liste zurückgibt, können wir uns diese Methoden ausgeben lassen, indem wir die letzten 11 Elemente anzeigen:
Can you write Python code for it?


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Dadurch, dass wir über ein range Objekt iterieren können, können wir range() gut in einer for-Schleife benutzen.
Can you write Python code for it?


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Den Wert zu einem Schlüssel können wir setzen indem wir einem Schlüssel einen Wert zuweisen, existiert dieser Schlüssel bereits, wird sein Wert überschrieben.
Can you write Python code for it?

Max = {"name": "Max", "nachname": "Mustermann", "alter": 42}
Martha = {"name": "Martha", "nachname": "Musterfrau"}
Martha["alter"] = 23
print(Martha)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Der boolean True auf dem Index 1 wird hier also als 1 erkannt. Dieses Phänomen tritt allerdings nur mit 1 und True und 0 und False auf. Um dieses Problem zu umgehen nutzen wir im folgenden eine Liste mit anderen Elementen.
Can you write Python code for it?

liste = list("abracadabra")
print(liste)
print("Erstes Auftreten von 'a':", liste.index("a"))
print("Erstes Auftreten von 'b':", liste.index("b"))
print("Erstes Auftreten von 'c':", liste.index("c"))
print("Erstes Auftreten von 'd':", liste.index("d"))


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Die Vereinigungsmenge enthält alle Elemente, die in einer der Mengen enthalten sind.
Can you write Python code for it?

# Vereinigungsmenge zweier Mengen:
set1 = {1, 3, 4, 5, 2}
set2 = {5, 8, 1, 3, 7, 9}
vereinigung = set1 | set2
print(vereinigung)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Die len() Funktion liefert bei einem Dictionary die Anzahl an Schlüsseln wieder:
Can you write Python code for it?

Martha = {"name": "Martha", "nachname": "Musterfrau"}
print("Anzahl Schlüssel:", len(Martha))


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Ein Tuple lässt sich über die tuple() Funktion oder über runde Klammern () definieren. Die runden Klammern können wir allerdings meistens weglassen. Der Zugriff auf die Elemente funktioniert, wie bei Listen sowohl über den Index, als auch über Slicing.
Can you write Python code for it?

Tuple = tuple("abracadabra")
print(Tuple[4])
print(Tuple[0:5])


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Ein range Objekt kann auch benutzt werden um sehr große Zahlenreihen zu erzeugen, da die Zahlen erst berechnet werden, wenn sie benötigt werden.
Can you write Python code for it?


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Elemente entfernen
Um Elemente zu entfernen gibt es zwei Möglichkeiten. Die set.pop() Methode entfernt ein Element aus der Menge und gibt es dabei zurück. Die set.remove() Methode kann dafür benutzt werden, um Elemente anhand ihres Wertes aus der Menge zu entfernen.
Can you write Python code for it?

Set = {23, "foo", 42, "test", (1,2)}
element = Set.pop()
print(element)
print(Set)

Set = {23, "foo", 42, "test", (1,2)}
Set.remove("foo")
print(Set)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Elemente finden
Eventuell wollen wir wissen ob ein Element in unserer Liste enthalten ist, und wenn es in unserer Liste enthalten ist, wollen wir eventuell wissen an welcher Stelle oder wie oft.
Zuerst wollen wir lernen, wie wir mit dem Schlüsselwort in feststellen, ob ein Element in unserer Liste enthalten ist:
Can you write Python code for it?

liste = [0, True, 4.2, False, "spam", "egg", 42]
print("egg:", "egg" in liste)
print("ham:", "ham" in liste)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Elemente hinzufügen
Nach dem wir eine Menge erstellt haben, können wir mit der set.add() Methode Elemente hinzufügen.
Can you write Python code for it?

some_primes = {2, 3, 5, 7, 11, 13}
some_primes.add(17)
print(some_primes)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Elemente hinzufügen
Nachdem wir eine Liste erstellt haben, möchten gegebenenfalls auch Elemente hinzufügen. Dazu gibt es mehrere Möglichkeiten. Wir können mit Hilfe der list.append() Methode ein Element an unsere Liste hinten anhängen oder mit der list.insert() Methode ein Element an einem Index in unsere Liste einfügen, wobei die Elemente nach diesem Index nach hinten aufrücken.
Can you write Python code for it?

liste = [0, True, 4.2, "foo", False, "spam", "egg", 42]
print(liste)
liste.append(3.14)
print(liste)

liste = [0, True, 4.2, "foo", False, "spam", "egg", 42]
print(liste)
liste.insert(4, "test")
print(liste)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Genauso, wie beim Slicing können die Werte auch negativ sein.
Can you write Python code for it?

# von 0 bis -100 jede zweite Zahl:
r = range(0, -100, -2)
print(list(r))


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Mit der set.isdisjoint() Methode können wir testen ob zwei Mengen disjunkt sind. Zwei Mengen sind disjunkt, wenn ihre Schnittmenge leer ist.
Can you write Python code for it?


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Mit der set.issubset() und der set.issuperset() Methode können wir feststellen, ob eine Menge eine Teilmenge, beziehungsweise eine Obermenge einer anderen Menge ist. Eine Menge s1 ist Teilmenge einer Menge s2, wenn alle Elemente von s1 in der Menge s2 enthalten sind. s2 ist dann die Obermenge von s1.
Can you write Python code for it?

s1 = {1, 2, 3, 4, 5}
s2 = {1, 2}
print("Ist s2 eine Teilmenge von s1:")
print(s2.issubset(s1))
print("Ist s1 eine Obermenge von s2:")
print(s1.issuperset(s2))


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Möchten wir ein Dictionary mit Einträgen erstellen, können wir dies entweder durch die dict() Funktion erreichen, in der wir Schlüssel und Werte als Liste von Tuplen mit zwei Elementen übergeben, oder indem wir Schlüssel und Werte durch Doppelpunkte : getrennt in geschweiften Klammern {} als Literale definieren.
Can you write Python code for it?

dict1 = {"name": "Max", "nachname": "Mustermann", "alter": 42}
dict2 = dict([("name", "Martha"), ("nachname", "Musterfrau"), ("alter", 23)])
print(dict1)
print(dict2)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Natürlich kann man auch das in Schlüsselwort mit Dictionaries benutzen:
Can you write Python code for it?

Martha = {"name": "Martha", "nachname": "Musterfrau"}
print("name?", "name" in Martha)
print("alter?", "alter" in Martha)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Nun wollen wir ein Element, dessen Wert wir kennen aus der Liste entfernen. Dazu benutzen wir die list.remove() Methode. Diese entfernt das erste Auftreten des Wertes, den wir ihr geben, aus der Liste.
Can you write Python code for it?

liste = list("abracadabra")
print(liste)
liste.remove("a")
print(liste)
liste.remove("a")
print(liste)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Oben haben wir statt des del Schlüsselwortes die list.pop() Methode benutzt. Das hat den Vorteil, dass uns die list.pop() Methode das Element, welches wir aus der Liste entfernt haben, zurück gibt. Wenn wir der list.pop() keinen Index mitgeben, entfernt sie standardmäßig das letzte Element. Wenn wir der list.pop() Methode einen Index geben, entfernt sie das Element an diesem Index aus der Liste.
Can you write Python code for it?

liste = ["foo", "test", 23, "spam", "egg", 42]
print(liste)
element = liste.pop(3)
print(liste)
print("Entfernt:", element)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Scheinbar ist der integer 1 in der Liste enthalten, obwohl keiner der Einträge auf den ersten Blick danach aussieht. Also wird ein Element unserer Liste als 1 interpretiert oder ist == 1. Um rauszufinden an welcher Stelle sich dieses Element befindet können wir die list.index() Methode benutzen. Dabei müssen wir allerdings vorsichtig sein, versuchen wir nämlich den Index eines Elementes zu finden, der nicht in der Liste enthalten ist, erhalten wir einen Fehler.
Can you write Python code for it?

liste = [0, True, 4.2, False, "spam", "egg", 42]
print("1:", 1 in liste)
ind = liste.index(1)
print(liste[ind])


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Strings
Jetzt da wir Listen und Tuple kennengelernt haben lohnt es sich, nochmal Strings anzuschauen, da wir auch hier auch auf einzelne Zeichen mit dem Index zugreifen können. So wie bei Listen und Tupeln, können wir auch bei Strings die str.count() und str.index() Methoden verwenden.
Can you write Python code for it?

zauberwort = "abracadabra"
print(zauberwort[0])
print(zauberwort[-1])
teilwort = zauberwort[:4]
print(teilwort)

zauberwort = "abracadabra"
zauberwort.count("a")

zauberwort = "abracadabra"
print(zauberwort.index("b"))

zauberwort = "abracadabra"
print("e?", "e" in zauberwort)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Um nicht nur einzelne Elemente, sondern mehrere Elemente an eine Menge anzuhängen, können wir die set.update() Methode benutzen.
Can you write Python code for it?

some_primes = {2, 3, 5, 7, 11, 13}
more_primes = [17, 19, 23]
some_primes.update(more_primes)
print(some_primes)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Wenn wir uns die Methoden von einem Tuple anschauen, stellen wir fest, dass es nur zwei "normale" Methoden gibt, die wir auch schon von der Liste kennen, nämlich tuple.count() und tuple.index(). Desweiteren können wir auf einen Tuple auch die len() Funktion und das Schlüsselwort in anwenden.
Can you write Python code for it?

dir(tuple)

Tuple = tuple("abracadabra")
print(Tuple)
print("Länge:", len(Tuple))
print("Anzahl 'a':", Tuple.count("a"))
print("Erstes 'b':", Tuple.index("b"))
print("e?", "e" in Tuple)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Wie wir sehen, können wir nicht nur einzelne Elemente einer Liste anhand ihres Indexes, sondern auch die gesamte Liste entfernen. Das Schlüsselwort del entfernt die Referenz einer Variable und somit die Variable, weshalb wir auch einen NameError erhalten, wenn wir versuchen die Variable zu benutzen, nachdem wir sie gelöscht haben.
Can you write Python code for it?

liste = ["foo", "test", 23, "spam", "egg", 42]
print(liste)
element = liste.pop()
print(liste)
print("Entfernt:", element)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Zugriff
Der Zugriff auf die Elemente erfolgt dann über den entsprechenden Schlüssel:
Can you write Python code for it?

Max = {"name": "Max", "nachname": "Mustermann", "alter": 42}
Martha = {"name": "Martha", "nachname": "Musterfrau", "alter": 23}
print("Alter:")
print("Max:", Max["alter"])
print("Martha:", Martha["alter"])


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
Zugriff auf Elemente
Auf die Elemente einer Liste wird über deren Index zugegriffen. Dieser ist ein integer startet beim ersten Element mit 0.
Can you write Python code for it?

liste = [0, True, 4.2, "foo"]
index = 0
length = len(liste)
while index < length:
    element = liste[index]
    print(index, element)
    index = index + 1


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
break, continue und else
Die Schlüsselwörter break, continue und else können wir innerhalb einer for-Schleife genauso benutzen, wie in einer while-Schleife.
Can you write Python code for it?

zauberwort = "abracadabra#test"
neuer_zauber = ""
for zeichen in zauberwort:
    if zeichen == "#":
        break
    elif zeichen == "a":
        continue
    else:
        neuer_zauber += zeichen
print(neuer_zauber)

string = "Das ist ein Teststring."
for zeichen in string:
    if zeichen == "Y":
        break
else:
    print("Kein 'Y' gefunden.")


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
dict
Ein Dictionary speichert Werte nicht anhand ihres Indexes, sondern anhand eines Schlüssels.
Erstellen eines dict
Ein leeres Dictionary kann auf zwei Arten erstellt werden:
Can you write Python code for it?


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
items(), keys() und values()
Die drei Methoden dict.items(), dict.keys() und dict.values() sind sich relativ ähnlich, weshalb wir sie zusammen betrachten wollen.
Can you write Python code for it?

dictionary = {0:"integer", True:"boolean", (0,0):"tuple", "s":"strings"}
print(dictionary.keys())  # liefert die Schlüssel als Liste
print(dictionary.values())  # liefert die Werte als Liste
print(dictionary.items())  # liefert Schlüssel und Werte als Tuple in einer Liste


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
list.copy()
Die list.copy() Methode kann benutzt werden um eine Kopie der Liste zu erstellen. Auch hier gibt es eine alternative Möglichkeit über Slicing, dasselbe zu erreichen.
Can you write Python code for it?

liste = list("abracadabra")
liste_copy = liste.copy()
print(liste)
print(liste_copy)

# Alternativ:
liste = list("abracadabra")
liste_copy = liste[:]
print(liste)
print(liste_copy)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
list.extend()
Die list.extend() Methode kann benutzt werden um an die bestehende Liste eine andere Liste anzuhängen.
Can you write Python code for it?

liste = list("abracadabra")
liste.extend("simsala")
print(liste)

# Alternativ:
liste = list("abracadabra")
liste = liste + list("simsala")
print(liste)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
list.reverse()
Mit der list.reverse() können wir eine Liste umdrehen. Wie auch die voherigen Methoden gibt es auch hier Alternativen.
Can you write Python code for it?

liste = list("abracadabra")
liste.reverse()
print(liste)

# Alternativ:
liste = list("abracadabra")
liste = liste[::-1]
print(liste)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
pop()
Auch Dictionaries besitzen eine dict.pop() Methode.
Can you write Python code for it?

dictionary = {0:"integer", True:"boolean", (0,0):"tuple", "s":"strings"}
value = dictionary.pop(0)
print(dictionary)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
range()
Die range() Funktion ist in vielerlei Hinsicht praktisch. Sie ermöglicht es uns auf einfache, gut lesbare Art und Weise Zahlenfolgen zu erzeugen. Warum das so praktisch ist werden wir gleich sehen.
python
range(stop)
range(start, stop[, step])
Wir können range() entweder nur mit einem stop Wert aufrufen (dieser muss ein integer sein), oder mit einem start, einem stop und einen optionalen step Wert. Bei beiden Varianten erhalten wir ein range Objekt.
Diese verhalten sich ähnlich wie die Werte beim Slicing. Geben wir keinen Wert für start an startet unser range Objekt bei 0, geben wir keinen Wert für step an, ist die Schrittweite 1.
Can you write Python code for it?

# alle Zahlen von 0 bis 10:
r = range(10)
print(list(r))

# jede zweite Zahl von 2 bis 42:
r = range(2, 42, 2)
print(list(r))


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
sets
Sets sind Mengen im mathematischen Sinn. Das bedeutet ein Element kann entweder in einer Menge enthalten sein, oder eben nicht.
Erstellen eines set
Ein Set kann entweder über die set() Funktion aus einem anderen Objekt erzeugt werden, oder über geschweifte Klammern {} welche die Literale eines Sets bilden.
Can you write Python code for it?

Set = set()
print(Set)

Set = {2,3,5,7}
print(Set)


I am working on the file "Level_03/Level_3.ipynb".
The first task is:
start, stop und step können allerdings auch weggelassen werden.
* Wird start weggelassen startet die Teilliste mit dem ersten Element.
* Wird stop weggelassen, endet die Teilliste mit dem letzten Element.
* wird step weggelassen, ist die Schrittweite 1
Can you write Python code for it?

liste = [0, True, 4.2, "foo", False, "spam", "egg", 42]
print(liste[2::2])  # von Index 2 bis zum Ende jedes zweite Element
print(liste[:-1:3])  # vom Start bis Index -1 jedes dritte Element
print(liste[::4])  # vom Start bis zum Ende jedes vierte Element
print(liste[1:])  # von Index 1 bis zum Ende


I am working on the file "Lexical Analysis.ipynb".
The first task is:

DATA ANALYSIS CODE (Statistics)
Can you write Python code for it?

from scipy import median
from scipy import mean
from scipy import var, std
import numpy as np

from source_code_analysis.models import SoftwareProject

projects = list()
projects.append(SoftwareProject.objects.get(name__iexact='CoffeeMaker', version__exact='1.0'))
projects.append(SoftwareProject.objects.get(name__iexact='Jfreechart', version__exact='0.6.0'))
projects.append(SoftwareProject.objects.get(name__iexact='Jfreechart', version__exact='0.7.1'))
projects.append(SoftwareProject.objects.get(name__iexact='JHotDraw', version__exact='7.4.1'))

print(projects)


I am working on the file "Lexical Analysis.ipynb".
The first task is:
DATA FETCHING CODE

SKIP this part if the Database already contains CodeLexiconInfo data

Analysis Code
LINSEN Normalizer
Can you write Python code for it?

from lexical_analysis import LINSENnormalizer


I am working on the file "Lexical Analysis.ipynb".
The first task is:
Import Django Model for Code Lexicon Information
Can you write Python code for it?

from source_code_analysis.models import CodeLexiconInfo


I am working on the file "Lexical Analysis.ipynb".
The first task is:
Jaccard Coefficient Statistics
Can you write Python code for it?

for project in projects:
    code_methods = project.code_methods.all()
    coefficients = list()
    for method in code_methods:
        # Check that this method has no "wrong_association"
        n_evaluations = method.agreement_evaluations.count()
        n_eval_wrong_assocation = method.agreement_evaluations.filter(wrong_association=True).count()
        if n_evaluations == n_eval_wrong_assocation:
            # if **all** the evaluations for the current method mark it as a wrong_association
            # exclude it from the statistics
            continue
        clexicon_info = method.lexical_info
        coefficients.append(clexicon_info.jaccard_coeff)
    coeff = np.array(coefficients)
    print('{proj} ({ver}) & {total} & {min:.3} & {max:.3} & {median:.3} & {mean:.3} & {variance:.3} & {devstd:.3} \\\\'.format(
                                                                             proj = project.name.title(), ver=project.version,
                                                                             total=coeff.size, min=coeff.min(), max=coeff.max(),
                                                                             median=median(coeff), mean=coeff.mean(),
                                                                             variance=var(coeff), devstd=std(coeff)))


I am working on the file "Lexical Analysis.ipynb".
The first task is:
Lexical Analyzer
Can you write Python code for it?

from lexical_analysis import LexicalAnalyzer

from source_code_analysis.models import SoftwareProject
target_sw_project = SoftwareProject.objects.get(name__iexact='CoffeeMaker')

# Use RelatedManager to get all the code methods associated to the target project
code_methods = target_sw_project.code_methods.all()

total_methods = code_methods.count()
coefficients = list()
for i, method in enumerate(code_methods):
    print('Analyzing Method {0} out of {1}: {2}'.format(i+1, total_methods, method.method_name))
    analyzer = LexicalAnalyzer(method)
    analyzer.analyse_textual_information()
    coefficients.append(analyzer.code_lexical_info.jaccard_coeff)


I am working on the file "Lexical Analysis.ipynb".
The first task is:
TFIDF Statistics separated by Agreement Rates
Can you write Python code for it?

from sklearn.feature_extraction.text import TfidfVectorizer
from evaluations import Judge

judges_combinations = (('leonardo.nole', 'rossella.linsalata'),
                       ('leonardo.nole', 'antonio.petrone'),
                       ('leonardo.nole', 'antonio.petrone'),
                       ('leonardo.nole', 'rossella.linsalata'),)

CODES_Labels = ('NC', 'DK', 'CO')
from collections import defaultdict
stats_results = defaultdict(list)

for pno, project in enumerate(projects):

    # Get Methods
    code_methods = project.code_methods.all()

    # Populate the Doc Collection
    document_collection = list()
    method_ids_map = dict()  # Map (dict) to store the association method.pk --> Row index in Tfidf Matrix
    for mno, method in enumerate(code_methods):
        clexicon_info = method.lexical_info
        document_collection.append(clexicon_info.normalized_comment)
        document_collection.append(clexicon_info.normalized_code)
        method_ids_map[method.id] = mno*2

    vectorizer = TfidfVectorizer(input='content', sublinear_tf=True, lowercase=False)
    tfidf_values = vectorizer.fit_transform(document_collection)

    j1_usrname, j2_usrname = judges_combinations[pno]
    j1 = Judge(j1_usrname, project.name, project.version)
    j2 = Judge(j2_usrname, project.name, project.version)

    j1_evals = j1.three_codes_evaluations
    j2_evals = j2.three_codes_evaluations

    project_stats = list()
    for code in range(3):
        j1_evals_code = j1_evals[code]
        j2_evals_code = j2_evals[code]

        method_ids = j1_evals_code.intersection(j2_evals_code)
        cosine_sim_vals = list()
        for mid in method_ids:
            i = method_ids_map[mid]
            cosine_sim_vals.append(tfidf_values[i].dot(tfidf_values[i+1].T)[0,0])

        cosine_sim_vals = np.array(cosine_sim_vals)
        project_stats.append(cosine_sim_vals)

    for code in range(3):
        vals = project_stats[code]
        label = CODES_Labels[code]
        if vals.size > 0:
           ...


I am working on the file "LiamLearn/K-fold_CV_F1_score.ipynb".
The first task is:
K fold cross-validation
Adapted from @LukasMosser code to fit python 3.5.
Doing a cross-validation on each well in order to see how each well perform as a blind text
Can you write Python code for it?

from sklearn import preprocessing
from sklearn import svm
from sklearn import metrics
#Create a set of unique well names

names = list(set(training_data["Well Name"]))

#Create a dicitionary of the well datasets, continued from original contest notebook
#But perform dropping for each well individually
#Maybe not necessary.

well_datas = {}
for name in names:
    well = training_data[training_data["Well Name"]==name]
    well_labels = well['Facies'].values.astype(np.int64)
    well = well.drop(['Formation', 'Well Name', 'Depth','Facies'], axis=1).values
    well_datas[name] = [well, well_labels]

X_data = {}
y_data = {}
for name, (data, labels) in well_datas.items():
    y_data[name] = np.array(labels, dtype=np.int64)
    X_data[name] = np.array(data, dtype=np.float32)

training_sets = []
test_sets = []

for i in range(len(names)):
    X_train = []
    y_train = []

    X_test = []
    y_test = []

    for name, data in X_data.items():
        if name is not names[i]:
            for row in data:
                X_train.append(row)
        else:
            for row in data:
                X_test.append(row)

    for name, labels in y_data.items():
        if name is not names[i]:
            for val in labels:
                y_train.append(val)
        else:
            for val in labels:
                y_test.append(val)

    X_train = np.array(X_train, dtype=np.float32)
    y_train = np.array(y_train, dtype=np.int64).reshape(len(y_train), 1)
    y_train = y_train.ravel()

    scaler = preprocessing.StandardScaler().fit(X_train)
    X_train = scaler.transform(X_train)

    X_test = np.array(X_test, dtype=np.float32)
    X_test = scaler.transform(X_test)

    y_test = np.array(y_test, dtype=np.int32)
    training_sets.append([X_train, y_train, X_test, y_test])

#Use as follows:
scores = []
for i, (X_train, y_train, X_test, y_test) in enumerate(training_sets):
    clf = svm.LinearSVC(class_weight='balanced', tol=1e-03, random_state=42, C=10)
    clf.fit(X_train, y_train)
    y_pred =...


I am working on the file "LiamLearn/K-fold_CV_F1_score__MATT.ipynb".
The first task is:
Isolate X and y:
Can you write Python code for it?

X = training_data.drop(['Formation', 'Well Name', 'Depth','Facies'], axis=1).values
y = training_data['Facies'].values


I am working on the file "LibraryEditor/Bruker_LibraryEditor_Export_Parser.ipynb".
The first task is:
Load modules and define functions.
Can you write Python code for it?

import re
import codecs
import json

def dpstr2dict(filename, data_points_string, meta_count):
    data_points = {}
    points = data_points_string.strip().split()
    count = len(points)
    if (count / 2) != int(meta_count):
        print "Could not convert string to dict! Data point mismatch in spectrum: " + filename
        return data_points_string # preserve original data
    for i in xrange(0, count, 2):
        data_points[float(points[i])] = int(points[i + 1])
    #print (meta_count)
    #print len(data_points)
    return data_points

def readspectrum(filename, filecontent):
    spectrum = {'SpecFile': filename, 'Comment': ''}
    #spectrum = {}
    values = ""
    for line in filecontent.splitlines():
        contents = line.split(':')
        if len(contents) == 2:
            key, value = contents
            spectrum[key.strip()] = value.strip()
        # 'Date', 'AnalName' and probably comments have multiple ':'
        elif len(contents) > 2:
            key = contents[0]
            value = ':'.join(contents[1:])
            spectrum[key.strip()] = value.strip()
        # spectra do not contain ":"
        else:
            values += contents[0]
    #print spectrum
    values = dpstr2dict(filename, values, spectrum['Num Peaks'])
    spectrum['Values'] = values
    return spectrum


I am working on the file "LibraryEditor/Library_Spectra_Export_process_results.ipynb".
The first task is:
Load modules and define functions.
Can you write Python code for it?

import sys
import os.path
import codecs
import json

def dpstr2dict(filename, data_points_string, meta_count):
    data_points = {} # using a dict to store the spectrum
                     # TODO: maybe use numpy ndarray instead
    points = data_points_string.strip().split()
    count = len(points)
    if (count / 2) != int(meta_count):
        print "Could not convert string to dict! Data point mismatch in spectrum: " + filename
        return data_points_string # preserve original data
    for i in xrange(0, count, 2):
        data_points[float(points[i])] = int(points[i + 1])
    #print (meta_count)
    #print len(data_points)
    return data_points

def readspectrum(filename, filecontent):
    spectrum = {'SpecFile': filename}
    values = ""
    for line in filecontent.splitlines():
        contents = line.split(':')
        if len(contents) == 2:
            key, value = contents
            spectrum[key.strip()] = value.strip()
        # 'Date', 'AnalName' and probably comments have multiple ':'
        elif len(contents) > 2:
            key = contents[0]
            value = ':'.join(contents[1:])
            spectrum[key.strip()] = value.strip()
        # spectra do not contain ":"
        else:
            values += contents[0]
    values = dpstr2dict(filename, values, spectrum['Num Peaks'])
    spectrum['Values'] = values
    return spectrum


I am working on the file "Librosa tutorial.ipynb".
The first task is:
A basic spectrogram display
Can you write Python code for it?

plt.figure()
librosa.display.specshow(melspec, y_axis='mel', x_axis='time')
plt.colorbar()


I am working on the file "Librosa tutorial.ipynb".
The first task is:
Beats can be used to downsample features
Can you write Python code for it?

chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
chroma_sync = librosa.feature.sync(chroma, beats)

plt.figure(figsize=(6, 3))
plt.subplot(2, 1, 1)
librosa.display.specshow(chroma, y_axis='chroma')
plt.ylabel('Full resolution')
plt.subplot(2, 1, 2)
librosa.display.specshow(chroma_sync, y_axis='chroma')
plt.ylabel('Beat sync')


I am working on the file "Librosa tutorial.ipynb".
The first task is:
But what's that in seconds?
Can you write Python code for it?


I am working on the file "Librosa tutorial.ipynb".
The first task is:
Documentation!
Librosa has extensive documentation with examples.
When in doubt, go to http://librosa.github.io/librosa/
Conventions

All data are basic numpy types
Audio buffers are called y
Sampling rate is called sr
The last axis is time-like:
        y[1000] is the 1001st sample
        S[:, 100] is the 101st frame of S
Defaults sr=22050, hop_length=512

Roadmap for today

librosa.core
librosa.feature
librosa.display
librosa.beat
librosa.segment
librosa.decompose

librosa.core

Low-level audio processes
Unit conversion
Time-frequency representations

To load a signal at its native sampling rate, use sr=None
Can you write Python code for it?

y_orig, sr_orig = librosa.load(librosa.util.example_audio_file(),
                     sr=None)
print(len(y_orig), sr_orig)


I am working on the file "Librosa tutorial.ipynb".
The first task is:
Exercise 0

Load a different audio file
Compute its STFT with a different hop length
Can you write Python code for it?

# Exercise 0 solution

y2, sr2 = librosa.load(   )

D = librosa.stft(y2, hop_length=   )


I am working on the file "Librosa tutorial.ipynb".
The first task is:
Exercise 1

Pick a feature extractor from the librosa.feature submodule and plot the output with librosa.display.specshow

Bonus: Customize the plot using either specshow arguments or pyplot functions
Can you write Python code for it?

# Exercise 1 solution

X = librosa.feature.XX()

plt.figure()

librosa.display.specshow(    )


I am working on the file "Librosa tutorial.ipynb".
The first task is:
Exercise 2

Plot a recurrence matrix using different  features
Bonus: Use a custom distance metric
Can you write Python code for it?


I am working on the file "Librosa tutorial.ipynb".
The first task is:
NMF is pretty easy also!
Can you write Python code for it?

# Fit the model
W, H = librosa.decompose.decompose(S, n_components=16, sort=True)

plt.figure(figsize=(6, 3))
plt.subplot(1, 2, 1), plt.title('W')
librosa.display.specshow(librosa.logamplitude(W**2), y_axis='log')
plt.subplot(1, 2, 2), plt.title('H')
librosa.display.specshow(H, x_axis='time')

# Reconstruct the signal using only the first component
S_rec = W[:, :1].dot(H[:1, :])

y_rec = librosa.istft(S_rec * phase)

Audio(data=y_rec, rate=sr)


I am working on the file "Librosa tutorial.ipynb".
The first task is:
Resampling is easy
Can you write Python code for it?

sr = 22050

y = librosa.resample(y_orig, sr_orig, sr)

print(len(y), sr)


I am working on the file "Librosa tutorial.ipynb".
The first task is:
Spectral representations
Short-time Fourier transform underlies most analysis.
librosa.stft returns a complex matrix D.
D[f, t] is the FFT value at frequency f, time (frame) t.
Can you write Python code for it?

D = librosa.stft(y)
print(D.shape, D.dtype)


I am working on the file "Librosa tutorial.ipynb".
The first task is:
We can include affinity weights for each link as well.
Can you write Python code for it?

R2 = librosa.segment.recurrence_matrix(chroma_sync,
                                       mode='affinity',
                                       sym=True)

plt.figure(figsize=(5, 4))
librosa.display.specshow(R2)
plt.colorbar()


I am working on the file "Librosa tutorial.ipynb".
The first task is:
librosa.beat

Beat tracking and tempo estimation

The beat tracker returns the estimated tempo and beat positions (measured in frames)
Can you write Python code for it?

tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
print(tempo)
print(beats)


I am working on the file "Librosa tutorial.ipynb".
The first task is:
librosa.display

Plotting routines for spectra and waveforms

Note: major overhaul coming in 0.5
Can you write Python code for it?

# Displays are built with matplotlib
import matplotlib.pyplot as plt

# Let's make plots pretty
import matplotlib.style as ms
ms.use('seaborn-muted')

# Render figures interactively in the notebook
%matplotlib nbagg

# IPython gives us an audio widget for playback
from IPython.display import Audio


I am working on the file "Lifetime curve fitting.ipynb".
The first task is:
Find the best function for all campaigns
Can you write Python code for it?

days_revenue = np.array([0 for i in xrange(max( [len(c['revenue']) for c in campaigns]))])
days_counts = np.array([0 for i in xrange(len(days_revenue))])
days_index = np.array([i+1 for i in xrange(len(days_revenue))])

for c in campaigns:
    for i, dr in enumerate(c.get('revenue')):
        days_revenue[i]+=dr
        days_counts[i]+=1
avg_days_revenue = days_revenue.cumsum() / days_counts

x = days_index
y = avg_days_revenue

scores = fit_data(x,y)
best = sorted(scores, key=lambda x: x['r2'], reverse=True)[0]
print "The best fit has %s curve with R^2 = %.2f" % ( best['function'], best['r2'] )

y_est = getattr(sys.modules[__name__], "%s" % best['function'])(x, *best['coefs'])

plt.figure()
plt.plot(x, y, 'bo', label="Cummulative campaign revenue")
plt.plot(x, y_est, 'r-', label="Estimation by " + best['function'])
plt.legend(loc='upper center')
plt.rcParams["figure.figsize"] = [12,5]
plt.show()


I am working on the file "Lifetime curve fitting.ipynb".
The first task is:
Fit campaigns to the function
Can you write Python code for it?

xx = np.array([i+1 for i in xrange(predict_days)])

for c in campaigns:
    y = np.array(c['revenue']).cumsum()
    x = np.array([i+1 for i in xrange(len(y))])

    score = fit_fn(x,y, best['function'])
    y_est = getattr(sys.modules[__name__], "%s" % score['function'])(x, *score['coefs'])
    yy_est = getattr(sys.modules[__name__], "%s" % score['function'])(xx, *score['coefs'])

    plt.figure()
    plt.rcParams["figure.figsize"] = [12,5]
    plt.plot(x, y, 'bo', label="Original" + c['name'])
    plt.plot(xx, yy_est, 'r-', label="Curve " + score['function'])
    plt.legend(loc='upper center')
    plt.show()

    print "Predicted revenue for campaign %s on %dth day is %.2f€ and costs were %.2f€" % (
        c['name'],expected_days, yy_est[expected_days], c['costs'])


I am working on the file "Lifetime curve fitting.ipynb".
The first task is:
Input parameters
Can you write Python code for it?


I am working on the file "Light Git index generator.ipynb".
The first task is:
For each repository in the settings file, let's get its data, create a summary object with the desired information and upload data to the ES server using ES bulk API.
Can you write Python code for it?

for repo_url in settings['git']:

    repo_name = repo_url.split('/')[-1]
    repo = Git(uri=repo_url, gitpath='/tmp/'+repo_name)

    utils.logging.info('Go for {}'.format(repo_name))

    items = []
    bulk_size = 10000

    for commit in repo.fetch():

        author_name = commit['data']['Author'].split('<')[0][:-1]
        author_domain = commit['data']['Author'].split('@')[-1][:-1]

        for file in commit['data']['files']:
            if 'added' not in file.keys() or file['added'] == '-':
                file['added'] = 0
            if 'removed' not in file.keys() or file['removed'] == '-':
                file['removed'] = 0

            summary = {
                'date': commit['data']['AuthorDate'],
                'commit': commit['data']['commit'],
                'author': author_name,
                'domain': author_domain,
                'file': file['file'],
                'added': file['added'],
                'removed': file['removed'],
                'repository': repo_name
            }

            items.append({'_index': index_name, '_type': 'item', '_source': summary})

            if len(items) > bulk_size:
                utils.helpers.bulk(es, items)
                items = []
                utils.logging.info('{} items uploaded'.format(bulk_size))

    if len(items) != 0:
        utils.helpers.bulk(es, items)
        utils.logging.info('Remaining {} items uploaded'.format(len(items)))


I am working on the file "Light Git index generator.ipynb".
The first task is:
Let's define an ES index mapping for the data that will be uploaded to the ES server
Can you write Python code for it?

MAPPING_GIT = {
    "mappings": {
        "item": {
            "properties": {
                "date": {
                    "type": "date",
                    "format" : "E MMM d HH:mm:ss yyyy Z",
                    "locale" : "US"
                },
                "commit": {"type": "keyword"},
                "author": {"type": "keyword"},
                "domain": {"type": "keyword"},
                "file": {"type": "keyword"},
                "added": {"type": "integer"},
                "removed": {"type": "integer"},
                "repository": {"type": "keyword"}
            }
        }
    }
}


I am working on the file "Light Git index generator.ipynb".
The first task is:
Let's give a name to the index to be created, and create it.
Note: utils.create_ES_index() removes any existing index with the given name before creating it
Can you write Python code for it?

index_name = 'git'
utils.create_ES_index(es, index_name, MAPPING_GIT)


I am working on the file "Light Git index generator.ipynb".
The first task is:
Let's import the git backend from Perceval
Can you write Python code for it?

from perceval.backends.core.git import Git


I am working on the file "Light Github index generator.ipynb".
The first task is:
Let's give a name to the indexes and create them in the ES server. Take care utils.create_ES_index() deletes any existing index with the same name before creating it.
Can you write Python code for it?

index_name_git = 'github-git'
utils.create_ES_index(es, index_name_git, utils.MAPPING_GITHUB_GIT)
index_name_github_issues = 'github-issues'
utils.create_ES_index(es, index_name_github_issues, utils.MAPPING_GITHUB_ISSUES)


I am working on the file "Light Github index generator.ipynb".
The first task is:
Let's import needed backends from Perceval
Can you write Python code for it?

from perceval.backends.core.git import Git
from perceval.backends.core.github import GitHub


I am working on the file "Light data with Google Science Journal.ipynb".
The first task is:
Let's have a quick peek at the data, it's always a good idea to do this, to know how to best load it:
Can you write Python code for it?

fname = "Untitled Experiment Trial 1.csv"
!head "$fname"


I am working on the file "Light data with Google Science Journal.ipynb".
The first task is:
Now let's get some quick summary statistics on the data:
Can you write Python code for it?


I am working on the file "Light data with Google Science Journal.ipynb".
The first task is:
OK, the timestamps look like miliseconds from the epoch.
For convenience, we'll subtract the first timestamp from all of them to get 0-offset data (basically setting our "laboratory clock" at $t=0$ for data collection).  This is done by the tc function below, applied to column 0 in converters.
We can also ask Pandas to use the time directly as our data index (index_col=0) and we'll name the columns ourselves, by providing the column names and asking it to skip the header (header=0):
Can you write Python code for it?

tc = lambda x: int(x)-1463893627134
df = pd.read_csv(fname, index_col=0, converters={0:tc}, names=["time", "lux"], header=0)
df.head()


I am working on the file "Light data with Google Science Journal.ipynb".
The first task is:
This already gives us more detail that Google does (cf screenshot above), as we have more precise min/max/average values, as well as extra statistics.
We can also plot the data, but because of the sharp variation in the intensity, the linear scale provided by the app isn't too informative, a log y scale will be much more useful:
Can you write Python code for it?


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Access data in grids (1D and 2D)

Access to data in grids is a slightly different process
There are two types of data grids
1D and 2D

When accessing grid data, we need to use the two optional arguments in the DbGet() and DbSet() functions. Typically we omit these arguments for general data access

Note that LTPython project, described later in this presentation provides more flexible data access methods. This is an illustration of barebone script code
Here's an example of getting the spectral distribution from a receiver
Can you write Python code for it?

#Get the spectral power distribution from a receiver (1D grids)
key="receiver[1].spectral_distribution[1]"
cellcount=int(lt0.DbGet(key,"Count"))
print("Number of rows: " + str(cellcount))
w=np.zeros((cellcount))
p=np.zeros((cellcount))
for i in range(1,cellcount+1,1):
    w[i-1],stat=lt0.DbGet(key,"Wavelength_At",0,i,1) #data returned is a tuple!
    p[i-1],stat=lt0.DbGet(key,"Power_At",0,i,1)

plt.plot(w,p,'-r')


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Access to ray path data

Consider the following system, where three sources are used to illuminate a dummy plane
Assume we want to see ray paths going through the cylinder object
Can you write Python code for it?

#Let's get a screenshot of the full system
viewname='1'
im,imname=ltd.GetViewImage(viewname)
plt.imshow(im)


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Accessing JumpStart Functions

JumpStart library is a set of helper functions available for macro users
These functions attempt to simplify the syntax/usage so that you can write macros faster!

LTCOM64 includes all JumpStart functions
This means you can access both LightTools API (that we looked at so far) and JumpStart functions using a single reference library

The example below shows how to create a handle to JumpStart functions
Can you write Python code for it?

from LTCOM64 import JSNET2
js=JSNET2()
#If PID capabilities (for multiple LightTools sessions) needed, use the PID for the session you want
#js.LTPID=12040
js.UpdateLTPointer


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Add the dummy and NSRay
Can you write Python code for it?

#Add a NSRay
lt0.Cmd("NSRayAim xyz 0,10,0 xyz 0,0,0")
#Add a dummy plane
lt0.Cmd("DummyPlane xyz 0,0,-20 xyz 0,0,-40")


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Add the mirror, set the optical property and orientation
Can you write Python code for it?

mirrorname="myMirror"
js.MakeTube(0.25,10,10,"R",mirrorname)
key="SOLID[@Last].SURFACE[LeftSurface].ZONE[1]"
lt0.DbSet(key,"PropertyName",op)
#Set the orientation, Alpha=45
key="Solid[@Last]"
lt0.DbSet(key,"Alpha",-45)


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Another function to apply variable values

Note that we do not skip disabled variables!
Can you write Python code for it?

def setVarVals(v):
    v=np.asarray(v)
    vlist=lt0.DbList('Lens_Manager[1]','Opt_DBVariable')
    vcount=lt0.ListSize(vlist)
    lt0.SetOption('DbUpdate',0)
    for i in range(1,vcount+1):
        vkey=lt0.ListAtPos(vlist,i)
        lt0.DbSet(vkey,'CurrentValue',float(v[i-1]))
        print('Variable Value: ' + str(v[i-1]))
    lt0.SetOption('DbUpdate',1)
    lt0.ListDelete(vlist)


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Creating a simple model for a parameter study

Make a block, set positon/orientation
Change one surface to a "Smooth/specular Mirror"
Add a single NSRay
Add a dummy plane to capture the reflected ray
Can you write Python code for it?

#First, let's create a simple function to add a new optical property
#This will create a new property, and return the name
def AddNewProperty(propname):
    lt0.Cmd("\O" + lt0.Str("PROPERTY_MANAGER[1]"))
    lt0.Cmd("AddNew=")
    lt0.Cmd("\Q")
    lt0.DbSet("Property[@Last]", "Name", propname)
    return 0

op="myMirror"
AddNewProperty(op)
key="PROPERTY[" + op + "]"
lt0.DbSet(key,"Simple Type","Mirror")


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Examples of capturing screenshots
Can you write Python code for it?

#We need to save the screenshot as an image file in the work directory
#LTUtilities module handles the work directory and file IO
import LTUtilities as ltu
ltu.lt0=lt0
ltd.ltu=ltu
#check the workdir
wd=ltu.checkpyWorkDir()
print(ltu.workdirstr) # this is where image files are saved

#Get a screenshot of the 3D View
viewname='3d'
im,imname=ltd.GetViewImage(viewname)
plt.imshow(im)

#Get a screenshot of an open chart view
#Usually, V3D is the first view. The '3' below indicates the second chart view currently open
viewname='3'
im,imname=ltd.GetViewImage(viewname)
plt.imshow(im)


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Finally, we call the minimize function with arguments

We need to pass the initial variable values to the minimize
For convenience, we can read the values from LightTools rather than hard coding
Make sure to save the original values since we will modify them during optimization
Can you write Python code for it?

# Here's a sample list of optimization algorithms we can try
# Some of these algorithms require 'jac', which is the Jacobian (gradiant), and it's not shown here
# The Nelder-Mead is the best option to try first, given its simplicity
optengines=['Nelder-Mead','BFGS','powell','Newton-CG','SLSQP','TNC']
vlist=lt0.DbList('Lens_Manager[1]','Opt_DBVariable')
vcount=int(lt0.ListSize(vlist))
lt0.ListDelete(vlist)
v0=np.zeros((vcount))
for i in range(1,vcount+1):
    v0[i-1]=lt0.DbGet('OPT_DBVARIABLE[' +str(i) +']','CurrentValue')

# Note that 'maxiter' should be small (e.g. 5) for other algorithms, except 'Nelder-Mead'
res=minimize(ApplyVarsReturnMF,v0,method=optengines[0],options={'disp': True,'maxiter':50})


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Here's an example of getting mesh data from a receiver

This example shows how to access individual cell values
Typically, you can use the GetMeshData() function described later in this document to get the data for a given mesh in a single call

Note that LTPython project, described later in this presentation provides more flexible data access methods. This is an illustration of barebone script code
Can you write Python code for it?

#Get the mesh data one cell at a time (this is a 2D grid)
# Note that a faster method for mesh data is described below
key="receiver[1].Mesh[1]"
xdim=int(lt0.DbGet(key,"X_Dimension")) #Columns
ydim=int(lt0.DbGet(key,"Y_Dimension")) #Rows
cv=np.zeros((ydim,xdim))
for i in range(1,xdim+1,1):
    for j in range(1,ydim+1):
        cv[j-1,i-1],stat=lt0.DbGet(key,"CellValue",0,i,j)

#Get the mesh bounds
MinX=lt0.DbGet(key,"Min_X_Bound")
MaxX=lt0.DbGet(key,"Max_X_Bound")
MinY=lt0.DbGet(key,"Min_Y_Bound")
MaxY=lt0.DbGet(key,"Max_Y_Bound")
#Create a data grid for plotting, and plot the data
xvec=np.linspace(MinX,MaxX,xdim+1)
yvec=np.linspace(MinY,MaxY,ydim+1)
X,Y=np.meshgrid(xvec,yvec)
plt.pcolormesh(X,Y,cv,cmap='jet')
plt.xlabel("X")
plt.ylabel("Y")
plt.axis("equal")
#See below for a simpler/faster method to access mesh data


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
How to use optimization algorithms from 'scipy'

Use of 'minimize' function
There are three key parts to setup an optimization problem
Initiate the minimize function
Use initial variable data
call the objective function

Apply variable values generated by the minimize to LightTools model
Evaluate the metrit function, return the merit function value

Import minimize from scipy library

We still need the libraries mentioned above in order to connect to LightTools, etc.
Import the LTCOM64 library and create a connection to the running LightTools session
Can you write Python code for it?

from scipy.optimize import minimize
import numpy as np
import matplotlib.pyplot as plt
import clr
#Initiate the connection with LightTools
clr.AddReference("C:\\Program Files\\Optical Research Associates\\LightTools 8.4.0\\Utilities.NET\\LTCOM64.dll")
from LTCOM64 import LTAPIx
lt0=LTAPIx()
lt0.UpdateLTPointer


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Import the resulting ray source using the local coordinate system on the lens surface

RaySource "C:/.../pyWorkDir/1mi8clam.txt" LXYZ 0,0,0 LXYZ 0,0,1 LXYZ 0,1,0

Note: rename the ray source with a meaningful name. The default name used is random
After the ray source is loaded into the model, intersection points can be visualized as a point cloud in the 3D model

Extra ray data for receiver filters

This data is not directly available with LTAPI4.GetMeshData()
Only way to access this data is the use DbGet() function for each ray
This means the process will be slower when there's a large number of rays on the receiver

Following example shows how to access optical path length for each ray

Optical Path Length filter is required on the receiver
Can you write Python code for it?

#Extra ray data, OPL
reckey='receiver[1]'
#Notice that the second argument is an Enum (integer) for the filter type
N,exdata=ltd.GetLTReceiverRays_Extra(reckey,ltd.ExtraRayData.Optical_Path_Length.value)
plt.hist(exdata,bins=21,color='green')
plt.xlabel('OPL')
plt.ylabel('Frequency')


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Now we are ready to change mirror and get the ray data
Can you write Python code for it?

key="Solid[1]"
segkey="NS_RAY[@Last].NS_SEGMENT[segment_2]"
numpts=11
datax=np.zeros((numpts,numpts))
datay=np.zeros((numpts,numpts))
alpha=np.linspace(-55,-35,11)
beta=np.linspace(-20,20,numpts)
for i in range(0,numpts,1):
    lt0.DbSet(key,"Alpha",float(alpha[i]))
    for j in range(0,11,1):
        lt0.DbSet(key,"Beta",float(beta[j]))
        datax[i,j]=lt0.DbGet(segkey,"Local_Surface_X")
        datay[i,j]=lt0.DbGet(segkey,"Local_Surface_Y")

plt.scatter(datax,datay)
plt.xlabel('X')
plt.ylabel('Y')


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Now we can create the objective function

'vardata' is what we get from minimize function
for example, if we setup 3 variables, we will get 3 values
Can you write Python code for it?

def ApplyVarsReturnMF(vardata):
    myd=np.asarray(vardata)
    setVarVals(myd)
    EvalMF()
    mfv=lt0.DbGet('OPT_MERITFUNCTIONS[1]','CurrentValue')
    print("MF Value: " + str(mfv))
    print('****')
    return mfv


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Our objective function, called by the minimize, should use the parameters sent from the minimize function

Update variables
Evaluate the merit function
Return the merit function value

First, a separate function to evaluate the merit function
Can you write Python code for it?

def EvalMF():
    lt0.Cmd("\O" + lt0.Str("OPT_MERITFUNCTIONS[1]"))
    lt0.Cmd("EvaluateAll=")
    lt0.Cmd("\Q")
    return 0


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Receiver rays based on Ray Ordinal Number

Every ray starts with an ordinal number, based on the ray sequence (1, 2, 3, etc.)
Diring ray trace, ordinal number does not change
Ordinal number can be used as a unique identifier when filtering ray data on receivers

Consider the following ray paths through a lens

One can isolate the ray paths using ray path analyzer or a macro approach discussed above
However, in this particular case, we want to obtan the ray intersection points on the lens surface

A receiver on the lens surface can give the ray intersection points for all rays, not just the ray path shown

If the ray ordinal numbers on the receiver attached to the dummy plane are known, then we can match those ray ordinal numbers to the subset of rays on the receiver attached to the lens surface
The simplest way to visualize ray intersection points as a point cloud is to generate a ray data source using the subset of rays, and importing that ray source using the local coordinate system on the lens surface
Can you write Python code for it?

#Assume default data, x, y, z, l, m, n, p
simdata='forward_sim_function[1]'
reckey1='receiver[1]' #receiver on the lens surface
reckey2='receiver[2]' #receiver on the dummy plane
n,rayfname=ltd.MakeRayFileUsingRayOrdinal(reckey1,DataAccessKey_Ordinal=reckey2)


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Running Spyder
Spyder provides a more versatile code environment with debug capabilities. For regular macro development work, this is the best environment
Typical Spyder environment will appear like this

How to load the test project into Spyder

Unzip the supplied LTPython.zip to your current working directory
This is usually C:/Users/YourUserName/

Run Spyder

Go to Project>Open Project.

Project files will appear like this

Test code to test most of the available functions are in "TestLTDataFunctions.py"
Most of the code is commented out. Make sure to uncomment the portions you like to try
Watch the attached video clip to see few examples
These are the different modules

LTData
This includes a set of functions to get/set database items, grid items, receiver data, ray path data, etc.

LTUtilities
This module contains some general purpose utilities, used by LTData and other modules

LTProperties
This is a special module to illustrate how to use JumpStart Optical Property functions
Notice that this module still uses COM. We will fix this issue. For now, this is the only way to access these JumpStart functions (fairly new to the JS library)
This module only contains "test code" that illustrates how to use the base functions in JS library

LTOpt
Few optimization examples. Use the attached test models for these examples

Ignore other modules
How to use win32COM client to connect to LightTools
Note that this is not a recommended method due to possible compatibility issues in the future!
Can you write Python code for it?

import win32com.client
import numpy as np
import matplotlib.pyplot as plt
#DbGet() and Mesh data example
lt = win32com.client.Dispatch("LightTools.LTAPI4")
XD=int(lt.DbGet(MeshKey,"X_Dimension"))
YD=int(lt.DbGet(MeshKey,"Y_Dimension"))
k=np.ones((XD,YD))
#The CellFilter may not work for all options in COM mode
[stat,myd,f]=lt.GetMeshData("receiver[1].Mesh[1]",list(k),"CellValue")
g=np.asarray(myd)
g=np.rot90(g)
x = np.linspace(-3, 3, XD)
y = np.linspace(-3, 3, XD)
X,Y = np.meshgrid(x, y)
plt.pcolor(X,Y,g)
plt.pcolormesh(X,Y,g,cmap="gray")
plt.xlabel("X")
plt.ylabel("Y")

#JumpStart library
js = win32com.client.Dispatch("LTCOM64.JSML")
js.MakeSphere(lt,5,"mySphere")
js.MoveVector(lt,"mySphere",0,10,10)
# js.MoveVector(lt,"mys*",0,10,10) will move all objects whose name starts with 'mys'


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Select, Copy, Boolean, Move

Make a cylinder
Subtract the cylinder from sphere
Move the resulting solid to XYZ 0,10,10

If you need more controls with images
Can you write Python code for it?

from IPython.display import Image
Image(filename = PATH + 'BooleanAndMove.PNG',width=500,height=100)

cmdstr="Cylinder " +lt0.Coord3(0,0,0) + " 3 15" #radius =3, length = 15
lt0.Cmd(cmdstr)
#Get the names of the objects. We have 2 objects
#Notice that we are using the "index" of each solid object
names=[]
for i in [1,2]:
    key="Solid[" + str(i) + "]"
    print("Current data key is: " + key) #so that we can see it
    names.append(lt0.DbGet(key, "Name"))
    print(names[i-1])

#Select two objects
lt0.Cmd("Select " + lt0.Str(names[0]) + " More " + lt0.Str(names[1]))
lt0.Cmd("Subtract")
#Resulting object has te name of the first selected object for boolean
lt0.Cmd("Select " + lt0.Str(names[0]))
lt0.Cmd("Move " + lt0.Coord3(0,10,10))


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Sending a message to LightTools

The message will appear in the Console Window, and the Macro Output tab
Can you write Python code for it?

lt0.Message("Hello from jupyter Notebook - 2!")


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Setting and getting data

Following example shows how to use DbSet() and DbGet() functions to access data
Set the radius of the sphere primitive to 10
Get the radius to test whether the "set" worked correctly
Can you write Python code for it?

#Set the radius to 10
key="Solid[@Last].Primitive[1]"
lt0.DbSet(key,"Radius",10)
r=lt0.DbGet(key,"Radius")
print("Radius of the sphere is: " + str(r))


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Several examples of getting and plotting receiver mesh and spectral data
Can you write Python code for it?

#First, import standard libraries we need for arrays/plotting
import matplotlib.pyplot as plt # general plotting
import numpy as np #additional support for arrays, etc.

#Plot a mesh
ltd.PlotRaster('receiver[1].mesh[1]','cellvalue',colormap='jet',
               xlabel='X-Value',ylabel='Y-Value',title='Mesh Data',plotsize=(5,5),plottype='2D')

#Plot the spectral distribution
numrows,spd=ltd.PlotSpectralDistribution('receiver[1].spectral_distribution[1]',returndata=True)
plt.plot(spd[:,0],spd[:,1])

#Plot true color data. Note the index=2 for the CIE mesh
r,g,b=ltd.PlotTrueColorRster('receiver[1].mesh[2]',plotsize=(5,5),returndata=True)


I am working on the file "LightTools_Data_Examples.ipynb".
The first task is:
Simple optimization example

Open 'Simple2VarOpt.1.lts'
X and Y coordinates of the NSRay are variables
Merit function is defined for X=0, Y=0 (local intersection coordinates on dummy plane)
When optimized, the ray should be placed at the origin of the dummy plane

Run the above code blocks in the sequential order to see the optimization process

Results will be printed below the last code block, where we invke the minimize function

Repeat the optimization for the following models

BezierSweptOpt.1.lts
Collimate a fan of rays using a collimator built with Swept geometry
The second profile of the Swept is 'Bezier', and we try to optimize Bezier parameters

Simple2VarOpt_Lens.1.lts
Focus a ray fan using a conic lens
The curvature and the conic constant are the variables

RayGrid_SplinePatch.1.lts
Start with a flat mirror, created with a splinepatch lens surface
Collimate the ray grid (i.e. perpendicular to the dummy plane)
This is a 9-variable problem and Nelder-Mead will require many iterations
Try 'powell' (or optengines[2])
res=minimize(ApplyVarsReturnMF,v0, method=optengines[2] ,options={'disp': True, 'maxiter':5})
Can you write Python code for it?


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
2. Photon Arrival Times
Often, you might have unbinned photon arrival times, rather than a light curve with time stamps and associated measurements. If this is the case, you can use the make_lightcurve method to turn these photon arrival times into a regularly binned light curve.
Can you write Python code for it?

arrivals = np.loadtxt("photon_arrivals.txt")
arrivals[:10]

lc_new = Lightcurve.make_lightcurve(arrivals, dt=1)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
A plot can also be customized using several keyword arguments.
Can you write Python code for it?

lc.plot(labels=('Time', "Counts"),  # (xlabel, ylabel)
        axis=(0, 1000, -50, 150),  # (xmin, xmax, ymin, ymax)
        title="Random generated lightcurve",
        marker='c:')  # c is for cyan and : is the marker style


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
A special case of splitting your light curve object is to split by GTIs. This can be helpful if you want to look at individual contiguous segments separately:
Can you write Python code for it?

# make a time array with a big gap and a small gap
time = np.arange(20)
counts = np.random.poisson(100, size=len(time))
gti = [(0,8), (12,20)]

lc = Lightcurve(time, counts, dt=1, skip_checks=True, gti=gti)

lc_split = lc.split_by_gti()

for lc_tmp in lc_split:
    print(lc_tmp.time)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Because I'd passed in GTIs that define the range from 0-8 and from 12-20 as good time intervals, the light curve will be split into two individual ones containing all data points falling within these ranges.
You can also apply the GTIs directly to the original light curve, which will filter time, counts, countrate, counts_err and countrate_err to only fall within the bounds of the GTIs:
Can you write Python code for it?

# make a time array with a big gap and a small gap
time = np.arange(20)
counts = np.random.poisson(100, size=len(time))
gti = [(0,8), (12,20)]

lc = Lightcurve(time, counts, dt=1, skip_checks=True, gti=gti)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Calculating a baseline
TODO: Need to document this method
Working with GTIs and Splitting Light Curves
It is possible to split light curves into multiple segments. In particular, it can be useful to split light curves with large gaps into individual contiguous segments without gaps.
Can you write Python code for it?

# make a time array with a big gap and a small gap
time = np.array([1, 2, 3, 10, 11, 12, 13, 14, 17, 18, 19, 20])
counts = np.random.poisson(100, size=len(time))

lc = Lightcurve(time, counts, skip_checks=True)

lc.gti


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Caution: This is one of the few methods that change the original state of the object, rather than returning a new copy of it with the changes applied! So any events falling outside of the range of the GTIs will be lost:
Can you write Python code for it?

# time array before applying GTIs:
lc.time

lc.apply_gtis()

# time array after applying GTIs
lc.time


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Create 1000 random Poisson-distributed counts:
Can you write Python code for it?

counts = np.random.poisson(100, size=len(times))
counts[:10]


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Error Distributions in stingray.Lightcurve
The instruments that record our data impose measurement noise on our measurements. Depending on the type of instrument, the statistical distribution of that noise can be different. stingray was originally developed with X-ray data in mind, where most data comes in the form of photon arrival times, which generate measurements distributed according to a Poisson distribution. By default, err_dist is assumed to Poisson, and this is the only statistical distribution currently fully supported. But you can put in your own errors (via counts_err or countrate_err). It'll produce a warning, and be aware that some of the statistical assumptions made about downstream products (e.g. the normalization of periodograms) may not be correct:
Can you write Python code for it?

times = np.arange(1000)

mean_flux = 100.0 # mean flux
std_flux = 2.0 # standard deviation on the flux

# generate fluxes with a Gaussian distribution and
# an array of associated uncertainties
flux = np.random.normal(loc=mean_flux, scale=std_flux, size=len(times))
flux_err = np.ones_like(flux) * std_flux

lc = Lightcurve(times, flux, err=flux_err, err_dist="gauss", dt=1.0, skip_checks=True)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Good Time Intervals
Lightcurve (and most other core stingray classes) support the use of Good Time Intervals (or GTIs), which denote the parts of an observation that are reliable for scientific purposes. Often, GTIs introduce gaps (e.g. where the instrument was off, or affected by solar flares). By default. GTIs are passed and don't apply to the data within a Lightcurve object, but become relevant in a number of circumstances, such as when generating Powerspectrum objects.
If no GTIs are given at instantiation of the Lightcurve class, an artificial GTI will be created spanning the entire length of the data set being passed in:
Can you write Python code for it?

times = np.arange(1000)
counts = np.random.poisson(100, size=len(times))

lc = Lightcurve(times, counts, dt=1, skip_checks=True)

lc.gti

print(times[0]) # first time stamp in the light curve
print(times[-1]) # last time stamp in the light curve
print(lc.gti) # the GTIs generated within Lightcurve

gti = [(0, 500), (600, 1000)]

lc = Lightcurve(times, counts, dt=1, skip_checks=True, gti=gti)

print(lc.gti)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Indexing
Count value at a particular time can be obtained using indexing.
Can you write Python code for it?


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Internally, both counts and countrate attribute will be defined no matter what the user passes in, since they're trivially converted between each other through a multiplication/division with `dt:
Can you write Python code for it?

print(mean_countrate)
print(lc.countrate[:10])

mean_counts = mean_countrate * dt
print(mean_counts)
print(lc.counts[:10])


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
MJDREF and Shifting Times
The mjdref keyword argument defines a reference time in Modified Julian Date. Often, X-ray missions count their internal time in seconds from a given reference date and time (so that numbers don't become arbitrarily large). The data is then in the format of Mission Elapsed Time (MET), or seconds since that reference time.
mjdref is generally passed into the Lightcurve object at instantiation, but it can be changed later:
Can you write Python code for it?

mjdref = 91254
time = np.arange(1000)
counts = np.random.poisson(100, size=len(time))

lc = Lightcurve(time, counts, dt=1, skip_checks=True, mjdref=mjdref)
print(lc.mjdref)

mjdref_new = 91254 + 20
lc_new = lc.change_mjdref(mjdref_new)
print(lc_new.mjdref)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Negation
A negation operation on the lightcurve object inverts the count array from positive to negative values.
Can you write Python code for it?

lc_neg = -lc

lc_sum = lc + lc_neg

np.all(lc_sum.counts == 0)  # All the points on lc and lc_neg cancel each other


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Note : By default, the start and stop parameters are assumed to be given as indices of the time array. However, the start and stop values can also be given as time values in the same value as the time array.
Can you write Python code for it?

lc_cut = lc_long.truncate(start=500, stop=1500, method='time')

lc_cut.time[0], lc_cut.time[-1]


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Note : See utils.savefig function for more options on saving a file.
Sample Data
Stingray also has a sample Lightcurve data which can be imported from within the library.
Can you write Python code for it?

from stingray import sampledata

lc = sampledata.sample_data()

lc.plot()


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Note that by default, stingray assumes that the user is passing a light curve in counts per bin. That is, the counts in bin $i$ will be the number of photons that arrived in the interval $t_i - 0.5\Delta t$ and $t_i + 0.5\Delta t$. Sometimes, data is given in count rate, i.e. the number of events that arrive within an interval of a second. The two will only be the same if the time resolution of the light curve is exactly 1 second.
Whether the input data is in counts per bin or in count rate can be toggled via the boolean input_counts keyword argument. By default, this argument is set to True, and the code assumes the light curve passed into the object is in counts/bin. By setting it to False, the user can pass in count rates:
Can you write Python code for it?

# times with a resolution of 0.1
dt = 0.1
times = np.arange(0, 100, dt)
times[:10]

mean_countrate = 100.0
countrate = np.random.poisson(mean_countrate, size=len(times))

lc = Lightcurve(times, counts=countrate, dt=dt, skip_checks=True, input_counts=False)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Note the warnings thrown by the syntax above. By default, stingray does a number of checks on the data that is put into the Lightcurve class. For example, it checks whether it's evenly sampled. It also computes the time resolution dt. All of these checks take time. If you know the time resolution, it's a good idea to put it in manually. If you know that your light curve is well-behaved (for example, because you know the data really well, or because you've generated it yourself, as we've done above), you can skip those checks and save a bit of time:
Can you write Python code for it?

dt = 1
lc = Lightcurve(times, counts, dt=dt, skip_checks=True)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
One useful feature is that you can explicitly pass in the start time and the duration of the observation. This can be helpful because the chance that a photon will arrive exactly at the start of the observation and the end of the observation is very small. In practice, when making multiple light curves from the same observation (e.g. individual light curves of multiple detectors, of for different energy ranges) this can lead to the creation of light curves with time bins that are slightly offset from one another. Here, passing in the total duration of the observation and the start time can be helpful.
Can you write Python code for it?

lc_new = Lightcurve.make_lightcurve(arrivals, dt=1.0, tstart=1.0, tseg=9.0)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Properties
A Lightcurve object has the following properties :

time : numpy array of time values
counts : numpy array of counts per bin values
counts_err: numpy array with the uncertainties on the values in counts
countrate : numpy array of counts per second
countrate_err: numpy array of the uncertainties on the values in countrate
n : Number of data points in the lightcurve
dt : Time resolution of the light curve
tseg : Total duration of the light curve
tstart : Start time of the light curve
meancounts: The mean counts of the light curve
meanrate: The mean count rate of the light curve
mjdref: MJD reference date (tstart / 86400 gives the date in MJD at the start of the observation)
gti:Good Time Intervals. They indicate the "safe" time intervals to be used during the analysis of the light curve.
err_dist: Statistic of the Lightcurve, it is used to calculate the uncertainties and other statistical values appropriately. It propagates to Spectrum classes
Can you write Python code for it?


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Re-binning
The time resolution (dt) can also be changed to a larger value.
Note : While the new resolution need not be an integer multiple of the previous time resolution, be aware that if it is not, the last bin will be cut off by the fraction left over by the integer division.
Can you write Python code for it?

lc_rebinned = lc_long.rebin(2)

print("Old time resolution = " + str(lc_long.dt))
print("Number of data points = " + str(lc_long.n))
print("New time resolution = " + str(lc_rebinned.dt))
print("Number of data points = " + str(lc_rebinned.n))


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Similarly, we can transform Lightcurve objects to and from astropy.TimeSeries objects:
Can you write Python code for it?

dt=1.0
time = np.arange(0, 100, dt)
counts = np.random.poisson(100, size=len(time))

lc = Lightcurve(time, counts, dt=dt, skip_checks=True)

# convet to astropy.TimeSeries object
ts = lc.to_astropy_timeseries()

type(ts)

ts[:10]


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
So we have time bins of 1 second time resolution, each with an average of 100 counts/bin. We require at least 2 time bins in each segment, and also a minimum number of total counts in the segment of 300. In theory, you'd expect to need 3 time bins (so 3-second segments) to satisfy the condition above. However, the Poisson distribution is quite variable, so we cannot guarantee that all bins will have a total number of counts above 300. Hence, our segments need to be 4 seconds long.
We can now use these segments to do some analysis, using the analyze_by_chunks method. In the simplest, case we can use a standard numpy operation to learn something about the properties of each segment:
Can you write Python code for it?

start_times, stop_times, lc_sums = lc.analyze_lc_chunks(chunk_length = 10.0, func=np.median)

lc_sums


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
The number of data points can be counted with the len function.
Can you write Python code for it?


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
The time bins and respective counts can be seen with lc.counts and lc.time
Can you write Python code for it?


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
This change only affects the reference time, not the values given in the time attribute. However, it is also possible to shift the entire light curve, along with its GTIs:
Can you write Python code for it?

gti = [(0,500), (600, 1000)]
lc.gti = gti

print("first three time bins: " + str(lc.time[:3]))
print("GTIs: " + str(lc.gti))

time_shift = 10.0
lc_shifted = lc.shift(time_shift)

print("Shifted first three time bins: " + str(lc_shifted.time[:3]))
print("Shifted GTIs: " + str(lc_shifted.gti))


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
This has split the light curve into three contiguous segments. You can adjust the tolerance for the size of gap that's acceptable via the min_gap attribute. You can also require a minimum number of data points in the output light curves. This is helpful when you're only interested in contiguous segments of a certain length:
Can you write Python code for it?

lc_split = lc.split(min_gap=6.0)

for lc_tmp in lc_split:
    print(lc_tmp.time)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
This light curve has uneven bins. It has a large gap between 3 and 10, and a smaller gap between 14 and 17. We can use the split method to split it into three contiguous segments:
Can you write Python code for it?

lc_split = lc.split(min_gap=2*lc.dt)

for lc_tmp in lc_split:
    print(lc_tmp.time)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
This splits the light curve into 10-second segments, and then finds the median number of counts/bin in each segment. For a flat light curve like the one we generated above, this isn't super interesting, but this method can be helpful for more complex analyses. Instead of np.median, you can also pass in your own function:
Can you write Python code for it?

def myfunc(lc):
    """
    Not a very interesting function
    """
    return np.sum(lc.counts) * 10.0

start_times, stop_times, lc_result = lc.analyze_lc_chunks(chunk_length=10.0, func=myfunc)

lc_result


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Truncation
A light curve can also be truncated.
Can you write Python code for it?

lc_cut = lc_long.truncate(start=0, stop=1000)

len(lc_cut)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
We'll get back to these when we talk more about some of the methods that apply GTIs to the data.
Operations
Addition/Subtraction
Two light curves can be summed up or subtracted from each other if they have same time arrays.
Can you write Python code for it?

lc = Lightcurve(times, counts, dt=1, skip_checks=True)
lc_rand = Lightcurve(np.arange(1000), [500]*1000, dt=1, skip_checks=True)

lc_sum = lc + lc_rand

print("Counts in light curve 1: " + str(lc.counts[:5]))
print("Counts in light curve 2: " + str(lc_rand.counts[:5]))
print("Counts in summed light curve: " + str(lc_sum.counts[:5]))


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
What if we only want the long segment?
Can you write Python code for it?

lc_split = lc.split(min_gap=6.0, min_points=4)

for lc_tmp in lc_split:
    print(lc_tmp.time)


I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
You can sort by the counts array using sort_counts method which changes time array accordingly:
Can you write Python code for it?

new_lc = lc_long[:]
new_lc = new_lc.sort_counts()
new_lc.counts[-1] == max(lc_long.counts)


#More General method
Q = 2000    #strength of the source-sheet,stb/d
h=25.26        #thickness of local gridblock,ft
phi=0.2        #porosity
kx=200         #pemerability in x direction,md
ky=200         #pemerability in y direction,md
kr=kx/ky       #pemerability ratio
miu=1          #viscosity,cp

#Line segment source parameters
L1=1                      #Line segment source length
alpha=30*numpy.pi/180     #Line segment angle from x direction, angle alpha in Fig.1

# computes the pressure-velcity field generated by the source-sheet
p_sheet1 = numpy.empty((N, N), dtype=float)
u_sheet1 = numpy.empty((N, N), dtype=float)
v_sheet1 = numpy.empty((N, N), dtype=float)
for i in range(N):
    for j in range(N):
        a=math.cos(alpha)**2+kr*math.sin(alpha)**2
        b=X_local[i,j]*math.cos(alpha)+kr*math.sin(alpha)*Y_local[i,j]
        c=Y_local[i,j]*math.cos(alpha)-X_local[i,j]*math.sin(alpha)
        dp=70.6*Q*miu/h/math.sqrt(kx*ky)
        dv=-0.4468*Q/h/phi*math.sqrt(kx/ky)

        p_sheet1[i,j] = dp/a*(
                             (
                              b*math.log(X_local[i,j]**2-2*b*L1+a*L1**2+kr*Y_local[i,j]**2)
                             -L1*a*math.log((X_local[i,j]-L1*math.cos(alpha))**2+kr*(Y_local[i,j]-L1*math.sin(alpha))**2)
                             +2*math.sqrt(kr)*c*math.atan((b-a*L1)/math.sqrt(kr)/c)
                             )
                             -
                             (
                               b*math.log(X_local[i,j]**2+kr*Y_local[i,j]**2)
                               +2*math.sqrt(kr)*c*math.atan((b)/math.sqrt(kr)/c)
                             )
                            )
        u_sheet1[i,j] = dv/a*(
                             (
                            math.cos(alpha)*math.log(X_local[i,j]**2-2*b*L1+a*L1**2+kr*Y_local[i,j]**2)+ 2*math.sqrt(kr)*math.sin(alpha)*math.atan((a*L1-b)/math.sqrt(kr)/c)
                             )
                            -
                             (
                           ...


I am working on the file "Line segment source.ipynb".
The first task is:
Line segment source integration
Line source solution for pressure and velocity (Datta-Gupta, 2007)
\begin{equation}
P(x,y)=B{{Q}{w}}=-\frac{70.60\mu }{h\sqrt{{{k}{x}}{{k}{y}}}}\ln \left{ {{(x-{{x}{w}})}^{2}}+\frac{{{k}{x}}}{{{k}{y}}}{{(y-{{y}{w}})}^{2}} \right}{{Q}{w}}+{{P}_{avg}}
\end{equation}
\begin{equation}
\frac{\partial P}{\partial x}=u=\frac{0.8936}{h\phi }\sqrt{\frac{{{k}{x}}}{{{k}{y}}}}\sum\limits_{k=1}^{{{N}{w}}}{{{Q}{k}}}\frac{x-{{x}{k}}}{{{\left( x-{{x}{k}} \right)}^{2}}+\frac{{{k}{x}}}{{{k}{y}}}{{(y-{{y}_{k}})}^{2}}}
\end{equation}
\begin{equation}
\frac{\partial P}{\partial y}=v=\frac{0.8936}{h\phi }\sqrt{\frac{{{k}{x}}}{{{k}{y}}}}\sum\limits_{k=1}^{{{N}{w}}}{{{Q}{k}}}\frac{y-{{y}{k}}}{{{\left( x-{{x}{k}} \right)}^{2}}+\frac{{{k}{x}}}{{{k}{y}}}{{(y-{{y}_{k}})}^{2}}}
\end{equation}
Local coordinate transformation

Figure 1. Nomenclature of the boundary element in the local coordinates
Based on the nomenclatures in Fig. 1, a boundary element could be determined as its start point (A), end point (B), length (lj) and inclination (αj). The coordinate transformation from global system to local system can be given as follows:
\begin{matrix}
   {x}'=x-{{x}{A}} & {y}'=y-{{y}{A}}  \
\end{matrix}
Where (xA,yA) is the location of start point (point A in Fig. A-1) of a BE in global coordinate system. Trigonometric sine and cosine function for a BE could be determined from start point (A) and end point (B) of the boundary elements, which can be expressed as follows:
\begin{matrix}
   \sin {{\alpha }{j}}=\frac{{{y}{B}}-{{y}{A}}}{{{l}{j}}} & \cos {{\alpha }{j}}=\frac{{{x}{B}}-{{x}{A}}}{{{l}{j}}}  \
\end{matrix}
In local coordinate system, line source are placed along the boundary element at a point (x’j,y’j). The location can be easily given as follows:
\begin{equation}
\begin{matrix}
   \begin{matrix}
   {{{{x}'}}{j}}=t\cos {{\alpha }{j}} & {{{{y}'}}{j}}=t\sin {{\alpha }{j}}  \
\end{matrix} & 0\le t  \
\end{matrix}\le {{l}_{j}}
\end{equation}
Can you write Python code for it?

#coordinate transformation
origin_new_x=0            # A point in Fig 1
origin_new_y=0

X_local=X-origin_new_x
Y_local=Y-origin_new_y


I am working on the file "Line segment source.ipynb".
The first task is:
Plot the results
Can you write Python code for it?

# plots the streamlines
%matplotlib inline

size = 8
pyplot.figure(figsize=(size, size-1))
pyplot.title('Streamline field')
pyplot.grid(True)
pyplot.xlabel('x', fontsize=16)
pyplot.ylabel('y', fontsize=16)
pyplot.xlim(x_start, x_end)
pyplot.ylim(y_start, y_end)
pyplot.plot((0+origin_new_x,L1*math.cos(alpha)+origin_new_x),(0+origin_new_y,L1*math.sin(alpha)+origin_new_y), color='#CD2305', linewidth=4) #red source line

#stream =pyplot.streamplot(X, Y, u, v, color=numpy.sqrt(u**2+v**2),cmap='jet',density=2, linewidth=1, arrowsize=1, arrowstyle='->') #streamline
stream =pyplot.streamplot(X, Y, u1, v1, color=numpy.sqrt(u1**2+v1**2),cmap='jet',density=2, linewidth=1, arrowsize=1, arrowstyle='->') #streamline

cbar=pyplot.colorbar(orientation='vertical')
equipotential=pyplot.contour(X, Y, p1, extend='both')

size = 8
pyplot.figure(figsize=(size, size-1))
pyplot.title('Velocity field')
pyplot.xlabel('x', fontsize=16)
pyplot.ylabel('y', fontsize=16)
pyplot.xlim(x_start, x_end)
pyplot.ylim(y_start, y_end)

Vtotal= numpy.sqrt(u1**2+v1**2)

pyplot.contour(X, Y, Vtotal, 10, linewidths=0.5, colors='k')
pyplot.contourf(X, Y, Vtotal, 10, cmap='rainbow')
pyplot.colorbar()  # draw colorbar


I am working on the file "LineSearch.ipynb".
The first task is:
We are interseted in optimization, so we don't want to find the root of our
function, but rather the "root" of the derivative as a potential minimum point.
Let's define our objectve function, its derivative, and solve for the minium.
Can you write Python code for it?

%matplotlib inline

import numpy as np
from math import pi
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')

def func(d):
    return 45*pi*d**2 + 17200.0/d

def deriv(d):
    return 90*pi*d - 17200.0/d**2

# choose starting interval
d1 = 1.0
d2 = 10.0

# evalaute function
g1 = deriv(d1)
g2 = deriv(d2)

# check that our bracket is ok
assert(g1*g2 < 0)

# find optimal point
size = []
dopt = bisection(d1, d2, g1, g2, deriv, size)

# plot function
dvec = np.linspace(d1, d2, 200)
plt.figure()
plt.plot(dvec, func(dvec)/1e3)
plt.plot(dopt, func(dopt)/1e3, 'r*', markersize=12)
plt.xlabel('diameter (m)')
plt.ylabel('cost (thousands of dollars)')

# plot convergence history (interval size)
plt.figure()
plt.semilogy(size)
plt.xlabel('iteration')
plt.ylabel('interval size')


I am working on the file "Line_chart.ipynb".
The first task is:
add a line chart, with the number of websites on y-axis and the years on x-axis
Can you write Python code for it?

    plt.plot(years, websites, color='blue', marker='o',
             linestyle='solid', linewidth= 2,)


I am working on the file "Line_chart.ipynb".
The first task is:
adjust the x and y axis range
Can you write Python code for it?

    plt.xlim(2000, 2015)
    plt.ylim(10, 1000)

    plt.title("Total number of websites online")

    plt.ylabel("Websites (millions)")

    plt.show()

if __name__ == "__main__":

    line_graph(plt)


I am working on the file "Line_chart.ipynb".
The first task is:
create a line chart to visualize the number of websites on the world wide web (data source: Internet Live Stats)
Can you write Python code for it?


I am working on the file "Linear Algebra.ipynb".
The first task is:
Compare speed python list vs numpy ops
Let's implement standard deviation function. And compare computation time for 10 million numbers.
Can you write Python code for it?

n = 10 ** 7

# Implementation using python list
def std(x:list):
    x_mean = sum(x)/len(x)
    y = sum([(v - x_mean) ** 2 for v in x])/len(x)
    return y**0.5

%time std(range(n))

# Implementation using numpy array function
def std_np(x):
    x_mean = np.sum(x)/len(x)
    return (((x - x_mean) ** 2).mean())** 0.5

%time std_np(np.arange(n))


I am working on the file "Linear Algebra.ipynb".
The first task is:
Covariance Matrix
Can you write Python code for it?

np.random.seed(1230)
X = np.random.ranf((5, 3))
X

n = X.shape[0]
X0 = X - np.mean(X, axis = 0)
(X0.T).dot(X0)/n

np.cov(X, ddof=0, rowvar=False)

np.var(X[:, 0])

np.cov(X[:,0], X[:,1], ddof=0)


I am working on the file "Linear Algebra.ipynb".
The first task is:
Eigen Value Decomposition
Read about Eigen, SVD, PCA decomposition https://www.cc.gatech.edu/~dellaert/pubs/svd-note.pdf
Can you write Python code for it?

cx = np.cov(X, rowvar=False)
cx

e, v = np.linalg.eig(cx)
e, v

Z = X - X.mean(axis=0)
Z

Z.mean(axis=0)

U, D, V = np.linalg.svd(Z)

U

D

V


I am working on the file "Linear Algebra.ipynb".
The first task is:
Matrix multiplication
Usecase - solve Normal Equations
http://mlwiki.org/index.php/Normal_Equation
Can you write Python code for it?

np.random.seed(1)
W = np.array([2.3, - 5.7, 8.9]).T
b = 1.2
X = np.random.random((10, 3))
y = np.dot(X, W)
print("W: ", W)

print("y: ", y)

W_estimate = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
W_estimate


I am working on the file "Linear Algebra.ipynb".
The first task is:
U and V are unitary matrix
Can you write Python code for it?


I am working on the file "Linear Algebra.ipynb".
The first task is:
Vectors of U and V are orthogonal
Can you write Python code for it?


I am working on the file "Linear Programming with OR-Tools.ipynb".
The first task is:
More simple problems
A company that operates 10 hours a day manufactures two products on three sequential processes. The following data characterizes the problem:
Can you write Python code for it?

import pandas as pd

problemdata = pd.DataFrame({'Process 1': [10, 5], 'Process 2':[6, 20], 'Process 3':[8, 10], 'Unit profit':[20, 30]})
problemdata.index = ['Product 1', 'Product 2']

problemdata


I am working on the file "Linear Programming with OR-Tools.ipynb".
The first task is:
Reddy Mikks model
Given the following variables:
$\begin{aligned}
x_1 = \textrm{Tons of exterior paint produced daily} \newline
x_2 = \textrm{Tons of interior paint produced daily}
\end{aligned}$
and knowing that we want to maximize the profit, where \$5000 is the profit from exterior paint and \$4000 is the profit from a ton of interior paint, the Reddy Mikks model is:
$$\textrm{Maximize  } z = 5x_1 + 4x_2$$
subject to
$$6x_1 + 4x_2 \le 24$$
$$x_1 + 2x_2 \le 6$$
$$-x_1 + x_2 \le 1$$
$$x_2 \le 2$$
$$x_1, x_2 \ge 0$$
Can you write Python code for it?

reddymikks = pywraplp.Solver('Reddy_Mikks', pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)

x1 = reddymikks.NumVar(0, reddymikks.infinity(), 'x1')
x2 = reddymikks.NumVar(0, reddymikks.infinity(), 'x2')

reddymikks.Add(6*x1 + 4*x2 <= 24)
reddymikks.Add(x1 + 2*x2 <= 6)
reddymikks.Add(-x1 + x2 <= 1)
reddymikks.Add(x2 <= 2)

profit = reddymikks.Objective()
profit.SetCoefficient(x1, 5)
profit.SetCoefficient(x2, 4)
profit.SetMaximization()

status = reddymikks.Solve()

if status not in [reddymikks.OPTIMAL, reddymikks.FEASIBLE]:
    raise Exception('No feasible solution found')

print("The company should produce",round(x1.solution_value(),2),"tons of exterior paint")
print("The company should produce",round(x2.solution_value(),2),"tons of interior paint")
print("The optimal profit is", profit.Value(), 'thousand USD')