ideaconsult / Toxtree.js

http://ideaconsult.github.io/Toxtree.js/
2 stars 3 forks source link

jToxKit

A kit of front-ends for accessing toxicological web services, based on AMBIT. It is designed to provide easy-to-integrate approach for using any or all of available front ends in third-party web pages. Each different front-end is referred as kit. Currently available are:

The toolkit is intended to be used by semi-programmers, and thus it's integration process is rather simple - referring two files and marking a placeholder in HTML of where all the structure to be inserted. However, it relies on the fact that certain external libraries like jQuery and some of jQueryUI widgets are already included in the page.

Integration manual

In order to use jToxKit in your page, you need to implement these steps:

  <link rel="stylesheet" href="https://github.com/ideaconsult/Toxtree.js/blob/master/jquery-ui.css"/>
  <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.js"></script>
  <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.ui.core.js"></script>
$(document).ready(function() { 
  jToxStudy.kits[0].querySubstance("http://apps.ideaconsult.net:8080/biodeg/substance/IUC4-efdb21bb-e79f-3286-a988-b6f6944d3734");
});

jToxKit itself provides certain global routines, which can be invoked like jToxKit.call(), however for ease of use, there is an alias jT for jToxKit, so jT.call() is also a valid reference.

Configuration parameters

Beside specifying the exact place of code insertion the <div> tag, referred above, is also used to setup the type and configuration of the front-end. There are three ways to pass configuration parameters to jToxKit:

For example, the following three have the same effect:

  1. Querying like this:
http://apps.ideaconsult.net:8080/toxbank/substance/IUC4-d982cd73-9ee1-32af-8604-962ae6875cc7/study?tab=P-CHEN&crossDomain=true
  1. Or, embedding a jToxKit placeholder like this:
    <div class="jtox-toolkit" data-kit="study" data-tab="P-CHEN" data-cross-domain="true" data-substance-uri="http://apps.ideaconsult.net:8080/biodeg/substance/IUC4-d982cd73-9ee1-32af-8604-962ae6875cc7"></div>
  1. Or, making a manual initialization like this:
