{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$\\mathrm{\\huge{Gradient\\, of \\, column\\, entasis}}$\n",
    "\n",
    "\n",
    "\n",
    "$\\mathrm{Bernhard \\,Fritsch^{1,2}, Malte\\,Vogl^{1,3},Björn\\,Hansen^{1}}$\n",
    "  \n",
    "1: Excellence Cluster 264 Topoi, 2: Berliner Antike Kolleg \n",
    "3: Max Planck Institute for History  of Science  \n",
    "Corresponding mail: bernhard.fritsch@topoi.org  \n",
    "Date: 01. July 2017\n",
    "\n",
    "**goal:** The notebook imports the 3D model of a column in xyz format, cuts the pointcloud into slices and calculates the smallest enclosing circle of each slice. The radius of the circles are plotted and thus show the run of the curve of the entasis of the column.\n",
    "<br>\n",
    "You can load xyz files (without normals) of columns in the import data cell. z of the xyz-file is the height and is recommanded to be a positive value. It is possible to analyze a single column, or even multiple columns at the same time. In this case, single plots for every columns are visualized, as well as plots with all graphs in one sheet.\n",
    "<br>\n",
    "Keywords: ancient columns, entasis\n",
    "<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hide_input": true
   },
   "source": [
    "#   Import data\n",
    "\n",
    "- Note! In order to change the input values in 1.1, 1.2 and 1.3 go to the top right and toggle on the code"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "hide_input": false
   },
   "source": [
    "## Import files\n",
    "\n",
    "file_list and list_of_url  defines the lists of files that will be loaded in.\n",
    "\n",
    "Urls are entered using the whole url to the column, with quotation marks around the url \"http://someurl\". The program will then find the file containing the coordinates.\n",
    "DOIs are added as the number with quotation marks around like this \"10.17171/1-1-10\" the program will then do the rest.\n",
    "\n",
    "Example:\n",
    "```\n",
    "file_list=['Name of xyz-file']\n",
    "or\n",
    "list_of_url=['10.17171/2-2-20-2','10.17171/2-2-25-2','http://repository.edition-topoi.org/collection/CLMN/single/00040']  \n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "hide_input": false
   },
   "outputs": [],
   "source": [
    "file_list=[]\n",
    "list_of_url=['10.17171/2-2-25-2','https://repository.edition-topoi.org/collection/CLMN/single/00106/0']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hide_input": false
   },
   "source": [
    "## Labels\n",
    "\n",
    "The plot_name gives the plots titles, and should be in the order they appear, first file_list then list_of_url.\n",
    "\n",
    "Example:\n",
    "\n",
    "```\n",
    "plot_name=[\"filename1\", \"filename2\", \"filename3\"]\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "plot_name=[\"Hadrians Library, Athens\", \"St. Peter, Rome\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Variables\n",
    "\n",
    "Slice range is the value of the distance in which the column is cut into slices in meters.\n",
    "\n",
    "Save plot defines if the plot should be saved on the server or just visualised, this can be True or False\n",
    "\n",
    "xmax and xmin defines the minimun value and maximum vale on the xaxis\n",
    "\n",
    "```\n",
    "slice_range = 0.01\n",
    "xmax=0.8 #Max on x-axis\n",
    "xmin = 0.3\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "slice_range = 0.01\n",
    "save_plot = False #True  / False\n",
    "xmax=0.7 #Max on x-axis\n",
    "xmin = 0.4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##   Import libraries and tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import scipy as scipy\n",
    "from scipy.spatial import distance\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from numpy import nan\n",
    "import random\n",
    "import math\n",
    "import requests\n",
    "import urllib\n",
    "import re\n",
    "from bs4 import BeautifulSoup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "for url_adr in list_of_url:\n",
    "    if \"http\" not in url_adr:\n",
    "        resTemp = \"https://doi.org/\" + url_adr\n",
    "        url_adr = requests.get(resTemp).url\n",
    "        url_adr = re.sub('CitableHandler', 'collection', url_adr.rstrip('/'))\n",
    "    elif url_adr.endswith(\"/\"):\n",
    "        url_adr = url_adr.rstrip(\"/\")\n",
    "\n",
    "    url = url_adr\n",
    "    req = urllib.request.Request(\n",
    "        url, data=None,\n",
    "        headers={'User-Agent': 'Mozilla/5.0'}\n",
    "    )\n",
    "    url = urllib.request.urlopen(req)\n",
    "    soup = BeautifulSoup(url, \"lxml\")\n",
    "\n",
    "    base_url = None\n",
    "    for link in soup.find_all(\"a\"):\n",
    "        href = link.get(\"href\")\n",
    "        if not href:\n",
    "            continue\n",
    "        if \".nxs\" in href:\n",
    "            base_url = href.split(\".nxs\")[0]\n",
    "            break\n",
    "\n",
    "    if not base_url:\n",
    "        print(\"No NXS/XYZ base found for:\", url_adr)\n",
    "        continue\n",
    "\n",
    "    print(base_url)\n",
    "\n",
    "    repository = \"https://repository.edition-topoi.org\"\n",
    "    xyz = repository + base_url + \".xyz\"\n",
    "    print(\"Testing:\", xyz)\n",
    "\n",
    "    request = requests.get(xyz)\n",
    "    if request.status_code == 200:\n",
    "        if xyz not in file_list:\n",
    "            file_list.append(xyz)\n",
    "        print(\"Found:\", xyz)\n",
    "    else:\n",
    "        print(\"XYZ not found:\", xyz, \"HTTP\", request.status_code)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Smallest enclosing circle emplementation from https://www.nayuki.io/res/smallest-enclosing-circle/smallestenclosingcircle.py\n",
    "\n",
    "# Returns the smallest circle that encloses all the given points. Runs in expected O(n) time, randomized.\n",
    "# Input: A sequence of pairs of floats or ints, e.g. [(0,5), (3.1,-2.7)].\n",
    "# Output: A triple of floats representing a circle.\n",
    "# Note: If 0 points are given, None is returned. If 1 point is given, a circle of radius 0 is returned.\n",
    "# \n",
    "# Initially: No boundary points known\n",
    "def make_circle(points):\n",
    "    # Convert to float and randomize order\n",
    "    shuffled = [(float(p[0]), float(p[1])) for p in points]\n",
    "    random.shuffle(shuffled)\n",
    "\n",
    "    # Progressively add points to circle or recompute circle\n",
    "    c = None\n",
    "    for (i, p) in enumerate(shuffled):\n",
    "        if c is None or not is_in_circle(c, p):\n",
    "            c = _make_circle_one_point(shuffled[0 : i + 1], p)\n",
    "    return c\n",
    "\n",
    "\n",
    "# One boundary point known\n",
    "def _make_circle_one_point(points, p):\n",
    "    c = (p[0], p[1], 0.0)\n",
    "    for (i, q) in enumerate(points):\n",
    "        if not is_in_circle(c, q):\n",
    "            if c[2] == 0.0:\n",
    "                c = make_diameter(p, q)\n",
    "            else:\n",
    "                c = _make_circle_two_points(points[0 : i + 1], p, q)\n",
    "    return c\n",
    "\n",
    "\n",
    "# Two boundary points known\n",
    "def _make_circle_two_points(points, p, q):\n",
    "    circ = make_diameter(p, q)\n",
    "    left = None\n",
    "    right = None\n",
    "    \n",
    "    # For each point not in the two-point circle\n",
    "    for r in points:\n",
    "        if is_in_circle(circ, r):\n",
    "            continue\n",
    "        \n",
    "        # Form a circumcircle and classify it on left or right side\n",
    "        cross = _cross_product(p[0], p[1], q[0], q[1], r[0], r[1])\n",
    "        c = make_circumcircle(p, q, r)\n",
    "        if c is None:\n",
    "            continue\n",
    "        elif cross > 0.0 and (left is None or _cross_product(p[0], p[1], q[0], q[1], c[0], c[1]) > _cross_product(p[0], p[1], q[0], q[1], left[0], left[1])):\n",
    "            left = c\n",
    "        elif cross < 0.0 and (right is None or _cross_product(p[0], p[1], q[0], q[1], c[0], c[1]) < _cross_product(p[0], p[1], q[0], q[1], right[0], right[1])):\n",
    "            right = c\n",
    "\n",
    "    # Select which circle to return\n",
    "    if left is None and right is None:\n",
    "        return circ\n",
    "    elif left is None:\n",
    "        return right\n",
    "    elif right is None:\n",
    "        return left\n",
    "    else:\n",
    "        return left if (left[2] <= right[2]) else right\n",
    "    \n",
    "\n",
    "def make_circumcircle(p0, p1, p2):\n",
    "    # Mathematical algorithm from Wikipedia: Circumscribed circle\n",
    "    ax = p0[0]; ay = p0[1]\n",
    "    bx = p1[0]; by = p1[1]\n",
    "    cx = p2[0]; cy = p2[1]\n",
    "    ox = (min(ax, bx, cx) + max(ax, bx, cx)) / 2.0\n",
    "    oy = (min(ay, by, cy) + max(ay, by, cy)) / 2.0\n",
    "    ax -= ox; ay -= oy\n",
    "    bx -= ox; by -= oy\n",
    "    cx -= ox; cy -= oy\n",
    "    d = (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) * 2.0\n",
    "    if d == 0.0:\n",
    "        return None\n",
    "    x = ox + ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d\n",
    "    y = oy + ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d\n",
    "    ra = math.hypot(x - p0[0], y - p0[1])\n",
    "    rb = math.hypot(x - p1[0], y - p1[1])\n",
    "    rc = math.hypot(x - p2[0], y - p2[1])\n",
    "    return (x, y, max(ra, rb, rc))\n",
    "\n",
    "\n",
    "def make_diameter(p0, p1):\n",
    "    cx = (p0[0] + p1[0]) / 2.0\n",
    "    cy = (p0[1] + p1[1]) / 2.0\n",
    "    r0 = math.hypot(cx - p0[0], cy - p0[1])\n",
    "    r1 = math.hypot(cx - p1[0], cy - p1[1])\n",
    "    return (cx, cy, max(r0, r1))\n",
    "\n",
    "\n",
    "_MULTIPLICATIVE_EPSILON = 1 + 1e-14\n",
    "\n",
    "def is_in_circle(c, p):\n",
    "    return c is not None and math.hypot(p[0] - c[0], p[1] - c[1]) <= c[2] * _MULTIPLICATIVE_EPSILON\n",
    "\n",
    "\n",
    "# Returns twice the signed area of the triangle defined by (x0, y0), (x1, y1), (x2, y2).\n",
    "def _cross_product(x0, y0, x1, y1, x2, y2):\n",
    "    return (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot of the entasis curve"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "code_folding": [],
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "X=[p for p in np.arange(slice_range,15,slice_range)]\n",
    "\n",
    "df_out = pd.DataFrame(index=X)\n",
    "\n",
    "for file in file_list:\n",
    "    df=pd.read_csv(file,sep=\" \",header=None, index_col=None, usecols=[0,1,2])\n",
    "    print('Head of table for file:  {0}'.format(file))\n",
    "    print(df.head())\n",
    "    df.columns = [\"X\", \"Y\", \"Z\"]\n",
    "    df = df.sort_values(by=\"Z\", ascending=[1])\n",
    "    max_height = float(df['Z'].max())\n",
    "    \n",
    "    plot_list=[]  \n",
    "    for i in np.arange(slice_range,max_height,slice_range):\n",
    "        j=i-slice_range\n",
    "        data=df.loc[df['Z'].between(j,i)]\n",
    "        n=list(zip(data[\"X\"],data[\"Y\"]))\n",
    "        if len(n)>0:\n",
    "            u=[[i[0],i[1]] for i in n]\n",
    "            m=make_circle(u)\n",
    "            plot_list.append((i,m[2]))\n",
    "        else:\n",
    "            plot_list.append((i,nan))\n",
    "        #else:\n",
    "        #    plot_list.append((i,max(maxi)))\n",
    "        #print(max(maxi),alge_diameter(list(data[\"X\"])-center_avg[0],list(data[\"Y\"])-center_avg[0]))\n",
    "        x2,y2=[],[]\n",
    "        for i in plot_list:\n",
    "            x2.append(i[1])\n",
    "            y2.append(i[0])\n",
    "\n",
    "    fig = plt.figure(figsize=(10,20))\n",
    "    \n",
    "    plt.rc('xtick', labelsize=14)    # fontsize of the tick labels\n",
    "    plt.rc('ytick', labelsize=14)    # fontsize of the tick labels\n",
    "\n",
    "    ax = fig.add_subplot(111)\n",
    "    ax.yaxis.tick_right()\n",
    "    ax.yaxis.set_label_position(\"right\")\n",
    "    plt.ylabel('Height (m)', fontsize=20)\n",
    "\n",
    "    plt.plot(x2,y2, linewidth=4.0)\n",
    "    plt.xlim(xmax, xmin)\n",
    "    plt.title(plot_name[file_list.index(file)], fontsize=20)\n",
    "    plt.xlabel('Diameter (m)', fontsize=20)\n",
    "\n",
    "    if save_plot == True:\n",
    "        plt.savefig(plot_name[file_list.index(file)]+'-2.png')\n",
    "\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "    x2+=[nan for p in range(len(X)-len(x2))]\n",
    "\n",
    "    df_out[plot_name[file_list.index(file)]]=pd.Series(x2,index=X)\n",
    "df_out = df_out.dropna(axis=0,how='all')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Multiplot\n",
    "\n",
    "In case multiple columns are processed at the same time, the plot shows the entasis of all columns in one plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ax = df_out.plot(figsize=(20,10), ylim=(0,1), linewidth=3.0)\n",
    "ax.legend(fontsize=16)\n",
    "ax.set_xlabel(\"Height (m)\", fontsize=16)\n",
    "ax.set_ylabel(\"Diameter (m)\", fontsize=16)\n",
    "\n",
    "if save_plot == True:\n",
    "        plt.savefig('MultiColumnPlot.png')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Default plot\n",
    "\n",
    "Changed xmax- and xmin-values of the xaxis while importing the data is shown in the plots above. Every entasis is additionally plotted with x-axis values from 0 to 1 and the y-axis as maximum value of the highest column. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "for plot in plot_name:\n",
    "#    df_out[plot].plot(figsize=(20,10), ylim=(0,1))\n",
    "        fig = plt.figure(figsize=(10,20))\n",
    "    \n",
    "        plt.rc('xtick', labelsize=14)    # fontsize of the tick labels\n",
    "        plt.rc('ytick', labelsize=14)    # fontsize of the tick labels\n",
    "\n",
    "        ax = fig.add_subplot(111)\n",
    "        ax.yaxis.tick_right()\n",
    "        ax.yaxis.set_label_position(\"right\")\n",
    "        plt.ylabel('Height (m)', fontsize=20)\n",
    "\n",
    "        x2 = df_out[plot].index.values\n",
    "        y2 = df_out[plot].values\n",
    "\n",
    "        plt.plot(y2,x2, linewidth=4.0)\n",
    "        plt.xlim(1, 0)\n",
    "        plt.title(plot, fontsize=20)\n",
    "        plt.xlabel('Diameter (m)', fontsize=20)\n",
    "        if save_plot == True:\n",
    "            plt.savefig(plot+'.png')\n",
    "        plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "editiontopoi": {
   "Annotations": {
    "Further information": "",
    "Subjects": "",
    "Version": ""
   },
   "Conditions for use": {
    "Further legal restrictions or comments": "",
    "Rights": "Creative Commons BY-NC-SA 3.0 DE: https://creativecommons.org/licenses/by-nc-sa/3.0/de/"
   },
   "General Information": {
    "Creator": "Björn Hansen; Malte Vogl",
    "DOI": "",
    "Description": "Visualizing the entasis of ancient columns",
    "Publication Year": 2017,
    "Publisher": "Edition Topoi",
    "Subtitle": "Subtitle",
    "Title": "testing custom.js for metadata functionality",
    "author": "Author"
   },
   "Specific Attributes": {
    "Alternate Identifier": "",
    "Geolocation/region": "",
    "Holder digital source": "",
    "Inventory Number": "",
    "Language source/object": "",
    "Origin / Holder object": "",
    "Related Identifier": ""
   },
   "Technical characteristics": {
    "Collection": "",
    "Contributor Name": "",
    "Contributor Type": "",
    "Date (Update)": "",
    "Format": "",
    "Resource Type": "",
    "Size": "",
    "Tools": ""
   }
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "nbTranslate": {
   "displayLangs": [
    "*"
   ],
   "hotkey": "alt-t",
   "langInMainMenu": true,
   "sourceLang": "en",
   "targetLang": "fr",
   "useGoogleTranslate": true
  },
  "toc": {
   "nav_menu": {
    "height": "12px",
    "width": "252px"
   },
   "number_sections": true,
   "sideBar": false,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "965px",
    "left": "7px",
    "right": "2067.87px",
    "top": "131px",
    "width": "20px"
   },
   "toc_section_display": "block",
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}