EternaScript Documentation

View All Scripts

Utility APIs

Pervasives

  • out(text)

    display text in result textarea

  • outln(text)

    display text in result textarea with newline

  • clear()

    clear result textarea

Library functions

  • Lib.bases

    "AGCU"

  • Lib.fold(sequence)

    return folded structure with sequence

    ex) Lib.fold("GGGGCCCC") = "((....))";

  • Lib.energyOfStruct(sequence, structure)

    return energy of structure

  • Lib.EternaScript(script id)

    return other user's script

    ex) var func = Lib.EternaScript(script_id);

    ex) func(parameters);

  • Lib.getStructure(puzzle_id)

    return structure of puzzle

    ex) Lib.getStructure(1001759)

  • Lib.replace(sequence, index, target)

    return sequence which character at index in sequence replaced to target

    ex) Lib.replace("AGCU", 2, "A") = "AGAU";

  • Lib.nextSequence(sequence)

    return next sequence of sequence in the order of default bases

    ex) Lib.nextSequence("AAAA") = "GAAA";

  • Lib.nextSequenceWithBases(sequence, bases)

    return next sequence of sequence in the order of bases

    ex) Lib.nextSequenceWithBases("UUUU", "UCGA") = "CUUU";

    ex) Lib.nextSequenceWithBases("AUAA", "UCGA") = "UCAA";

  • Lib.random(from, to)

    return random number between from and to

  • Lib.randomSequence(size)

    return random sequence with length of size

  • Lib.map(function, sequence)

    applies function to each sequence bases

  • Lib.filter(function, sequence)

    return sequences only satisfy the function

  • Lib.splitDefault(structure)

    split structure into a structure array

    ex) Lib.splitDefault("((..))") = ["((", "..", "))"];

  • Lib.join(array)

    join array with each element to sequence

    ex) Lib.join(Lib.split("((..))")) = "((..))";

  • Lib.distance(source structure, destination structure)

    return differences between source structure and destination structure

    if same then 0 else +1

    if different length then just return -1

    ex) Lib.distance("((..))", "((()))") = 2

    ex) Lib.distance("(((())))", "(())") = -1

  • Lib.distanceCustom(function, source structure, destination structure)

    return differences between source structure and destination structure with custom rule

    ex) Lib.distanceCustom(function(index){ ... }, source, dest);

Class RNA

  • getPairmap(structure)

    return the array of pair information

    ex) getPairmap("((..))") = [5,4, , ,2,1]

  • getStructure

    return structure

  • getRootElement

    return root RNAElement class of rna object

  • map

    applies function to all RNAElement

Class RNAElement

  • getParent()

    return the parent RNAElement class

  • getChilds()

    return the child RNAElement class array

  • getElements()

    return the array of structure and index JSON objects

  • isPaired()

    return boolean whether the stack element is paired or not

  • getBaseType()

    return RNAElement.Stack or RNAElement.Loop if the element is stack or loop

  • getType()

    return RNAElement.Hairpin, RNAElement.Bulge, RNAElement.Internal, RNAElement.Multiloop or RNAElement.Dangling if the element is hairpin, bulge, internal, multiloop or dangling

  • getIndices()

    return the array of indices

  • isStack()/isLoop()/isHairpin()/isBulge()/isInternal()/isMultiloop()/isDangling()

    return boolean whether the element is stack, loop, hairpin, bulge, internal, multiloop or dangling

  • getSegmentCount()

    return how many structure segments included

    if the multiloop consists of 2 branches then getSegmentCount() of multiloop returns 2

Booster APIs

General structure

Accessing the applet
var applet = document.getElementById('maingame');
if (applet == null) return "maingame element missing";

from there, APIs can be used like this:

var ok = applet.set_sequence_string(my_seq);
Exploring the API without writing a booster

Every modern browser has some sort of console that lets users input javascript commands.

  • Open the puzzle
  • Open the javascript console of your browser
  • Because the game is loaded in an iframe, you will need to change the console to run commands within the iframe instead of the top-level website page. Somewhere in the console window, there should be a dropdown, likely with "Top" currently selected which will need to be changed to something like "game" or "EternaJS".