$(document).ready(function(){
  var st = new jToxStudy($(".jtox-toolkit")[0], { crossDomain: true, tab: 'P-CHEM' });
  st.querySubstance("http://apps.ideaconsult.net:8080/toxbank/substance/IUC4-d982cd73-9ee1-32af-8604-962ae6875cc7");

Although different kits can have different configuration parameters, these are common, and can be separates in few groups:

Connection related
Kit events handlers
Miscellaneous

As, can be seen, the three connection callbacks can be local for each kit, so it is possible to report connection statuses in the most appropriate for the kit's way. This is also true for Url's, which means that not all kits, needs to communicate with one and the same server.

jToxKit methods

There are certain methods that are common for all kits and some kit wrappers - like jToxQuery - rely on having them:

jToxKit.initKit(element)

The actual kit initialization procedure - it determines the kit that need to be used relying on data-kit option and creates a new instance, passing the element as kit's root. It is automatically invoked for kits, not marked as manualInit, however it can be called from the JS code for such kits and all initialization and configuration procedure goes as needed.

jToxKit.kit(element)

Returns the instance of the kit that has the passed element as its root. When passed a <div> element, marked with jtox-toolkit class - this method will return the instance that was created during kit's initialization, i.e. - during initKit() call.

jToxKit.parentKit(prototype, element)

Returns the instance of prototype which has its root as the closest parent of element. In other words - traverses up all the parents of element until it reaches a jToxKit's kit, which is of given prototype.

jToxKit.insertTool(name, root)

Inserts a third-party tool, which was added to jToxKit's production files, like ketcher, for example. It inserts that HTML code for the name tool under the passed root. If this tool has separate script files (and it probably does), it needs to be included separately on the page.

jToxKit.call(kit, service, params, callback)

The general function for making server calls - all other kits should use this method. The passed kit instance's settings are used for baseUrl, crossDomain, jsonp other that may be relevant. If null is passed - the default settings from jToxKit itself are used. The most important parameter is service which determines the actual call to be made. The next parameter params is explained later - it can be omitted. Finally there is callback, which is called in both success and error. It's format is function callback(result, jhr), where result is what came from server, or null on error, and jhr is the actual jQuery AJAX object. The params parameter (if present) can have the following properties:

UI methods

There is a bunch of methods, which are responsible for some pure UI-related stuff within jToxKit. They can be found in jToxKit.ui or jT.ui, and although most of them are internally used by the kits, here is a short explanation of most important ones:

jToxKit.ui.shortenedData(content, message, data)

A method for shortening passed content, wrap it into a separate div block and make it clipboard insertable if message is supplied. The clipboard copied data is data or content if the first one is null.

jToxKit.ui.changeTabsIds(root, suffix)

When you have jQueryUI tabs' plugin used, it relies on ids of elements, and when you use same kit more than once you'll end up having id duplication. This function takes care of that - it adds gives suffix to ids of all a and corresponding div elements which are part of tabs' structure.

jToxKit.ui.processColumns(kit, category)

Most of kits have a mechanism for providing column configuration and this function takes provided kit's default columns and provided ones (remember - they live in <kit>.settings.configuration.columns) and build up the final column listing the way it can be provided to dataTables plugin which is used all around.

jToxKit.ui.putStars(kit, stars, title)

Put a stars number of stars, using provided kit's stars format setting and putting given title as hover tooltip.

jToxKit.ui.bindControls(kit, handlers)

The two most important kits - jToxCompound and jToxSubstance have their own paging and filtering mechanism. This function puts the necessary controls and handling so that they start to work. Look at the code for more details.

jToxKit.putActions(kit, col, defs)

Alters the given column's mRender function so that it includes also selection and/or details icons - depending on provided defs. Check the code of jToxSubstance, jToxModel and jToxDataset for more details.

jToxKit.updateCounter(str, count, total)

Update a counter within a given str. The counter can be either of this form: (1/14), or just a simple number: (14) - which is the case when total is not passed. This method find old such form, if exists, and updates it.

Kit instance common methods

<kit class>.kits

An array with all kit instances from this kit class. For example: jToxQuery.kits[0] is the first instance of jToxQuery found on the page.

<kit instance>.modifyUri(uri)

When a certain kit is wrapped with another one, like the way jToxQuery wraps jToxSearch - this is the mechanism which allows jToxQuery to collect "preferences" of all sub-widgets, before passing the so-constructed uri to the main kit. Refer jToxQuery's documentation for more information.

<kit instance>.query(uri)

A shorthand, general method, that jToxQuery can call on any (main) kit, to perform it's preferred query method. For example for jToxCompound this method is another way to call <jToxCompound>.queryDataset(datasetUri).

jToxCompound kit

An OpenTox compound dataset management and visualization tool. Since compound is very basic term in OpenTox hierarchy it is used in other places like jToxQuery and jToxTree kit. It is vital to understand that the scope of this kit it not to provide complete, versatile interface for making queries, linking between them, etc. - it aims at visualizing and providing basic navigation within one particular query. It is designed to be easily configurable - up to the point of being only one table, and easily driven with API calls, which are explained below.

As a consequence of this perspective, all functionality as filtering and ordering, is applied to the currently downloaded dataset entries, i.e. - one "page" of the dataset. This is due to the fact that for many datasets it is impossible to have general procedures applied to them, thus the scope of this kit is limited to local visualization functions only.

Dependencies

It has less dependencies, compare to jToxStudy, namely they are:

    <link rel="stylesheet" href="https://github.com/ideaconsult/Toxtree.js/blob/master/jquery.ui.tabs.css"/>
    <link rel="stylesheet" href="https://github.com/ideaconsult/Toxtree.js/blob/master/jquery.dataTables.css"/>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.ui.widget.js"></script>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.ui.tabs.js"></script>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.dataTables.js"></script>
Parameters

Parameters that can be passed either with data-XXX attributes or when initialized manually with JavaScript are:

Configuration

Feature enabling-disabling functions and dataset entry detailed visualization rely pretty much on proper grouping of the features. There is a predefined default grouping, but it can be changed via configuration parameter. It is find in group member of it, which has the following syntax:

"groups" : {
    "<group name>": <array> | <function>,
    ...
}

The <array> option, means an array of feature IDs, the <function> option is a function with following syntax: function (groupName, miniDataset) which should return (again) an array of feature IDs that are part of that group. It can either be function object itself, or function-name, if configuration is passed via external json. The first parameter (groupName) is the name of the group being filled, and the second parameter - miniDataset is the 1-sized dataset that jToxStudy queried to obtain the available features, with features property pre-processed. The context in which the function is called is the jToxKit instance (i.e. this parameter). A special case is when one (or more) of the member of the array is (are) objects and not string. This is used when certain bunch of features need to be grouped in one checkbox. The format of the object should be:

{ "name": "Group name", "features": [ ... <array of features> ] };

This can be part of the array. For example the default Names group can look like this:

    "Names": [
      "http://www.opentox.org/api/1.1#ChemicalName",
      "http://www.opentox.org/api/1.1#TradeName",
      "http://www.opentox.org/api/1.1#IUPACName",
      { "name": "Formulas",
        "features": [
          "http://www.opentox.org/api/1.1#SMILES",
          "http://www.opentox.org/api/1.1#InChIKey",
          "http://www.opentox.org/api/1.1#InChI",
        ]
      },
      "http://www.opentox.org/api/1.1#REACHRegistrationDate"
    ],

Which will result in all formula-related features to be grouped in one, named Formulas and thus, turning on and off can be done from single checkbox.

Another aspect that can be configured from there is the list of possible exports, it has the following format:

"exports": [
    {type: "<MIME type for export>", icon: "<icon location, relative to current page>"},
    ...
]

And now, we've finally got to explaining each feature's configuration options:

"baseFeatures": {
    "<featureId": {
        title: "<readable title>",
        data: "<location in data entry of the value of that feature>",
        accumulate: true | false, // whether value of this feature need to be accumulated
        search: true | false, // is this feature searchable
        basic: true | false, // is it a basic, feature with custom behaviour?
        used: true | false, // put true if you want to make sure it won't show up on Other tab
        visibility: none | all | main | details,
        column: <object to be merged with dataTable column definition | function definition>
        process: <function name | definition to be called during feature preparation>,
        render: <function definition - used for rendering feature values (also - as mRender)>,
    },
    ...
}

All of them are optional, and it is good to remember that these are merged with feature definitions as they arrive from the server.

In the full configuration, shown below example of using last two can be seen for Diagram property. The standard columns part of the configuration refers to the detailed view, feature table:

{
      "columns": {
        "compound": {
          "Name": { sTitle: "Name", mData: 'title', mRender: ... },
          "Value": { sTitle: "Value", mData: 'value', sDefaultContent: "-" },
          "SameAs": { sTitle: "SameAs", mData: 'sameAs', sDefaultContent: "-" },
          "Source": { sTitle: "Source", mData: 'source', sDefaultContent: "-", mRender: ... }
        }
      },
      "groups": {
        "Identifiers" : [
          "http://www.opentox.org/api/1.1#Diagram", 
          "http://www.opentox.org/api/1.1#CASRN", 
          "http://www.opentox.org/api/1.1#EINECS",
          "http://www.opentox.org/api/1.1#IUCLID5_UUID"
        ],

        "Names": [
          "http://www.opentox.org/api/1.1#ChemicalName",
          "http://www.opentox.org/api/1.1#TradeName",
          "http://www.opentox.org/api/1.1#IUPACName",
          "http://www.opentox.org/api/1.1#SMILES",
          "http://www.opentox.org/api/1.1#InChIKey",
          "http://www.opentox.org/api/1.1#InChI",
          "http://www.opentox.org/api/1.1#REACHRegistrationDate"
        ],

        "Calculated": function (name, features) {
          var arr = [];
          for (var f in features) {
            if (features[f].source != null && features[f].source.type != null && !features[f].source.type.toLowerCase() == "algorithm")
              arr.push(f);
          }
          return arr;
        },

        "Other": function (name, features) {
          var arr = [];
          for (var f in features) {
            if (!features[f].used)
              arr.push(f);
          }
          return arr;
        }
      },
      "exports": [
        {type: "chemical/x-mdl-sdfile", icon: "images/sdf.jpg"},
        {type: "chemical/x-cml", icon: "images/cml.jpg"},
        {type: "chemical/x-daylight-smiles", icon: "images/smi.png"},
        {type: "chemical/x-inchi", icon: "images/inchi.png"},
        {type: "text/uri-list", icon: "images/link.png"},
        {type: "application/pdf", icon: "images/pdf.png"},
        {type: "text/csv", icon: "images/excel.png"},
        {type: "text/plain", icon: "images/excel.png"},
        {type: "text/x-arff", icon: "images/weka.png"},
        {type: "text/x-arff-3col", icon: "images/weka.png"},
        {type: "application/rdf+xml", icon: "images/rdf.gif"},
        {type: "application/json", icon: "images/json.png"}
      ]
      "exports": [
        {type: "chemical/x-mdl-sdfile", icon: "images/sdf.jpg"},
        {type: "chemical/x-cml", icon: "images/cml.jpg"},
        {type: "chemical/x-daylight-smiles", icon: "images/smi.png"},
        {type: "chemical/x-inchi", icon: "images/inchi.png"},
        {type: "text/uri-list", icon: "images/link.png"},
        {type: "application/pdf", icon: "images/pdf.png"},
        {type: "text/csv", icon: "images/excel.png"},
        {type: "text/plain", icon: "images/excel.png"},
        {type: "text/x-arff", icon: "images/weka.png"},
        {type: "text/x-arff-3col", icon: "images/weka.png"},
        {type: "application/rdf+xml", icon: "images/rdf.gif"},
        {type: "application/json", icon: "images/json.png"}
      ],

      "baseFeatures": {
        "http://www.opentox.org/api/1.1#Similarity": {title: "Similarity", location: "compound.metric", search: true, used: true},
        "http://www.opentox.org/api/1.1#Diagram": {title: "Diagram", search: false, used: true, visibility: "main", ... },
        },
      }
    }
Methods

jToxCompound has several methods to drive visualization, as well as several "static" ones, which makes it possible for other kits to use its functionality. Let's start with these:

jToxCompound.processDataset(dataset, features, fnValue, startIdx)

Only the first parameter dataset is required and it is the downloaded dataset, as is from the OpenTox server. If features are already preprocessed (see below) they can be passed here as second parameter - features. The third - fnValue is a user-provided function that takes part during each entry's preprocessing, it is explained in details in a second. The last parameter startIdx is the starting index within the dataset, if a call is made for some other part of the dataset. Remember - this is a static call and it does not preserve context information like page size, index, etc.

jToxCompound.processFeatures(features)

Very important function in unified feature processing. It traverses all reported features, merging those that mean one and the same thing, as reported by their sameAs parameter, also takes care of predefined features that can instruct it to "location" certain feature value inside the dataset entry, itself. This is called internally by processDataset() or should be called if features parameter is passed to the later.

jToxCompound.processEntry(entry, features, fnValue)

Used extensively during dataset preprocessing. When traversing the dataset, each entry is passed with already preprocessed features so that features that need to have their values extracted and set separately are processed here. Also, if several features are setup to location their values in same entry's property - it is also done here. fnValue function (the same passed to processDataset()) can participate in the process, it has the following definition: fnValue(oldValue, newValue).

jToxCompound.extractFeatures(entry, features, callback)

A shorthand function which extracts all feature values from the given entry, processing them according to features definitions passed, filters out those with empty titles, and returns an array of features, with one field added - value. On each added entry callback is called in this manner function (feature, featureId) (after value property is set) and if the returned value is false the feature entry is not added at all.

<jToxCompound>.queryDataset(datasetUri)

The starting point of dataset visualization. This function makes a separate call for feature-retrieving, preprocesses them (as described above), prepares the visualization table, showing or hiding, whatever is needed and calls processEntries for actual dataset entries' retrieval. Cannot be called several times within same instance.

<jToxCompound>.queryEntries(start, size)

The actual dataset entries retrieving function. It makes call to get entries from the already set up dataset, starting from start-th one and asking for size of them. All pagination UI elements are updated, if not hidden.

<jToxCompound>.equalizeTables()

A UI-related, function which takes care the two tables - fixed and variable parts, to be with equally sized rows - it is handy when some manual changing of values within the table cells is performed from outside. Normally it is not necessary to call it, because all details opening, filtering, etc. takes care to call it internally.

<jToxCompound>.nextPage()
<jToxCompound>.prevPage()

These two are shortcuts for the previous function, taking into account the current page size and also taking care not to query for something outside of the known limits of the dataset.

<jToxCompound>.filterEntries(needle)

Filter the presented entries with the given needle, finding substring match on each features, not marked with search: false in their definition.

jToxSubstance kit

This kit is responsible for substance browsing, pretty much the same way jToxCompound is responsible for compound browsing. However, for this one it is more simplistic, because it happens on single table and with less controls.

Parameters

The kit has the following parameters:

Methods

Methods of this kit that can be used are:

<jToxSubstance>.querySubstance(uri)

As expected - it initiates a query for list of substances. Some paging information can be present in the URI - it is stripped, remembered and used. Also it overides the ones, provided with settings, if any.

<jToxSubstance>.query(uri)

A shorthand for the previous method.

<jToxSubstance>.nextPage()
<jToxSubstance>.prevPage()

Pagination control - works as expected, taking care not to go after the end, or before the beginning.

Configuration

As usually, columns can be configured. They are wrapped in the substance category. Here is how the default one looks like:

    configuration: { 
      columns : {
        substance: {
          'Id': { sTitle: 'Id', mData: 'URI', sDefaultContent: "-", sWidth: "60px", mRender: ...},
          'Substance Name': { sTitle: "Substance Name", mData: "name", sDefaultContent: "-" },
          'Substance UUID': { sTitle: "Substance UUID", mData: "i5uuid", mRender: ...},
          'Composition Type': { sTitle: "Composition Type", mData: "substanceType", sWidth: "15%", sDefaultContent: '-' },
          'Public name': { sTitle: "Public name", mData: "publicname", sDefaultContent: '-'},
          'Reference substance UUID': { sTitle: "Reference substance UUID", mData: "referenceSubstance", mRender: ...},
          'Owner': { sTitle: "Owner", mData: "ownerName", sDefaultContent: '-'},
          'Info': { sTitle: "Info", mData: "externalIdentifiers", mRender: ...}
        }
      }
    }

jToxStudy kit

This kit gives front-end to AMBIT services, which provide import of IUCLID5 generated and maintained data for toxicological studies (experiments). The kit name is study (for use in data-kit initialization attribute). First, there are several additional

Dependencies

From jQueryUI Version 1.8+, based library jQueryUI tabs and jQuery based DataTables Version 1.9+. For column resizing we also depend on colResizable, which in turn needs jQuery migrate plugin for its reference of $.explorer - feel free not to include the latest, if you don't have such error from colResizable (they might update not to use it, some day).

    <link rel="stylesheet" href="https://github.com/ideaconsult/Toxtree.js/blob/master/jquery.ui.tabs.css"/>
    <link rel="stylesheet" href="https://github.com/ideaconsult/Toxtree.js/blob/master/jquery.dataTables.css"/>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery-migrate-1.2.1.min.js"></script>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/colResizable-1.3.min.js"></script>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.ui.widget.js"></script>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.ui.tabs.js"></script>
    <script src="https://github.com/ideaconsult/Toxtree.js/raw/master/jquery.dataTables.js"></script>

These are needed in the same page in order for jToxStudy to work. It has some additional

Parameters

Not quite a lot yet, mainly event handlers:

Configuration

The configuration structure as passed to the kit initialization or references with data-config-file is used to give column visibility and re-naming possibilities. An example of valid configuration object / json is this:

{
    "columns": {
        "_": { 
            "main": { 
                "name": { "bVisible": false } 
            },
            "effects": {
                "endpoint": { "sTitle": "Type", "iOrder": -2 },
                "result": { "sTitle": "Value", "iOrder": -1 }
            }
        },
        "PC_PARTITION_SECTION": {
            "effects": {
                "endpoint": { "iOrder": 0 },
                "result": { "iOrder": 0 }
            }
        }
    }
}

All column redefinitions are following dataTables syntax, but only parameters that need to be changed are given. Additional iOrder is used to make reordering of the column in the table. The rule is:

The standard bVisible parameter can be present (usually only for hiding) which makes the column absent from column definitions at all.

Each column (re)definitions are grouped on several levels:

So the actual column re-definition goes like this:

The array of so built columns is then sorted on iOrder and passed to dataTables initialization.

Methods

jToxStudy methods that can be invoked from outside are quite few, actually:

new jToxStudy(root, settings)

It is called either internally from jToxKit upon initialization, or later from the user. The first parameter is an HTMLElement which will be used for base for populating necessary DOM tree. It returns a new instance of jToxStudy, referred as <jToxStudy> that can later be queried with methods, described below:

<jToxStudy>.querySubstance(substanceUri)

If substanceUri parameter is not provided during initialization, this is the way to ask for studies for particular substance. Fill's up the fist tab and queries for composition and studies summary.

<jToxStudy>.queryComposition(substanceUri)

The substanceUri is the same as in previous function, but this one takes care only for Composition tab. Usually called automatically from previous function, when it successfully retrieved substance information.

<jToxStudy>.querySummary(substanceUri)

The substanceUri is the same as in previous function. This one queries for a summary of all studies available for the given substance. It fills up the numbers in the studies' tabs and prepares the tables for particular queries later on, which are executes upon each tab's activation.

jToxDataset kit

The dataset(s) browsing kit - if jToxCompound is browsing entries within a data, this kit is browsing datasets on a server. It is rather simple and is mainly used as a widget within jToxQuery kit.

Parameters

There are few things that can be setup from outside:

Methods

They are not plenty - just a few:

<jToxDataset>.listDatasets(uri)
<jToxDataset>.query(uri)

Makes a query for retrieving the list of datasets from the server. If uri passed is null - the default form: <baseURL>/dataset is used.

<jToxDataset>.modifyUri(uri)

The required method for this kit to be part of jToxQuery kit. What it does is to scan all input boxes, which means selectable should be set to true, and add dataset_uris[]=<selected uri> parameter to the given uri for each of selected datasets.

There are several public static methods, that can be used from elsewhere:

jToxDataset.putStars(kit, stars, title)

Returns an html text with given amount of stars put, taking into account the kit's settings for maxStars and shortStars. The title is the tooltip that is set for the block.

jToxDataset.addSelection(kit, oldFn)

Returns a dataTables rendering function (i.e. function (data, type, full)), using the provided old one - oldFn, and adding a selection box, with proper handling before it.

Configuration

All the columns of the table can be configured, the same way jToxStudy does. All column definitions are found under dataset property. The default set looks like this:

configuration: { 
  columns : {
    dataset: {
      'Id': { iOrder: 0, sTitle: "Id", mData: "URI", sWidth: "50px", mRender: function ... },
      'Title': { iOrder: 1, sTitle: "Title", mData: "title", sDefaultContent: "-" },
      'Stars': { iOrder: 2, sTitle: "Stars", mData: "stars", sWidth: "160px" },
      'Info': { iOrder: 3, sTitle: "Info", mData: "rights", mRender: function ... }
    }
  }
}

More columns can be added, or these can be turned off just by adding bVisible: false to the certain definition.

jToxModel kit

The model(s) and algorithm(s) browsing kit - pretty similar to jToxDataet as functionality and configuration. However, it has two modes of running - algorithm listing or model listing, and it is upon initialization. This kit is mainly used as a widget within jToxQuery kit.

Parameters

There are few things that can be setup from outside:

Methods

They are not plenty - just a few:

<jToxModel>.listModels(uri)

Makes a query for retrieving the list of models from the server. If uri passed is null - the default form: <baseURL>/model is used.

<jToxModel>.listAlgorithms(needle)

Makes a query for retrieving all available algorithms from the server. If needle is passed it is used in the search of the form: <baseURL>/algorithms?search=<needle>.

<jToxModel>.query(uri)

This is a shortcut to either listModels() or listAlgorithms() method, depending on settings.algorithms parameter.

<jToxModel>.modifyUri(uri)

The required method for this kit to be part of jToxQuery kit. What it does is to scan all input boxes, which means selectable should be set to true, and add feature_uris[]=<selected uri> parameter to the given uri for each of selected models.

<jToxModel>.getModel(algoUri, callback)

Gets or creates a model for given algorithm. If forceCreate is not specified in the options it first asks the server for such model, only if that fails - it makes a PUSH request to create a new one, then polls the given task. In any case - the callback is called after all is done - either with the modelURI, or with null if everything fails. This is the first parameter, the second is jQuery's ajax, jhr parameter.

<jToxModel>.runPrediction(datasetUri, modelUri, callback)

Instructs the server to run a prediction of modelUri onto given datasetUri and calls callback when all is done with object in dataset format as first parameter (or null, on fail) and jQuery's ajax jhr parameter as second. Again - the method first asks the server if it has predictions for this model and dataset cached, and if not - it initiates a task for prediction, polls it until is done and only then invokes the callback.

Configuration

All the columns of the table can be configured, the same way jToxStudy does. All column definitions are found under model or algorithm properties, depending on the mode the kit is running. The default set looks like this:

configuration: { 
  columns : {
    model: {
     'Id': { iOrder: 0, sTitle: "Id", mData: "id", sWidth: "50px", mRender: function ... },
     'Title': { iOrder: 1, sTitle: "Title", mData: "title", sDefaultContent: "-" },
     'Stars': { iOrder: 2, sTitle: "Stars", mData: "stars", sWidth: "160px" },
     'Algorithm': {iOrder: 3, sTitle: "Algorithm", mData: "algorithm" },
     'Info': { iOrder: 4, sTitle: "Info", mData: "trainingDataset", mRender: function ... }
    },
    algorithm: {
     'Id': { iOrder: 0, sTitle: "Id", mData: "id", sWidth: "150px", mRender: function ... },
     'Title': { iOrder: 1, sTitle: "Title", mData: "name", sDefaultContent: "-" },
     'Description': {iOrder: 2, sTitle: "Description", sClass: "shortened", mData: "description", sDefaultContent: '-' },
     'Info': { iOrder: 3, sTitle: "Info", mData: "format", mRender: function ... }
    }
  }
}

More columns can be added, or these can be turned off just by adding bVisible: false to the certain definition.

jToxQuery kit

A general purpose kit, that wraps several others to make them work together. For example - in the normal query & browse user experience, when you need to define certain criteria for your search and have a browser interpret them - you actually have one browser component and one or more other, that alter the actual data to be browsed, i.e. - they alter the server queries that are made to obtain the data to be browsed. The key aspect of jToxQuery is that it is independent of underlying components (kits). Of course, it relying on certain structure and behaviour.

There are two type of sub-kits: main kit (only one) and widgets (zero or more). There is one way to determine which is which - widgets have jtox-widget class added to their root element. All such are enumerated and treated a bit different.

There is another important term here: handler, these are DOM elements that should initiate some kind of action via jToxQuery. These can be input elements, select, button, etc. - anything that reacts on change or click events. They to mark an element as handler-active is to add jtox-handler to it's classes and then specify the name of the handler to be called, via data-handler attribute. Doing so, jToxQuery will take care to invoke this handler, when a change/click happens on this element.

How are handlers specified? Using the standard configuration mechanism - there is a handler object under configuration key, which is in jToxQuery's settings. This is how the default settings for jToxQuery look like:

{ 
  configuration: {
    // this is the main thing to be configured
    handlers: { 
      query: function (el, query) { query.query(); },
    }
  }
};

As can be seen, each handler function is passed two arguments: el - the element which provoked this handler, to be called, and query - the instance of jToxQuery which is mitigating the call. Having that, if you define button in your HTML:

<button name="searchbutton" class="jtox-handler" title="Search" data-handler="query"><span class="ui-icon ui-icon-search"/></button>

You'll have jToxQuery call the query() method of the main kit each time the user presses this button.

There are two ways to enrich this list of handlers - pass proper configuration to the jToxQuery kit itself, or call <jToxQuery>.addHandlers(handlers) passing an object with additional handlers that you intend to use. They way to find kit's parent jToxQuery instance is using jToxKit.parentKit(jToxQuery, <kit's root element>) method, described above.

