updated
authorChristian Urban <urbanc@in.tum.de>
Tue, 20 Nov 2018 13:42:32 +0000
changeset 211 092e0879a5ae
parent 210 63a1376cbebd
child 212 4bda49ec24da
updated
testing2/danube.scala
testing2/danube_test.sh
testing2/danube_test1.scala
testing2/danube_test2.scala
testing2/docdiff.scala
testing2/docdiff_test.sh
testing2/docdiff_test1.scala
testing2/docdiff_test2.scala
testing2/docdiff_test3.scala
testing2/docdiff_test4.scala
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/danube.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,177 @@
+// Part 2 and 3 about Movie Recommendations 
+// at Danube.co.uk
+//===========================================
+
+import io.Source
+import scala.util._
+
+//object CW7b { // for purposes of generating a jar
+
+// (1) Implement the function get_csv_url which takes an url-string
+//     as argument and requests the corresponding file. The two urls
+//     of interest are ratings_url and movies_url, which correspond 
+//     to CSV-files.
+//     The function should ReTurn the CSV file appropriately broken
+//     up into lines, and the first line should be dropped (that is without
+//     the header of the CSV file). The result is a list of strings (lines
+//     in the file).
+
+def get_csv_url(url: String) : List[String] = {
+  val csv = Source.fromURL(url)("ISO-8859-1")
+  csv.mkString.split("\n").toList.drop(1)
+}
+
+val ratings_url = """https://nms.kcl.ac.uk/christian.urban/ratings.csv"""
+val movies_url = """https://nms.kcl.ac.uk/christian.urban/movies.csv"""
+
+// test cases
+
+//val ratings = get_csv_url(ratings_url)
+//val movies = get_csv_url(movies_url)
+
+//ratings.length  // 87313
+//movies.length   // 9742
+
+// (2) Implement two functions that process the CSV files. The ratings
+//     function filters out all ratings below 4 and ReTurns a list of 
+//     (userID, movieID) pairs. The movies function just ReTurns a list 
+//     of (movieId, title) pairs.
+
+
+def process_ratings(lines: List[String]) : List[(String, String)] = {
+  for (cols <- lines.map(_.split(",").toList); 
+       if (cols(2).toFloat >= 4)) yield (cols(0), cols(1))  
+}
+
+def process_movies(lines: List[String]) : List[(String, String)] = {
+  for (cols <- lines.map(_.split(",").toList)) yield (cols(0), cols(1))  
+}
+
+// test cases
+
+//val good_ratings = process_ratings(ratings)
+//val movie_names = process_movies(movies)
+
+//good_ratings.length   //48580
+//movie_names.length    // 9742
+
+//==============================================
+// Do not change anything below, unless you want 
+// to submit the file for the advanced part 3!
+//==============================================
+
+
+// (3) Implement a grouping function that calulates a map
+//     containing the userIds and all the corresponding recommendations 
+//     (list of movieIds). This  should be implemented in a tail
+//     recursive fashion, using a map m as accumulator. This map
+//     is set to Map() at the beginning of the claculation.
+
+def groupById(ratings: List[(String, String)], 
+              m: Map[String, List[String]]) : Map[String, List[String]] = ratings match {
+  case Nil => m
+  case (id, mov) :: rest => {
+    val old_ratings = m.getOrElse (id, Nil)
+    val new_ratings = m + (id -> (mov :: old_ratings))
+    groupById(rest, new_ratings)
+  }
+}
+
+// test cases
+//val ratings_map = groupById(good_ratings, Map())
+//val movies_map = movie_names.toMap
+
+//ratings_map.get("414").get.map(movies_map.get(_)) // most prolific recommender with 1227 positive ratings
+//ratings_map.get("474").get.map(movies_map.get(_)) // second-most prolific recommender with 787 positive ratings
+//ratings_map.get("214").get.map(movies_map.get(_)) // least prolific recommender with only 1 positive rating
+
+
+
+//(4) Implement a function that takes a ratings map and a movie_name as argument.
+// The function calculates all suggestions containing
+// the movie mov in its recommendations. It ReTurns a list of all these
+// recommendations (each of them is a list and needs to have mov deleted, 
+// otherwise it might happen we recommend the same movie).
+
+def favourites(m: Map[String, List[String]], mov: String) : List[List[String]] = 
+  (for (id <- m.keys.toList;
+        if m(id).contains(mov)) yield m(id).filter(_ != mov))
+
+
+
+// test cases
+// movie ID "912" -> Casablanca (1942)
+//          "858" -> Godfather
+//          "260" -> Star Wars: Episode IV - A New Hope (1977)
+
+//favourites(ratings_map, "912").length  // => 80
+
+// That means there are 80 users that recommend the movie with ID 912.
+// Of these 80  users, 55 gave a good rating to movie 858 and
+// 52 a good rating to movies 260, 318, 593.
+
+
+// (5) Implement a suggestions function which takes a rating
+// map and a movie_name as arguments. It calculates all the recommended
+// movies sorted according to the most frequently suggested movie(s) first.
+def suggestions(recs: Map[String, List[String]], 
+                    mov_name: String) : List[String] = {
+  val favs = favourites(recs, mov_name).flatten
+  val favs_counted = favs.groupBy(identity).mapValues(_.size).toList
+  val favs_sorted = favs_counted.sortBy(_._2).reverse
+  favs_sorted.map(_._1)
+}
+
+// test cases
+
+//suggestions(ratings_map, "912")
+//suggestions(ratings_map, "912").length  
+// => 4110 suggestions with List(858, 260, 318, 593, ...)
+//    being the most frequently suggested movies
+
+// (6) Implement recommendations functions which generates at most
+// *two* of the most frequently suggested movies. It Returns the 
+// actual movie names, not the movieIDs.
+
+def recommendations(recs: Map[String, List[String]],
+                   movs: Map[String, String],
+                   mov_name: String) : List[String] =
+  suggestions(recs, mov_name).take(2).map(movs.get(_).get)                 
+
+
+// testcases
+
+// recommendations(ratings_map, movies_map, "912")
+//   => List(Godfather, Star Wars: Episode IV - A NewHope (1977))
+
+//recommendations(ratings_map, movies_map, "260")
+//   => List(Star Wars: Episode V - The Empire Strikes Back (1980), 
+//           Star Wars: Episode VI - Return of the Jedi (1983))
+
+// recommendations(ratings_map, movies_map, "2")
+//   => List(Lion King, Jurassic Park (1993))
+
+// recommendations(ratings_map, movies_map, "0")
+//   => Nil
+
+// recommendations(ratings_map, movies_map, "1")
+//   => List(Shawshank Redemption, Forrest Gump (1994))
+
+// recommendations(ratings_map, movies_map, "4")
+//   => Nil  (there are three ratings fro this movie in ratings.csv but they are not positive)     
+
+
+// If you want to calculate the recomendations for all movies.
+// Will take a few seconds calculation time.
+
+//val all = for (name <- movie_names.map(_._1)) yield {
+//  recommendations(ratings_map, movies_map, name)
+//}
+
+// helper functions
+//List().take(2
+//List(1).take(2)
+//List(1,2).take(2)
+//List(1,2,3).take(2)
+
+//}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/danube_test.sh	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,99 @@
+#!/bin/bash
+
+# to make the script fail safely
+set -euo pipefail
+
+
+out=${1:-output}
+
+echo "" > $out
+
+echo "Below is the feedback for your submission danube.scala" >> $out
+echo "" >> $out
+
+
+# compilation tests
+
+function scala_compile {
+  (ulimit -t 30; JAVA_OPTS="-Xmx1g" scala "$1" 2>> $out 1>> $out) 
+}
+
+# functional tests
+
+function scala_assert {
+  (ulimit -t 30; JAVA_OPTS="-Xmx1g" scala -i "$1" "$2" -e "" 2> /dev/null 1> /dev/null)
+}
+
+# purity test
+
+function scala_vars {
+   (egrep '\bvar\b|\breturn\b|\.par|ListBuffer|mutable' "$1" 2> /dev/null 1> /dev/null)
+}
+
+
+# var, .par return, ListBuffer test
+#
+echo "danube.scala does not contain vars, returns etc?" >> $out
+
+if (scala_vars danube.scala)
+then
+  echo "  --> fail (make triple-sure your program conforms to the required format)" >> $out
+  tsts0=$(( 0 ))
+else
+  echo "  --> success" >> $out
+  tsts0=$(( 0 )) 
+fi
+
+### compilation test
+
+
+if  [ $tsts0 -eq 0 ]
+then 
+  echo "danube.scala runs?" >> $out
+
+  if (scala_compile danube.scala)
+  then
+    echo "  --> success" >> $out
+    tsts=$(( 0 ))
+  else
+    echo "  --> scala did not run danube.scala" >> $out
+    tsts=$(( 1 )) 
+  fi
+else
+  tsts=$(( 1 ))     
+fi
+
+### danube get_cvs_url tests
+
+if [ $tsts -eq 0 ]
+then
+  echo "danube.scala tests:" >> $out
+  echo "  val movies_url = \"\"\"https://nms.kcl.ac.uk/christian.urban/movies.csv\"\"\"" >> $out
+  echo "  get_csv_url(movies_url).length == 9742" >> $out
+
+  if (scala_assert "danube.scala" "danube_test1.scala")
+  then
+    echo "  --> success" >> $out
+  else
+    echo "  --> one of the tests failed" >> $out
+  fi
+fi
+
+### danube processing tests
+
+if [ $tsts -eq 0 ]
+then
+  echo "  val good_ratings = process_ratings(ratings)" >> $out
+  echo "  val movie_names = process_movies(movies)" >> $out  
+  echo "  " >> $out
+  echo "  good_ratings.length == 48580 " >> $out
+  echo "  movie_names.length == 9742 " >> $out
+
+  if (scala_assert "danube.scala" "danube_test2.scala") 
+  then
+    echo "  --> success" >> $out
+  else
+    echo "  --> one of the tests failed" >> $out
+  fi
+fi
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/danube_test1.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,5 @@
+
+val urban_mov_url = """https://nms.kcl.ac.uk/christian.urban/movies.csv"""
+
+assert(get_csv_url(urban_mov_url).length == 9742)
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/danube_test2.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,18 @@
+
+import io.Source
+import scala.util._
+
+def urban_get_csv_file(name: String) : List[String] = {
+  val csv = Source.fromFile(name)
+  csv.mkString.split("\n").toList.drop(1)
+}
+
+val urban_ratings = urban_get_csv_file("ratings.csv")
+val urban_movies = urban_get_csv_file("movies.csv")
+
+
+assert(process_ratings(urban_ratings).length == 48580)
+
+assert(process_movies(urban_movies).length == 9742)
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/docdiff.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,117 @@
+// Part 1 about Code Similarity
+//==============================
+
+
+//object CW7a { // for purposes of generating a jar
+
+//(1) Complete the clean function below. It should find
+//    all words in a string using the regular expression
+//    \w+  and the library function 
+//
+//         some_regex.findAllIn(some_string)
+//
+//    The words should be Returned as a list of strings.
+
+def clean(s: String) : List[String] = 
+  ("""\w+""".r).findAllIn(s).toList
+
+
+//(2) The function occurrences calculates the number of times  
+//    strings occur in a list of strings. These occurrences should 
+//    be calculated as a Map from strings to integers.
+
+def occurrences(xs: List[String]): Map[String, Int] =
+  (for (x <- xs.distinct) yield (x, xs.count(_ == x))).toMap
+
+//(3) This functions calculates the dot-product of two documents
+//    (list of strings). For this it calculates the occurrence
+//    maps from (2) and then multiplies the corresponding occurrences. 
+//    If a string does not occur in a document, the product is zero.
+//    The function finally sums up all products. 
+
+def prod(lst1: List[String], lst2: List[String]) : Int = {
+    val words = (lst1 ::: lst2).distinct
+    val occs1 = occurrences(lst1)
+    val occs2 = occurrences(lst2)
+    words.map{ w => occs1.getOrElse(w, 0) * occs2.getOrElse(w, 0) }.sum
+}
+
+//(4) Complete the functions overlap and similarity. The overlap of
+//    two documents is calculated by the formula given in the assignment
+//    description. The similarity of two strings is given by the overlap
+//    of the cleaned (see (1)) strings.  
+
+def overlap(lst1: List[String], lst2: List[String]) : Double = {
+    val m1 = prod(lst1, lst1)
+    val m2 = prod(lst2, lst2) 
+    prod(lst1, lst2).toDouble / (List(m1, m2).max)
+}
+
+def similarity(s1: String, s2: String) : Double =
+  overlap(clean(s1), clean(s2))
+
+
+/*
+
+
+val list1 = List("a", "b", "b", "c", "d") 
+val list2 = List("d", "b", "d", "b", "d")
+
+occurrences(List("a", "b", "b", "c", "d"))   // Map(a -> 1, b -> 2, c -> 1, d -> 1)
+occurrences(List("d", "b", "d", "b", "d"))   // Map(d -> 3, b -> 2)
+
+prod(list1,list2) // 7 
+
+overlap(list1, list2)   // 0.5384615384615384
+overlap(list2, list1)   // 0.5384615384615384
+overlap(list1, list1)   // 1.0
+overlap(list2, list2)   // 1.0
+
+// Plagiarism examples from 
+// https://desales.libguides.com/avoidingplagiarism/examples
+
+val orig1 = """There is a strong market demand for eco-tourism in
+Australia. Its rich and diverse natural heritage ensures Australia's
+capacity to attract international ecotourists and gives Australia a
+comparative advantage in the highly competitive tourism industry."""
+
+val plag1 = """There is a high market demand for eco-tourism in
+Australia. Australia has a comparative advantage in the highly
+competitive tourism industry due to its rich and varied natural
+heritage which ensures Australia's capacity to attract international
+ecotourists."""
+
+similarity(orig1, plag1)
+
+
+// Plagiarism examples from 
+// https://www.utc.edu/library/help/tutorials/plagiarism/examples-of-plagiarism.php
+
+val orig2 = """No oil spill is entirely benign. Depending on timing and
+location, even a relatively minor spill can cause significant harm to
+individual organisms and entire populations. Oil spills can cause
+impacts over a range of time scales, from days to years, or even
+decades for certain spills. Impacts are typically divided into acute
+(short-term) and chronic (long-term) effects. Both types are part of a
+complicated and often controversial equation that is addressed after
+an oil spill: ecosystem recovery."""
+
+val plag2 = """There is no such thing as a "good" oil spill. If the
+time and place are just right, even a small oil spill can cause damage
+to sensitive ecosystems. Further, spills can cause harm days, months,
+years, or even decades after they occur. Because of this, spills are
+usually broken into short-term (acute) and long-term (chronic)
+effects. Both of these types of harm must be addressed in ecosystem
+recovery: a controversial tactic that is often implemented immediately
+following an oil spill."""
+
+overlap(clean(orig2), clean(plag2))
+similarity(orig2, plag2)
+
+// The punchline: everything above 0.6 looks suspicious and 
+// should be looked at by staff.
+
+*/
+
+
+//}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/docdiff_test.sh	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,136 @@
+#!/bin/bash
+
+# to make the script fail safely
+set -euo pipefail
+
+
+out=${1:-output}
+
+echo "" > $out
+
+echo "Below is the feedback for your submission docdiff.scala" >> $out
+echo "" >> $out
+
+
+# compilation tests
+
+function scala_compile {
+  (ulimit -t 30; JAVA_OPTS="-Xmx1g" scala "$1" 2>> $out 1>> $out) 
+}
+
+# functional tests
+
+function scala_assert {
+  (ulimit -t 30; JAVA_OPTS="-Xmx1g" scala -i "$1" "$2" -e "" 2> /dev/null 1> /dev/null)
+}
+
+# purity test
+
+function scala_vars {
+   (egrep '\bvar\b|\breturn\b|\.par|ListBuffer|mutable' "$1" 2> /dev/null 1> /dev/null)
+}
+
+
+# var, .par return, ListBuffer test
+#
+echo "docdiff.scala does not contain vars, returns etc?" >> $out
+
+if (scala_vars docdiff.scala)
+then
+  echo "  --> fail (make triple-sure your program conforms to the required format)" >> $out
+  tsts0=$(( 0 ))
+else
+  echo "  --> success" >> $out
+  tsts0=$(( 0 )) 
+fi
+
+### compilation test
+
+
+if  [ $tsts0 -eq 0 ]
+then 
+  echo "docdiff.scala runs?" >> $out
+
+  if (scala_compile docdiff.scala)
+  then
+    echo "  --> success" >> $out
+    tsts=$(( 0 ))
+  else
+    echo "  --> scala did not run docdiff.scala" >> $out
+    tsts=$(( 1 )) 
+  fi
+else
+  tsts=$(( 1 ))     
+fi
+
+### docdiff clean tests
+
+if [ $tsts -eq 0 ]
+then
+  echo "docdiff.scala tests:" >> $out
+  echo "  clean(\"ab a abc\") == List(\"ab\", \"a\", \"abc\")" >> $out
+  echo "  clean(\"ab*a abc1\") == List(\"ab\", \"a\", \"abc1\")" >> $out
+
+  if (scala_assert "docdiff.scala" "docdiff_test1.scala")
+  then
+    echo "  --> success" >> $out
+  else
+    echo "  --> one of the tests failed" >> $out
+  fi
+fi
+
+### docdiff occurrences tests
+
+if [ $tsts -eq 0 ]
+then
+  echo "  occurrences(List(\"a\", \"b\", \"b\", \"c\", \"d\")) == " >> $out
+  echo "      Map(\"a\" -> 1, \"b\" -> 2, \"c\" -> 1, \"d\" -> 1)" >> $out
+  echo "  " >> $out
+  echo "  occurrences(List(\"d\", \"b\", \"d\", \"b\", \"d\")) == " >> $out
+  echo "      Map(\"d\" -> 3, \"b\" -> 2)" >> $out
+
+  if (scala_assert "docdiff.scala" "docdiff_test2.scala") 
+  then
+    echo "  --> success" >> $out
+  else
+    echo "  --> one of the tests failed" >> $out
+  fi
+fi
+
+### docdiff prod tests
+
+if [ $tsts -eq 0 ]
+then
+  echo "  val l1 = List(\"a\", \"b\", \"b\", \"c\", \"d\")" >> $out
+  echo "  val l2 = List(\"d\", \"b\", \"d\", \"b\", \"d\")" >> $out
+  echo "  " >> $out
+  echo "  prod(l1, l2) == 7 " >> $out
+  echo "  prod(l1, l1) == 7 " >> $out
+  echo "  prod(l2, l2) == 13 " >> $out
+
+  if (scala_assert "docdiff.scala" "docdiff_test3.scala") 
+  then
+    echo "  --> success" >> $out
+  else
+    echo "  --> one of the tests failed" >> $out
+  fi
+fi
+
+### docdiff overlap tests
+
+if [ $tsts -eq 0 ]
+then
+  echo "  val l1 = List(\"a\", \"b\", \"b\", \"c\", \"d\")" >> $out
+  echo "  val l2 = List(\"d\", \"b\", \"d\", \"b\", \"d\")" >> $out
+  echo "  " >> $out
+  echo "  overlap(l1, l2) == 0.5384615384615384 " >> $out
+  echo "  overlap(l1, l1) == 1.0 " >> $out
+  echo "  overlap(l2, l2) == 1.0 " >> $out
+
+  if (scala_assert "docdiff.scala" "docdiff_test4.scala") 
+  then
+    echo "  --> success" >> $out
+  else
+    echo "  --> one of the tests failed" >> $out
+  fi
+fi
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/docdiff_test1.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,6 @@
+
+
+assert(clean("ab a abc") == List("ab", "a", "abc"))
+
+
+assert(clean("ab*a abc1") == List("ab", "a", "abc1"))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/docdiff_test2.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,5 @@
+
+
+assert(occurrences(List("a", "b", "b", "c", "d")) == Map("a" -> 1, "b" -> 2, "c" -> 1, "d" -> 1))
+
+assert(occurrences(List("d", "b", "d", "b", "d")) == Map("d" -> 3, "b" -> 2))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/docdiff_test3.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,10 @@
+
+
+val urban_list1 = List("a", "b", "b", "c", "d")
+val urban_list2 = List("d", "b", "d", "b", "d")
+
+assert(prod(urban_list1, urban_list2) == 7)
+
+assert(prod(urban_list1, urban_list1) == 7)
+
+assert(prod(urban_list2, urban_list2) == 13)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/testing2/docdiff_test4.scala	Tue Nov 20 13:42:32 2018 +0000
@@ -0,0 +1,10 @@
+
+
+val urban_list1 = List("a", "b", "b", "c", "d")
+val urban_list2 = List("d", "b", "d", "b", "d")
+
+assert(overlap(urban_list1, urban_list2) == 0.5384615384615384)
+
+assert(overlap(urban_list1, urban_list1) == 1.0)
+
+assert(overlap(urban_list2, urban_list2) == 1.0)