https://github.com/file-acomplaint/knottingham
Raw File
Tip revision: c2766d13d4535610cc269831164b72d5ac1f880d authored by unknown on 25 May 2024, 19:44:29 UTC
Rephrased README
Tip revision: c2766d1
index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> Knottingham</title>
    <link rel="icon" href="https://fi-le.net/images/favicon.png">
    <meta author content="fi-le">
    <meta name="keywords" content="Knot Theory, Knottingham, Knots">
    <script type="text/javascript" src="lib/paper.js"></script>
    <script type="text/javascript" src="lib/BigInteger.min.js"></script>
    <script type="text/javascript" src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    <script type="text/javascript" src="https://sagecell.sagemath.org/static/embedded_sagecell.js"></script>

    <script type="text/javascript" src="js/polynomials.js"></script>
    <script type="text/javascript" src="js/knotTools.js"></script>
    <script type="text/paperscript" canvas="canvas" src="js/canvas.js"></script>

  
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>

<body>

    <div style="text-align:center;">
      <div style="margin:0px; padding:0px;">
        <canvas id="canvas" width="1000px;" height="450px;"></canvas>
        <p style="font-family: monospace;" id="log"></p>
      </div>

      <div style="margin:1%;">
        <div style="display: grid;grid-template-columns: 1.5fr 1fr;align-items: center;">
          <p><b>Alexander Polynomial:</b> <span id="alexanderPolynomial"></span></p>
          <p style="display:none;" id="jonesContainer"><b>Jones Polynomial:</b> <span id="jonesPolynomial"></span></p>
          <p style="display:none;" id="homflyContainer"><b>HOMFLY Polynomial:</b> <span id="homflyPolynomial" style="font-family:monospace;"></span></p>
          <p><b>Gauss</b>: <span id="gauss" style="font-family: monospace;"></span> <br> <b>Dowker-Thislethwaite</b>: <span id="dt" style="font-family: monospace;"></span></p>
            <p id="candidates-p"><b><!--Candidates with  \(<10\) Crossings:--></b>  <span id="candidates"></span></p>
        </div>

        <hr>
        <p>
          <button type="button" onclick="window.globals.draw(); isomorphy.checked = false; smoothing.checked = false; window.globals.switchIsomorphy(); window.globals.isomorphy = false;"><b>Draw from Scratch</b></button>
          <button type="button" onclick="window.globals.select()">Show / Hide Bezier Handles</button>
          <button type="button" onclick="window.globals.undo()">Undo</button>
        </p>

        <p>Force Smoothness: <input id="smoothing" type="checkbox" checked="true" onchange="window.globals.smooth = this.checked;">
        | <button type="button" onclick="straighten()">Straighten</button>
          <!--  <button type="button" onclick="flatten()">Flatten</button> -->
          <button type="button" onclick="window.globals.simplify()">Simplify</button>
          <button type="button" onclick="orthogonalise(this, dt.innerHTML, 'DT', 'Orthogonalize', 'Error')" id="orthButton">Orthogonalize (slow)</button> <br>

      </p>

        <p>Drag Neighboring Points: <input id="dragging" type="checkbox" checked="false"  onchange="window.globals.neighbors = this.checked ? 2 : 0;"> | <b>Try reverting Non-Reidemeister moves:</b> <input type="checkbox" id="isomorphy" checked="true",  onchange="window.globals.isomorphy = this.checked; window.globals.switchIsomorphy();"></p>

      <p>
        Additional Invariants, calculated once: <button type="button" onclick="getJones()" id="jonesButton">Jones Polynomial</button>
        <button type="button" onclick="getHomfly()" id="homflyButton">HOMFLY Polynomial</button>
      </p>
        <p><b>Styling:</b><br>
          Gap Width: <input type="range" min="2" max="5" value="2" step="0.1" class="slider" onchange="window.globals.gapWidth = this.value; window.globals.updateStyle();"><br>
          Stroke Width: <input type="range" min="1" max="10" value="3"  step="0.1" class="slider"  onchange="window.globals.strokeWidth = this.value; window.globals.updateStyle();"><br>
          Show Intersections: <input type="checkbox" id="showIntersections" onchange="window.globals.showIntersections = this.checked;">
          Drag Handles Independently: <input type="checkbox" id="dragIndependently" onchange="window.globals.independentHandles = this.checked;">

        </p>
        <hr>

        <p><b>Exporting:</b>
          <button type="button" onclick="toSVG();">To SVG</button>
          <button type="button" onclick="toJSON();">To JSON</button>
          <button type="button" onclick="toTikz(); this.innerHTML='Export to TikZ (Copied to Clipboard!);'">To TikZ</button> <br>
          <b>Importing:</b>
          <button onclick="orthogonalise(this, dtInput.value, 'DT', 'From DT code:', 'Error: Try again in the format `x y z ...`');">From DT code:</button> <input type="text" id="dtInput" placeholder="4 6 2"> 
          <button onclick="orthogonalise(this, rolfsenInput.value, 'Rolfsen', 'From Rolfsen Table:', 'Error: Try again in the format x_y');">From Rolfsen Table:</button> <input type="text" id="rolfsenInput" placeholder="10_161"> 
          <p>From Knottingham JSON: </p><input type="file" id="file" accept=".JSON,.json,.knottingham"name="Load a Knottingham JSON file" oninput="readJSON(this.files[0])">
          
        </p>
      </div>
    </div>

    <div style="margin:5%;">
      <h3>Manual</h3>
      <p><b>Knottingham</b> is a tool that lets you draw and manipulate knot diagrams, sporting a clean yet somewhat hand-drawn look. To start knotting away, you may want to follow these steps:</p>
      <ul>
        <li>Create a knot by:</li>
        <ul>
          <li>Clicking on segments to add new nodes</li>
          <li>Clicking and dragging nodes to move them (you can use 'Drag Neighbors' to rescue nodes from below crossings)</li>
          <li>and finally <b>clicking on the (red) crossings to switch them</b> (with "try reverting Non-Reidemeister moves" turned off)</li>
          <li>or importing JSON</li>
          <li><b>or clicking on 'Drawing' to draw a new knot from scratch</b>!</li>
        </ul>
        <li>Adjust the knot by:</li>
        <ul>
          <li>Removing nodes with <b>Shift+Click</b></li>
          <li>Smoothing segments with <b>Control+Click</b></li>
          <li>Moving, rotating and mirroring the knot with the <b>WASD+EQ+M</b> keys</li>
          <li>Undoing with the <b>Z</b> key</li>
          <li>Selecting it through the select button and adjust Bezier handles</li>
          <li>Creating a <b>minimal-bend diagram</b> on the integer grid with the button "Orthogonalize". You can follow up with:</li>
          <li>Forcing smoothness (twice continuous differentiability, to be precise)</li>
          <li>Adjusting the style with the sliders</li>
        </ul>
        <li> Show the knot to your friends by:
          <ul>
            <li>Exporting it to SVG!</li>
            <li>Exporting it to JSON, to be imported back into Knottingham!</li>
            <li>Exporting it to TikZ! (Fully customizable, but without crossing Info)</li>
          </ul>
        </li>
      </ul>

      Knottingham can also try <b>detecting non-Reidemeister moves</b>! Check the corresponding box and start thinking through knot equivalences. Discontious operations like smoothing or deleting segments might lead to breaking the equivalence.

      The Jones and HOMLY polynomial are calculated with <a href="https://sagecell.sagemath.org/">SageCellMath</a>. To help them cover server costs incurred through websites like this, they accept contributions and donations <a href="https://github.com/sponsors/sagemath">here</a>.
      <br>
      <!--
      These features could arrive in a future version:
      <ul>
        <li>Proven Non-Reidemeister Move-Detection</li>
        <li>Some more styling options</li>
        <li>Redoing</li>
      </ul>
      -->
      <p>Any and all feedback is appreciated! You can mail to <a href="mailto:developer/at/fi-le.net">developer/at/fi-le.net</a>. <br> Knottingham is open source - you can read and contribute to the code over <a href="https://github.com/file-acomplaint/knottingham">here</a>.</p>
    </div>
    
     <script type="text/javascript">
      

      window.globals = {neighbors:0, strokeWidth:5, gapWidth:2, strokeColor:'black', showIntersections:true, independentHandles: false, smooth:false, isomorphy:true};
      var polynomial = document.getElementById('alexanderPolynomial');
      var jonesPolynomial = document.getElementById('jonesPolynomial');
      var candidates = document.getElementById('candidates');
      var candidates_p = document.getElementById('candidates-p');
      var smoothing = document.getElementById('smoothing');
      var dragging = document.getElementById('dragging');
      var isomorphy = document.getElementById('isomorphy');
      var showIntersections = document.getElementById('showIntersections');
      var dragIndependently = document.getElementById('dragIndependently');
      var dt = document.getElementById('dt');
      var log = document.getElementById('log');
      var gauss = document.getElementById('gauss');
      var orthButton = document.getElementById('orthButton');
      var jonesButton = document.getElementById('jonesButton');
      var homflyButton = document.getElementById('homflyButton');
      var dtInput = document.getElementById('dtInput');
      var rolfsenInput = document.getElementById('rolfsenInput');

      isomorphy.checked = smoothing.checked = showIntersections.checked = true;
      dragging.checked = dragIndependently.checked = false;

      function flatten() {
        smoothing.checked = false;
        window.globals.flatten();
      }
      function straighten() {
        smoothing.checked = false;
        window.globals.straighten();
      }

      function toTikz() {
        var string =  window.globals.toTikz();
        navigator.clipboard.writeText(string);
      }

      function readJSON(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          window.globals.fromJSON(e.target.result);
        };
        reader.readAsText(file);
      }

      function toSVG() {
        // Kindly provided by users senz, Dave and defghi 1977
        // https://stackoverflow.com/questions/23218174/how-do-i-save-export-an-svg-file-after-creating-an-svg-with-d3-js-ie-safari-an
        var svg =  window.globals.toSVG();

        svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
        var svgData = svg.outerHTML;
        var preface = '<?xml version="1.0" standalone="no"?>\r\n';
        var svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"});
        var svgUrl = URL.createObjectURL(svgBlob);
        var downloadLink = document.createElement("a");
        downloadLink.href = svgUrl;
        downloadLink.download = "knottingham";
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      }

      function toJSON() {
        // Many thanks to users bformet and volzoran
        // https://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser

        var jsonString =  window.globals.toJSON();
        var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(jsonString);
        var dl = document.createElement("a");
        dl.setAttribute("href", dataStr);
        dl.setAttribute("download", "knot.knottingham");
        dl.click();
        document.body.removeChild(dl);
      }

      var pyodide = null;
      
      async function getPyodide(display) {
        if (pyodide == null) {
          display.innerHTML = "loading... [1/7]";
          pyodide = await loadPyodide();
          display.innerHTML = "loading... [2/7]";
          await pyodide.loadPackage("micropip");
          display.innerHTML = "loading... [3/7]";
          const micropip = pyodide.pyimport("micropip");
          await micropip.install("sqlite3");
          display.innerHTML = "loading... [4/7]";
          await micropip.install('knot_floer_homology-1.2-cp311-cp311-emscripten_3_1_45_wasm32.whl');
          display.innerHTML = "loading... [5/7]";
          await micropip.install('snappy_manifolds-1.2-py3-none-any.whl');
          display.innerHTML = "loading... [6/7]";
          await micropip.install('spherogram-2.2.1-cp311-cp311-emscripten_3_1_45_wasm32.whl');
        }
      }

      async function orthogonalise(button, code, codeType, successString, errorString) {
        if (window.globals.getNumIntersections() < 3) {
          button.innerHTML = ">2 crossings needed.";
          return;
        }
        smoothing.checked = false;
        await getPyodide(button);
        

        if (codeType == "DT") {
          if (code == "") {
            code = "4 6 2";
          }
          linkString = "DT:[("+code.replaceAll(" ", ", ")+")]";
        } else if (codeType == "Rolfsen") {
          if (code == "") {
            code = "10_161";
          }
          linkString = code;
        }

        try {
          let geometry = pyodide.runPython(`
            from spherogram.links import Link
            from spherogram.links.orthogonal import OrthogonalLinkDiagram

            from pyodide.ffi import to_js

            l = Link("` + linkString + `")
            o = OrthogonalLinkDiagram(l)
            to_js(o.plink_data())`);
          window.globals.fromSnappy(geometry);
          button.innerHTML = successString;
        } catch(err) {
          console.error(err);
          button.innerHTML = errorString;
        }
      }
      
      function runSage(code, callback, display) {
        // Using SageMathCell API adapted from
        // https://github.com/sagemath/sagecell/blob/master/contrib/sagecell-client/sagecell-service.py
        // The right thing to do here would be using
        // https://github.com/sagemath/sagecell/blob/master/contrib/sagecell-client/sagecell-client.py
        // However, the Javascript Websocket API doesn't allow headers when creating a connection, so the Jupyter-Kernel-ID cannot be sent as intended, resulting in a 403.
        retries = 3;
        display.innerHTML = "Loading SageCell";
        async function executeRequest() {
          const url = 'https://sagecell.sagemath.org/service';
          const requestBody = {
              code: code,
              accepted_tos: "true"
          };

          fetch(url, {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
              },
              body: new URLSearchParams(requestBody)
          })
          .then(response => response.json())
          .then(reply => {
              if (reply['success'] && 'stdout' in reply) {
                  callback(reply['stdout'], display);
              } else {
                  console.log(reply);
                  if (retries > 0) {
                      setTimeout(executeRequest, 500);
                  } else {
                      display.innerHTML = "Connection to SageCell failed.";
                  }
              }
          })
          .catch(error => {
            console.error(error);
              if (retries > 0) {
                  setTimeout(executeRequest, 500);
              } else {
                display.innerHTML = "Connection to SageCell failed.";
              }
          });
        }
        executeRequest();
      }

      function getJones() {
        const code = 'K = Knots().from_dowker_code([' + dt.innerHTML +'])\nprint(K.jones_polynomial())';

        runSage(code,function(result, jonesButton) {
          jonesPolynomial.innerHTML = "\\(" + "p_J(t)=" + result.replaceAll("*", "") + "\\)";
          if (window.MathJax) {MathJax.typeset();}
          document.getElementById('jonesContainer').style.display = "block";
          jonesButton.innerHTML = "Refresh Jones Polynomial" 
        },jonesButton);
      }
      function getHomfly() {
        const code = 'K = Knots().from_dowker_code([' + dt.innerHTML +"])\nprint(K.homfly_polynomial())";

        runSage(code,function(result, homflyButton) {
          document.getElementById('homflyContainer').style.display = "block";
          homflyPolynomial.innerHTML = "p_HOM(M,L)=" + result;
          homflyButton.innerHTML = "Refresh HOMFLY Polynomial";
        },homflyButton);
      }
      </script>

      <script src="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js"></script>
      
</body>
</html>
back to top