Parameters

There are few things that can be setup from outside:

Methods

There are just a few method of these kit:

jToxQuery.queryKit(element)

Returns the instance of jToxQuery kit, which is rooted in the closest parent of passed element. This is the way a widget, or main kit to find which jToxQuery it belongs to - passing it's rootElement, for example.

<jToxQuery>.widget(name)

Returns an instance of a widget, with given name

<jToxQuery>.addHandlers(handlers)

Adds the supplied set of handlers to the handler list recognized and used by jToxQuery. Without doing this referring them at certain DOM elements won't have any effect.

<jToxQuery>.kit()

Returns the main kit, that is managed by this jToxQuery instance.

<jToxQuery>.query()

The most important function of the kit - the one that actually incorporates all widgets and the main kit to provide the final functionality. What it does, is to walk on all widgets and ask them to alter one and the same URI, using their modifyUri() method. The loop looks like this:

uri = widget.modifyUri(uri);

The initial value of uri is the passed service or empty one. After the uri is build this way, a call to main kit's query() is made -- et voilà!

jToxSearch kit

A universal search banner kit, which integrates with jToxQuery to provide different ways of querying the main components, wrapped with jToxQuery. There are four search methods currently: auto, similarity, smarts and url, which are presented with different buttons.

It also provides integration with ketcher compound editor, ensuring bi-directional connection between the drawing and the search needle field.