Synchronous vs Asynchronous

In order to ensure that multiple boosters and user interaction do not interfere with each other, boosters are run one at a time and the UI is locked preventing user input while a booster is running. For "synchronous" scripts (which do all their work immediately and without stopping), this "just works". However, if a script performs any actions asyncronously (eg using setTimeout/setInterval, promises/async/await, asyncronous network requests, etc), the game will think your code has already ended, when it will actually be running some code after it initially finishes executing and returns a result (either via an explicit return or running to the end of the script).

Because of this, in order for asyncronous scripts to be properly handled, it needs to indicate that it is asyncronous and let the game know once it has completed. This is done by the script ending with the statement return {async: "true"}; and then once it is actually complete, calling applet['end_'+sid](r); where sid is the ID of the script.

EternaScripts also have timeout-checking statements automatically inserted in loops. This causes the code to stop if the script has been running for more than (by default) 10 seconds. In asyncronous scripts, you are likely going to be running code after that timeout happens. To prevent this behavior, you can use the statement global_timer = new Date();.

For an example of a syncronous booster, see the Tsumego script. For an example of a asyncronous booster, see the Naive Solver script.

Getters

  • get_sequence_string()

    Parameters: none

    Returns: a string representing the sequence

  • get_full_sequence(index)

    Parameters:

    • index: 0-based index of the state to be queried

    Returns: a string representing the full-length sequence, including the oligos in the case of a multistrand puzzle

  • get_locks()

    Parameters: none

    Returns: a 0-based array of booleans indicating locked (true) and mutable (false) positions in the puzzle

  • get_targets()

    Parameters: none

    Returns: an array of objects describing the structural constraints of each state in the puzzle

  • get_target_structure(index)

    Parameters:

    • index: 0-based index of the state to be queried

    Returns: the dot-bracket representation of the target structure for the given state (which include modifications made by magic glue, if applicable)

  • get_native_structure(index)

    Parameters:

    • index: 0-based index of the state to be queried

    Returns: the dot-bracket representation of the predicted MFE for the queried state in the puzzle (i.e. the native fold)

  • get_full_structure(index)

    Parameters:

    • index: 0-based index of the state to be queried

    Returns: the complete dot-bracket representation of the predicted MFE, including oligos, for the queried state in the puzzle (i.e. the native fold)

  • get_free_energy(index)

    Parameters:

    • index: 0-based index of the state to be queried

    Returns: the free energy of the queried state

  • get_tracked_indices()

    Parameters: none

    Returns: an array listing the indices of the bases that have been marked with the black mark

  • get_barcode_indices()

    Parameters: none

    Returns: an array listing the indices of the bases forming the barcode, if present in the lab puzzle

  • is_barcode_available()

    Parameters: none

    Returns: a boolean describing whether the barcode in the puzzle is still available for the current round or not

  • current_folder()

    Parameters: none

    Returns: the name of the currently selected folding engine (only available in labs)

  • get_puzzle_id()

    Parameters: none

    Returns: a number, the currently loaded puzzle ID

  • get_solution_id()

    Parameters: none

    Returns: a number, the currently loaded solution ID, or undefined if no existing solution loaded

  • get_custom_numbering_to_index()

    Parameters: none

    Returns: for puzzles that have custom base numbering, an array mapping the custom base number to the original base index

  • get_index_to_custom_numbering()

    Parameters: none

    Returns: for puzzles that have custom base numbering, an array mapping the original base index to the custom base number

  • check_constraints()

    Parameters: none

    Returns: boolean indicating whether or not all constraints have been satisfied

  • constraint_satisfied(index)

    Parameters:

    • index: the index of the constraint to check

    Returns: boolean indicating whether or not the constraint at the given index have been satisfied