Parameters

There are few things that can be setup from outside:

Methods

There are just a few method of these kit:

<jToxQuery>.setAuto(needle)

Sets the search needle, also resetting the search method to auto.

<jToxQuery>.setMol(mol)

Sets the search needle to mol, by remembering the given data, also resetting the search method to mol.

<jToxQuery>.getNeedle()

Returns the current search needle - be it, as displayed in the search box, or as stores mol compound structure definition.

<jToxQuery>.makeQuery(needle)

Initiates a query, by asking the wrapping jToxQuery kit, for the main component providing the queries. If needle is supplies - it makes a setAuto() call first, i.e. - resets the method to auto and the searching needle.

jToxLog kit

A network requests logger, providing feedback for success or failure on each call. Normally it should be put somewhere in the beginning of the page, so it can auto-install itself on the instance of jToxKit, which will make it available for all kits, during settings inheritance mechanism.

The notifications handled are onConnect, onSuccess and onError - and the requested service (see jToxKit.call()) is used as identifier for updating status changes.

Parameters

There are few things that can be setup from outside:

Methods

They are pretty straightforward:

<jToxLog>.install(kit)

Installs the logger for given kit. If kit is null - the (only) instance of jToxKit is used, which means that all calls are passed to the logger. If resend setting is set to true the original handlers for this kit are still called.

<jToxLog>.revert(kit)

Restores the old handlers for the kit.

How is made and how to build?

The following information is not intended for end users, but it gives a detailed overview of the procedure and layout of development and building of jToxKit.

General concept - js, html, css files, merging, templates, etc.

As described in the beginning, the main concept is to allow easy use of the whole toolkit - even easier than jQuery-based widgets and libraries. This usually contradicts with ease of development. That's why we established certain structure and rules of development process, so we can keep it easy, while providing ways for automatic production of end-user files for user-page integration.

In order to archive this, these rules are followed:

In order to archive these there are few things that we've established

File naming

Each different kit, presumably needs three files: one JS, one HTML and one CSS. They all need to have same names, built like this: tox<kit name>.<extension>. For example for study kit, the three files are:toxstudy.html, toxstudy.js and toxstudy.css.

There is also one, general set - for the jToxKit as a whole. It has slightly different convention: jT.<extension>. The key moment here is that toxstudy.html for example, is used during the development of jToxStudy, referring jQuery, jQueryUI, jtoxkit.js, etc. files. In the same time - it is the source for final, production jtoxkit.js file.

Script and styling files merging

During [Building procedure](#Building procedure) all script and styling files are merged together to result in one javascript and one cascading stylesheets file. It is (optionally) minified after that.

The order of merging is not specified, except the fact that jtoxkit.js (.css) is put last.

HTML files processing

Here comes the most interesting part - how to have development-ready HTML file and source provider for the final, production, js files in the same time? It is achieved by adding special tags:

    <!--[[ jT.templates['mytempname'] -->
    <div>…</div>
    <!-- ]]-->

Being an actual HTML comment it is well ignored during development. The special format of the comment, however, enables a script to convert this to following JavaScript code:

    jT.templates['mytempname'] =
    "<div>…</div>" +
    "";

Of course, it may have more than one lines, and also it is not necessary to be jT.template[] entry. However, jT.template entries are automatically processed during jT.init(), and everything in there becomes the (HTML) content of specially added <div class="jtox-template"></div> element in the end of body of the target, user's page.

They also enable nesting, i.e.:

    <!--[[ jT.templates['outerTemp'] -->
    <div>Some initial lines here
    <!--[[ jT.templates['innerTemp'] -->
    <div>More sub-template lines</div>
    <!-- // end of inner ]]-->
    </div>
    <!-- // end of outer ]]-->

will result in the following JavaScript code:

    jT.templates['outerTemp'] =
    "<div>Some initial lines here";

    jT.templates['innerTemp'] =
    "<div>More sub-template lines</div>" +
    ""; // end of inner

    jT.templates['outerTemp'] +=
    "</div>" +
    ""; // end of outer
Building scripts

There are two scripts, involved in the process:

Building procedure

It is as simple as running the build.sh script! It can, even be run without parameters which will result in building all kits, not minifying them:

$ ./build.sh 
Clearing old files...
Backing tool [ketcher]...
Processing targets [common toxcompound toxstudy jtoxkit]...
Merging JS files from [../scripts] ...
Adding html2js transformed ones from [..]...
Merging CSS files from [../styles] ...
Done.

However, there are few parameters that can be provided, mainly for setting new paths:

Usage: build.sh [options]
Options can be one or more from the following:

    [--min | -m]           : run minification of the output js, producing additional .min.js file.
        [--clean | -c]         : clean all pre-existing files in the output folder.
    [--html <html dir>]    : the directory where html files live. Default is [..].
    [--out <output dir>]   : the directory where output files should be put. Default is [../www].
    [--css <styles dir>]   : the directory where styling files live. Default is [../styles].
    [--js <js dir>]        : the directory where script files live. Default is [../scripts].
    [--target <kit list>]  : list of kits to be included. Omit jtoxkit. Default [toxstudy].
    [--lib | -l <filename>]: html file name, referring to some external library (tool).
    [--help | -h]          : this help.

Default is like: build.sh --html .. --out ../www --css ../styles --js ../script --target toxstudy

The result of this script can be directly used. There is a test page for proper result, which should not produce errors when opened in the browser test.html.

A word on external tools / libraries

You can include certain libraries to be packed during building process. Like it is done with ketcher. The way it is designed to happen is:

With the given example the call is:

jT.insertTool('ketcher', jT.$('#ketcher-test')[0]);

Any additional initialization that the particular tool needs, has to be called separately.

jToxKit new generation

https://github.com/ideaconsult/jToxKit