Setters

  • set_sequence_string_async/set_target_structure_async/select_folder_async

    These methods behave identically to their non-_async counterparts, however they run asyncronously, returning a promise that resolves with their result once they complete. These methods should be preferred over the syncronous versions because they will work for engines that are only available asyncronously and in the future may have the ability to run without causing the page to "freeze" during long computations. Be aware that if you do not wait for the promises to be resolved before using other APIs, it will likely cause an error to be thrown in order to prevent incorrect behavior due to attempting to get or change data while folding/modifications are still in progress.

  • select_folder(folder_name)

    selects a folding engine by its name. only available in lab puzzles.

    Parameters:

    • folder_name: name of the folding engine to be used

    Returns: a boolean, true if successful, false otherwise (the operation may fail, for instance Vienna2 cannot be selected on a puzzle that contains multistrand states)

  • set_sequence_string(seq)

    sets the sequence in the puzzle. the applet recomputes foldings, free energies and reevaluates contraints.

    Parameters:

    • seq: the sequence

    Returns: a boolean, a boolean, true if successful, false otherwise (the operation may fail, if seqcontains invalid characters for instance)

  • set_tracked_indices(marks, options = null)

    sets base rings/black marks in the puzzle

    Parameters:

    • marks: an array where entries are either indices of bases to be marked (to mark with the default black ring) or objects containing a baseIndex and optional color property (color should be a numeric RGB color value, eg 0x000000 for black, 0xFFFFFF for white, 0xFF0000 for red, etc)
    • options: an object containing an optional layerName property which can be used to place marks on a separate, named, user-selectable layer (by default, they will be placed on the "Script" layer). Note that all current base rings on the selected layer are replaced

    Returns: nothing

  • set_target_structure(index, structure, startAt = 0)

    sets the current target structure, if allowed (ie, in situations where magic glue can be used). operates identically to the paste target structure dialog

    Parameters:

    • index: 0-based index of the state to set the target structure for
    • structure: dot-bracket representation of the desired target structure
    • startAt: the index of the first base to start changing the target structure at

    Returns: nothing

Folding

  • fold_async/fold_with_binding_site_async/energy_of_structure_async/energy_of_structure_async /pairing_probabilities_async/subopt_single_sequence_async/subopt_oligos_async /cofold_async/get_defect_async

    These methods behave identically to their non-_async counterparts, however they run asyncronously, returning a promise that resolves with their result once they complete. These methods should be preferred over the syncronous versions because they will work for engines that are only available asyncronously and in the future may have the ability to run without causing the page to "freeze" during long computations.

  • fold(seq, constraint = null)

    folds a sequence, eventually considering limitations defined in constraint

    Parameters:

    • seq: a string representing the sequence to be folded
    • constraint: optional constraints (Vienna formatted, if applicable for the currently selected engine)

    Returns: the dot-bracket representation of the MFE structure

  • energy_of_structure(seq, secstruct)

    for engines that support it, computes the free energy of a sequence folded as specified by secstruct

    Parameters:

    • seq: the sequence
    • secstruct: the dot-bracket representation of the secondary structure

    Returns: a floating-point number, expressed in kcal/mol

  • fold_with_binding_site(seq, site, bonus)

    for engines that support it, folds a sequence with a bonus at a particular location for a ligand

    Parameters:

    • seq: a string representing the sequence to be folded
    • site: array of base indices describing the binding site of the ligand
    • bonus: energy bonus of the ligand

    Returns: the dot-bracket representation of the MFE structure

  • cofold(seq, oligo, malus = 0.0, constraint = null)

    for engines that support it, folds a sequence with a secondary RNA strand

    Parameters:

    • seq: a string representing the sequence to be folded
    • oligo: a string representing the sequence of the secondary RNA strand
    • malus: factor representing the concentration of the secondary RNA strand
    • constraint: optional constraints (Vienna formatted, if applicable for the currently selected engine)

    Returns: the dot-bracket representation of the MFE structure

  • pairing_probabilities(seq, secstruct = null)

    for engines that support it, computes the pairing probabilities/dot plot for a sequence

    Parameters:

    • seq: a string representing the sequence to get the pairing probabilities for
    • secstruct: a dot-bracket string representing the target structure ("lower left" of the dot plot)

    Returns: the pairing probabilities as a sparse coordinate matrix (an array of the form [i1, j1, val1, i2, j2, val2, ...], omitting matrix entries where the value is zero)

  • subopt_single_sequence(seq, kcalDelta, pseudoknotted = false, temp = 37)

    for engines that support it, folds a sequence and retrieves information about possible suboptimal structures

    Parameters:

    • seq: a string representing the sequence to be folded
    • kcalDelta: a number, in kcals per mol, specifying how far from the MFE suboptimal structures should be included
    • pseudoknotted: a boolean indicating whether or not pseudoknots should be considered (if supported by the selected engine)
    • temp: folding temperature (if supported by the selected engine)

    Returns: an object with the properties suboptStructures (an array of dot-bracket strings of suboptimal structures), suboptEnergyError (an array of numbers corresponding to the suboptimal structures indicating their energy error), and suboptFreeEnergy (an array of numbers corresponding to the suboptimal structures indicating their free energy)

  • subopt_oligos(seq, oligos, kcalDelta, pseudoknotted = false, temp = 37)

    for engines that support it, folds a sequence along with some secondary RNA strands and retrieves information about possible suboptimal structures

    Parameters:

    • seq: a string representing the sequence to be folded
    • oligos: an array of strings representing the secondary oligo sequences
    • kcalDelta: a number, in kcals per mol, specifying how far from the MFE suboptimal structures should be included
    • pseudoknotted: a boolean indicating whether or not pseudoknots should be considered (if supported by the selected engine)
    • temp: folding temperature (if supported by the selected engine)

    Returns: an object with the properties suboptStructures (an array of dot-bracket strings of suboptimal structures), suboptEnergyError (an array of numbers corresponding to the suboptimal structures indicating their energy error), and suboptFreeEnergy (an array of numbers corresponding to the suboptimal structures indicating their free energy)

  • get_defect(seq, secstruct, pseudoknotted = false, temp = 37)

    for engines that support it, calculates the ensemble defect of the given sequence and structure

    Parameters:

    • seq: a string representing the sequence to be folded
    • secstruct: the dot-bracket target structure
    • pseudoknotted: a boolean indicating whether or not pseudoknots should be considered (if supported by the selected engine)
    • temp: folding temperature (if supported by the selected engine)

    Returns: an object with the properties suboptStructures (an array of dot-bracket strings of suboptimal structures), suboptEnergyError (an array of numbers corresponding to the suboptimal structures indicating their energy error), and suboptFreeEnergy (an array of numbers corresponding to the suboptimal structures indicating their free energy)

Miscellaneous

  • sparks_effect(from, to)

    initiates a sparking effect on the specified segment

    Parameters:

    • from: start index
    • to: end index

    Returns: nothing

  • submit_solution(details = 'prompt', options = null)

    in experimental puzzles, submits the currently loaded solution.

    Parameters:

    • details: either be 'prompt' (the default) to show the submission dialog to ask for a title and description, or you can pass an object with the properties title and description (if either title or description are not specified, the default will be used like if you left the fields blank in the dialog)
    • options: an object with the following properties:
      • validate: a boolean, controls whether optional validation is performed - that is, the validation where a player can normally choose to bypass in a dialog, ie whether non-required constraints are satisfied and validating that all pairs are valid in the context of a custom structure. By default, validation is enabled
      • notifyOnError: a boolean, controls whether errors in the submission process are shown to the user. If true (the default), the user will be shown the normal dialogs that allow for either continuing or canceling submission for optional validation (if enabled) as well as being shown notification dialogs in the situation of other errors (eg, the backend returns an error because the barcode is unique or the user hasn't unlocked the lab, or other required validation fails)

    Returns: Because this function runs asynchronously (both due to the network request being asynchronous and the potential for users to be prompted), this function returns a Promise

    • The promise will reject if required validation fails or some other unhandled error is encountered
    • The promise will resolve to false if optional validation failed (with validate set to true) and either notifyOnError is false or the user opted to cancel submission in the dialog
    • The promise will resolve to true if the solution was submitted successfully.


Help Eterna invent medicine. Make a donation today.

TwitterFacebookInstagramYouTubeTwitchGitHub