diff --git a/.gitignore b/.gitignore index 655fc7457..140e7be28 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ lib/nlopt2 lib/lfs1 lib/lpeg src/build +tests tests/utests/*_gen.mad tests/utests/*.tfs diff --git a/.gitmodules b/.gitmodules index b491b0b8e..5873ca3c6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,12 @@ [submodule "MADdocs"] path = doc url = https://github.com/MethodicalAcceleratorDesign/MADdocs + update = merge [submodule "MADLibs"] path = bin url = https://github.com/MethodicalAcceleratorDesign/MADLibs + update = merge [submodule "MADpy"] path = pymad url = https://github.com/MethodicalAcceleratorDesign/MADpy + update = merge diff --git a/doc b/doc index 03176946b..05f842eb8 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit 03176946ba19f2985e5e89a999e05b6fba122603 +Subproject commit 05f842eb866f4271e04e68ba9597f55aae8e3632 diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index d0c3cbf10..000000000 --- a/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build -SOURCEDIR = source -BUILDDIR = build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 747ffb7b3..000000000 --- a/docs/make.bat +++ /dev/null @@ -1,35 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=source -set BUILDDIR=build - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.https://www.sphinx-doc.org/ - exit /b 1 -) - -if "%1" == "" goto help - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% - -:end -popd diff --git a/docs/source/_ext/customRoles.py b/docs/source/_ext/customRoles.py deleted file mode 100644 index 71516bcdd..000000000 --- a/docs/source/_ext/customRoles.py +++ /dev/null @@ -1,35 +0,0 @@ -from docutils import nodes -from sphinx import addnodes -from sphinx.locale import _ -from sphinx.domains.c import CDomain, CObject, CXRefRole -from sphinx.domains import ObjType - - -#------May be useful in the future-------- -# class CConstObject(CObject): -# object_type = 'const' - -# object_types = CDomain.object_types -# directives = CDomain.directives -# roles = CDomain.roles - -# object_types['const'] = ObjType(_('const'), 'const', 'identifier', 'type') -# directives['const'] = CConstObject -# roles['const'] = CXRefRole() -#---------------------------------------- - -def unit_role(name, rawtext, text, lineno, inliner, options=None, context=None): - node = nodes.strong(text = text) - return [node], [] - -def type_role(name, rawtext, text, lineno, inliner, options=None, context=None): - node = nodes.emphasis(text = text) - return [node], [] - -def setup(app): - app.add_role("unit", unit_role) - app.add_role("type", type_role) - - return - - diff --git a/docs/source/_ext/pygments_mad_lexer.py b/docs/source/_ext/pygments_mad_lexer.py deleted file mode 100644 index 0e96615e5..000000000 --- a/docs/source/_ext/pygments_mad_lexer.py +++ /dev/null @@ -1,30 +0,0 @@ -# -- Custom Lexer ------------------------------------------------------------ -from pygments.lexers.scripting import LuaLexer -from pygments.token import Comment, Operator - - -class MadLexer(LuaLexer): - """ - Exactly the same as the Lua Lexer, except for the following changes: - New name, aliases, filenames and url (also removed mimetypes) - The comment can also be ! - The character "\\" is now an accepted operator. - """ - - name = 'MAD' - url = "https://mad.web.cern.ch/mad/" - aliases = ['mad'] - filenames = ['*.mad'] - mimetypes = [] - - tokens = { - **LuaLexer.tokens, - 'ws': [ - (r'(?:!.*$)', Comment.Single), - *LuaLexer.tokens["ws"], - ], - 'base': [ - (r'\\', Operator), - *LuaLexer.tokens["base"], - ], - } \ No newline at end of file diff --git a/docs/source/_ext/sphinx-mad-domain.py b/docs/source/_ext/sphinx-mad-domain.py deleted file mode 100644 index 80c0ae942..000000000 --- a/docs/source/_ext/sphinx-mad-domain.py +++ /dev/null @@ -1,948 +0,0 @@ -# -*- coding: utf-8 -*- -""" - sphinx.domains.mad - ~~~~~~~~~~~~~~~~~~ - - The mad domain. - - adapted from sphinxcontrib-luadomain - :author: Eloitt Dumeix - :liscence: BSD, see LICENSE for details - - - Also from sphinx: - :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import re -from docutils import nodes -from docutils.parsers.rst import Directive, directives -from sphinx import addnodes -from sphinx.roles import XRefRole -from sphinx.domains import Domain, ObjType, Index -from sphinx.directives import ObjectDescription -from sphinx.locale import get_translation -from sphinx.util import logging -from sphinx.util.nodes import make_refnode -from sphinx.util.docfields import Field, GroupedField, TypedField -from sphinx.environment import BuildEnvironment -from sphinx.builders import Builder -from typing import Any, Dict, Iterable, Iterator, List, Tuple, Optional, Union - -MESSAGE_CATALOG_NAME = 'sphinx-mad-domain' -_ = get_translation(MESSAGE_CATALOG_NAME) - -logger = logging.getLogger(__name__) - -# REs for Mad signatures -mad_sig_re = re.compile( - r'''^ ([\w.]*[\.\:])? # class name(s) - (\w+) \s* # thing name - (?: \((.*)\) # optional: arguments - (?:\s* -> \s* (.*))? # return annotation - )? $ # and nothing more - ''', re.VERBOSE) - - -def _pseudo_parse_arglist(sig_node: addnodes.desc_signature, arg_list: str) -> None: - """"Parse" a list of arguments separated by commas. - - Arguments can have "optional" annotations given by ending in an underscore - """ - param_list = addnodes.desc_parameterlist() - for argument in arg_list.split(','): - # if argument[-1] == "_": #Here in case we would like to do anything with optional arguments - # param_list += addnodes.desc_optional(argument, argument) - # else: - param_list += addnodes.desc_parameter(argument, argument) - sig_node += param_list - - -class MadField(Field): - pass - - -class MadGroupedField(GroupedField): - pass - - -class MadTypedField(TypedField): - pass - - -class MadObject(ObjectDescription): - """ - Description of a general Mad object. - - :cvar allow_nesting: Class is an object that allows for nested namespaces - :vartype allow_nesting: bool - """ - option_spec = { - 'noindex': directives.flag, - 'module': directives.unchanged, - 'annotation': directives.unchanged, - 'virtual': directives.flag, - 'protected': directives.flag, - 'abstract': directives.flag, - 'deprecated': directives.flag, - } - - doc_field_types = [ - MadTypedField('parameter', label=_('Parameters'), - names=('param', 'parameter', 'arg', 'argument', - 'keyword', 'kwarg', 'kwparam'), - typerolename='class', typenames=('paramtype', 'type'), - can_collapse=True), - Field('returnvalue', label=_('Returns'), has_arg=False, - names=('returns', 'return')), - MadField('returntype', label=_('Return type'), has_arg=False, - names=('rtype',), bodyrolename='class'), - ] - - allow_nesting = False - - def get_signature_prefix(self, signature: str) -> str: - """May return a prefix to put before the object name in the - signature. - """ - prefix = [] - - if 'virtual' in self.options: - prefix.append('virtual') - if 'protected' in self.options: - prefix.append('protected') - if 'abstract' in self.options: - prefix.append('abstract') - return ' '.join(prefix) + ' ' - - def needs_arg_list(self) -> bool: - """May return true if an empty argument list is to be generated even if - the document contains none. - """ - return False - - def handle_signature(self, sig: str, sig_node: addnodes.desc_signature) -> Tuple[str, str]: - """Transform a Mad signature into RST nodes. - - Return (fully qualified name of the thing, classname if any). - - If inside a class, the current class name is handled intelligently: - * it is stripped from the displayed name if present - * it is added to the full name (return value) if not present - """ - m = mad_sig_re.match(sig) - if m is None: - raise ValueError - name_prefix, name, arg_list, ret_ann = m.groups() - - # determine module and class name (if applicable), as well as full name - modname = self.options.get( - 'module', self.env.ref_context.get('mad:module')) - class_name = self.env.ref_context.get('mad:class') - if class_name: - add_module = False - if name_prefix and name_prefix.startswith(class_name): - fullname = name_prefix + name - # class name is given again in the signature - name_prefix = name_prefix[len(class_name):].lstrip('.') - elif name_prefix: - # class name is given in the signature, but different - # (shouldn't happen) - fullname = class_name + '.' + name_prefix + name - else: - # class name is not given in the signature - fullname = class_name + '.' + name - else: - add_module = True - if name_prefix: - class_name = name_prefix.rstrip('.') - fullname = name_prefix + name - else: - class_name = '' - fullname = name - - sig_node['module'] = modname - sig_node['class'] = class_name - sig_node['fullname'] = fullname - - sig_prefix = self.get_signature_prefix(sig) - if sig_prefix: - sig_node += addnodes.desc_annotation(sig_prefix, sig_prefix) - - if name_prefix: - sig_node += addnodes.desc_addname(name_prefix, name_prefix) - elif add_module and self.env.config.add_module_names: - modname = self.options.get( - 'module', self.env.ref_context.get('mad:module')) - if modname: - node_text = modname + '.' - sig_node += addnodes.desc_addname(node_text, node_text) - - annotation = self.options.get('annotation') - - sig_node += addnodes.desc_name(name, name) - if not arg_list: - if self.needs_arg_list(): - # for callables, add an empty parameter list - sig_node += addnodes.desc_parameterlist() - if ret_ann: - sig_node += addnodes.desc_returns(ret_ann, ret_ann) - if annotation: - sig_node += addnodes.desc_annotation(' ' + annotation, ' ' + annotation) - return fullname, name_prefix - - _pseudo_parse_arglist(sig_node, arg_list) - if ret_ann: - sig_node += addnodes.desc_returns(ret_ann, ret_ann) - if annotation: - sig_node += addnodes.desc_annotation(' ' + annotation, ' ' + annotation) - return fullname, name_prefix - - def get_index_text(self, modname: str, name: str) -> str: - """Return the text for the index entry of the object.""" - raise NotImplementedError('must be implemented in subclasses') - - def add_target_and_index(self, name_cls: str, sig: str, sig_node: addnodes.desc_signature) -> None: - modname = self.options.get( - 'module', self.env.ref_context.get('mad:module')) - fullname = (modname and modname + '.' or '') + name_cls[0] - # note target - - if fullname not in self.state.document.ids: - sig_node['names'].append(fullname) - sig_node['ids'].append(fullname) - sig_node['first'] = (not self.names) - self.state.document.note_explicit_target(sig_node) - objects = self.env.domaindata['mad']['objects'] - if fullname in objects: - self.state_machine.reporter.warning( - 'duplicate object description of %s, ' % fullname + - 'other instance in ' + - self.env.doc2path(objects[fullname][0]) + - ', use :noindex: for one of them', - line=self.lineno) - objects[fullname] = (self.env.docname, self.objtype) - - indextext = self.get_index_text(modname, name_cls) - if indextext: - self.indexnode['entries'].append(('single', indextext, - fullname, '', None)) - - def before_content(self) -> None: - """Handle object nesting before content - - :mad:class:`MadObject` represents Mad language constructs. For - constructs that are nestable, such as a Mad classes, this method will - build up a stack of the nesting heirarchy so that it can be later - de-nested correctly, in :mad:meth:`after_content`. - - For constructs that aren't nestable, the stack is bypassed, and instead - only the most recent object is tracked. This object prefix name will be - removed with :mad:meth:`after_content`. - """ - prefix = None - if self.names: - # fullname and name_prefix come from the `handle_signature` method. - # fullname represents the full object name that is constructed using - # object nesting and explicit prefixes. `name_prefix` is the - # explicit prefix given in a signature - (fullname, name_prefix) = self.names[-1] - if self.allow_nesting: - prefix = fullname - elif name_prefix: - prefix = name_prefix.strip('.') - if prefix: - self.env.ref_context['mad:class'] = prefix - if self.allow_nesting: - classes = self.env.ref_context.setdefault('mad:classes', []) - classes.append(prefix) - if 'module' in self.options: - modules = self.env.ref_context.setdefault('mad:modules', []) - modules.append(self.env.ref_context.get('mad:module')) - self.env.ref_context['mad:module'] = self.options['module'] - - def after_content(self) -> None: - """Handle object de-nesting after content - - If this class is a nestable object, removing the last nested class prefix - ends further nesting in the object. - - If this class is not a nestable object, the list of classes should not - be altered as we didn't affect the nesting levels in - :mad:meth:`before_content`. - """ - classes = self.env.ref_context.setdefault('mad:classes', []) - if self.allow_nesting: - try: - classes.pop() - except IndexError: - pass - self.env.ref_context['mad:class'] = (classes[-1] if len(classes) > 0 - else None) - if 'module' in self.options: - modules = self.env.ref_context.setdefault('mad:modules', []) - if modules: - self.env.ref_context['mad:module'] = modules.pop() - else: - self.env.ref_context.pop('mad:module') - - -class MadModuleLevel(MadObject): - """ - Description of an object on module level (functions, data). - """ - - def needs_arg_list(self) -> bool: - return self.objtype == 'function' - - def get_index_text(self, modname: str, name_cls: str) -> str: - if self.objtype == 'function': - if not modname: - return _('%s() (built-in function)') % name_cls[0] - return _('%s() (in module %s)') % (name_cls[0], modname) - elif self.objtype == 'data': - if not modname: - return _('%s (built-in variable)') % name_cls[0] - return _('%s (in module %s)') % (name_cls[0], modname) - else: - return '' - - -class MadClassLike(MadObject): - """ - Description of a class-like object (classes, interfaces). - """ - - allow_nesting = True - - CLASS_DEF_RE = re.compile(r'^\s*([\w.]*)(?:\s*:\s*(.*))?') - - def handle_signature(self, sig: str, sig_node: addnodes.desc_signature) -> Tuple[str, str]: - """Transform a Mad signature into RST nodes. - - Return (fully qualified name of the thing, classname if any). - - If inside a class, the current class name is handled intelligently: - * it is stripped from the displayed name if present - * it is added to the full name (return value) if not present - """ - m = self.CLASS_DEF_RE.match(sig) - if m is None: - raise ValueError - - class_name, base_classes_raw = m.groups() - if base_classes_raw: - base_classes = re.findall(r'[\w.]+', base_classes_raw) - else: - base_classes = [] - - # determine module and class name (if applicable), as well as full name - modname = self.options.get('module', self.env.ref_context.get('mad:module')) - classname = self.env.ref_context.get('mad:class') - - sig_node['module'] = modname - sig_node['class'] = classname - sig_node['fullname'] = class_name - - sig_prefix = self.get_signature_prefix(sig) - if sig_prefix: - sig_node += addnodes.desc_annotation(sig_prefix, sig_prefix) - - modname = self.options.get('module', self.env.ref_context.get('mad:module')) - if modname: - nodetext = modname + '.' - sig_node += addnodes.desc_addname(nodetext, nodetext) - - sig_node += addnodes.desc_name(class_name, class_name) - sig_node += addnodes.desc_annotation(": ", ": ") - - for base in base_classes: - p_node = addnodes.pending_xref( - '', refdomain='mad', reftype='type', - reftarget=base, modname=None, classname=None) - p_node['mad:class'] = base - p_node += nodes.Text(base) - sig_node += p_node - - sig_node += nodes.Text(', ') - sig_node.pop() - - return class_name, '' - - def add_target_and_index(self, name_cls: str, sig: str, sig_node: addnodes.desc_signature) -> None: - modname = self.options.get('module', self.env.ref_context.get('mad:module')) - fullname = (modname and modname + '.' or '') + name_cls[0] - # note target - - if fullname not in self.state.document.ids: - sig_node['names'].append(fullname) - sig_node['ids'].append(fullname) - sig_node['first'] = (not self.names) - - self.state.document.note_explicit_target(sig_node) - objects = self.env.domaindata['mad']['objects'] - if fullname in objects: - self.state_machine.reporter.warning( - 'duplicate object description of %s, ' % fullname + - 'other instance in ' + - self.env.doc2path(objects[fullname][0]) + - ', use :noindex: for one of them', - line=self.lineno) - objects[fullname] = (self.env.docname, self.objtype) - - index_text = self.get_index_text(modname, name_cls) - if index_text: - self.indexnode['entries'].append(('single', index_text, - fullname, '', None)) - - def get_signature_prefix(self, signature: str) -> str: - return self.objtype + ' ' - - def get_index_text(self, modname: str, name_cls: str) -> str: - if self.objtype == 'class': - if not modname: - return _('%s (built-in class)') % name_cls[0] - return _('%s (class in %s)') % (name_cls[0], modname) - elif self.objtype == 'exception': - return name_cls[0] - else: - return '' - - -class MadClassAttribute(MadObject): - """ - Description of a class attribute. - """ - allow_nesting = True - ATTRIBUTE_DEF_RE = re.compile(r'^\s*([\w.]*)(?:\s*:\s*(.*))?') - - def handle_signature(self, signature: str, sig_node: addnodes.desc_signature) -> Tuple[str, str]: - m = self.ATTRIBUTE_DEF_RE.match(signature) - if m is None: - raise ValueError - - attr_name, attr_type = m.groups() - - # determine module and class name (if applicable), as well as full name - modname = self.options.get('module', self.env.ref_context.get('mad:module')) - classname = self.env.ref_context.get('mad:class') - - sig_node['module'] = modname - sig_node['class'] = classname - sig_node['fullname'] = attr_name - - sig_node += addnodes.desc_name(attr_name, attr_name) - sig_node += addnodes.desc_annotation(": ", ": ") - sig_node += addnodes.desc_type(attr_type, attr_type) - - full_attr_name = ".".join(filter(None, [modname, classname, attr_name])) - return full_attr_name - - def add_target_and_index(self, name: str, sig: str, sig_node: addnodes.desc_signature) -> None: - mod_name = self.options.get('module', self.env.ref_context.get('mad:module')) - full_name = (mod_name and mod_name + '.' or '') + name - - if full_name not in self.state.document.ids: - sig_node['names'].append(full_name) - sig_node['ids'].append(full_name) - sig_node['first'] = (not self.names) - - self.state.document.note_explicit_target(sig_node) - objects = self.env.domaindata['mad']['objects'] - if full_name in objects: - self.state_machine.reporter.warning( - 'duplicate object description of %s, ' % full_name + - 'other instance in ' + - self.env.doc2path(objects[full_name][0]) + - ', use :noindex: for one of them', - line=self.lineno) - objects[full_name] = (self.env.docname, self.objtype) - - index_text = self.get_index_text(full_name) - if index_text: - self.indexnode['entries'].append(('single', index_text, - full_name, '', None)) - - def before_content(self): - pass - - def after_content(self): - pass - - def get_index_text(self, attr): - return _('%s (attribute)') % attr - - -class MadAliasObject(ObjectDescription): - object_type = 'class' - ALIAS_RE = re.compile(r'^ *([\w.]*) *= *(.*)$') - - def get_signature_prefix(self, signature: str) -> str: - return 'alias ' - - def handle_signature(self, signature: str, sig_node: addnodes.desc_signature) -> Tuple[str, str]: - """Transform an alias declaration into RST nodes. - .. mad:alias:: Bar = table - """ - m = MadAliasObject.ALIAS_RE.match(signature) - if m is None: - raise ValueError - alias, type_alias = m.groups() - - sig_node['alias'] = alias - sig_node['type_alias'] = type_alias - - sig_prefix = self.get_signature_prefix(signature) - sig_node += addnodes.desc_annotation(sig_prefix, sig_prefix) - sig_node += addnodes.desc_name(alias, alias) - sig_node += addnodes.desc_annotation(": ", ": ") - sig_node += addnodes.desc_addname(type_alias, type_alias) - - return alias - - def add_target_and_index(self, alias_name: str, sig: str, sig_node: addnodes.desc_signature): - if alias_name not in self.state.document.ids: - sig_node['names'].append(alias_name) - sig_node['ids'].append(alias_name) - sig_node['first'] = (not self.names) - self.state.document.note_explicit_target(sig_node) - objects = self.env.domaindata['mad']['objects'] - if alias_name in objects: - self.state_machine.reporter.warning( - 'duplicate object description of %s, ' % alias_name + - 'other instance in ' + - self.env.doc2path(objects[alias_name][0]) + - ', use :noindex: for one of them', - line=self.lineno) - objects[alias_name] = (self.env.docname, self.object_type) - - index_text = self.get_index_text(alias_name) - self.indexnode['entries'].append(('single', index_text, - alias_name, '', None)) - - def before_content(self): - pass - - def after_content(self): - pass - - def get_index_text(self, alias_name): - return _('%s (alias)') % alias_name - - -class MadClassMember(MadObject): #How would we like to describe a class? - """ - Description of a class member (methods, attributes). - """ - - def needs_arg_list(self) -> bool: - return self.objtype.endswith('method') - - def get_signature_prefix(self, signature: str) -> str: - if self.objtype == 'staticmethod': - return 'static ' - elif self.objtype == 'classmethod': - return 'classmethod ' - return super(MadClassMember, self).get_signature_prefix(signature) - - def get_index_text(self, modname: str, name_cls: str) -> str: - name, cls = name_cls - add_modules = self.env.config.add_module_names - if self.objtype == 'method': - try: - class_name, method_name = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s() (in module %s)') % (name, modname) - else: - return '%s()' % name - if modname and add_modules: - return _('%s() (%s.%s method)') % (method_name, modname, class_name) - else: - return _('%s() (%s method)') % (method_name, class_name) - elif self.objtype == 'staticmethod': - try: - class_name, method_name = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s() (in module %s)') % (name, modname) - else: - return '%s()' % name - if modname and add_modules: - return _('%s() (%s.%s static method)') % (method_name, modname, - class_name) - else: - return _('%s() (%s static method)') % (method_name, class_name) - elif self.objtype == 'classmethod': - try: - class_name, method_name = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s() (in module %s)') % (name, modname) - else: - return '%s()' % name - if modname: - return _('%s() (%s.%s class method)') % (method_name, modname, - class_name) - else: - return _('%s() (%s class method)') % (method_name, class_name) - elif self.objtype == 'attribute': - try: - class_name, attr_name = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s (in module %s)') % (name, modname) - else: - return name - if modname and add_modules: - return _('%s (%s.%s attribute)') % (attr_name, modname, class_name) - else: - return _('%s (%s attribute)') % (attr_name, class_name) - else: - return '' - - -class MadModule(Directive): - """ - Directive to mark description of a new module. - """ - - has_content = False - required_arguments = 1 - optional_arguments = 0 - final_argument_whitespace = False - option_spec = { - 'platform': lambda x: x, - 'synopsis': lambda x: x, - 'noindex': directives.flag, - 'deprecated': directives.flag, - } - - def run(self) -> List[nodes.Node]: - env = self.state.document.settings.env - modname = self.arguments[0].strip() - no_index = 'noindex' in self.options - env.ref_context['mad:module'] = modname - ret = [] - if not no_index: - env.domaindata['mad']['modules'][modname] = \ - (env.docname, self.options.get('synopsis', ''), - self.options.get('platform', ''), 'deprecated' in self.options) - # make a duplicate entry in 'objects' to facilitate searching for - # the module in MadDomain.find_obj() - env.domaindata['mad']['objects'][modname] = (env.docname, 'module') - target_node = nodes.target('', '', ids=['module-' + modname], - ismod=True) - self.state.document.note_explicit_target(target_node) - # the platform and synopsis aren't printed; in fact, they are only - # used in the modindex currently - ret.append(target_node) - indextext = _('%s (module)') % modname - inode = addnodes.index(entries=[('single', indextext, - 'module-' + modname, '', None)]) - ret.append(inode) - return ret - - -class MadCurrentModule(Directive): - """ - This directive is just to tell Sphinx that we're documenting - stuff in module foo, but links to module foo won't lead here. - """ - - has_content = False - required_arguments = 1 - optional_arguments = 0 - final_argument_whitespace = False - option_spec: Dict = {} - - def run(self) -> List[nodes.Node]: - env = self.state.document.settings.env - modname = self.arguments[0].strip() - if modname == 'None': - env.ref_context.pop('mad:module', None) - else: - env.ref_context['mad:module'] = modname - return [] - - -class MadXRefRole(XRefRole): - def process_link(self, env: BuildEnvironment, ref_node: nodes.Element, has_explicit_title: bool, - title: str, target: str) -> Tuple[str, str]: - ref_node['mad:module'] = env.ref_context.get('mad:module') - ref_node['mad:class'] = env.ref_context.get('mad:class') - if not has_explicit_title: - title = title.lstrip('.') # only has a meaning for the target - target = target.lstrip('~') # only has a meaning for the title - # if the first character is a tilde, don't display the module/class - # parts of the contents - if title[0:1] == '~': - title = title[1:] - dot = title.rfind('.') - if dot != -1: - title = title[dot + 1:] - return title, target - -class MadModuleIndex(Index): - """ - Index subclass to provide the Mad module index. - """ - - name = 'modindex' - localname = _('Mad Module Index') - shortname = _('modules') - - def generate(self, docnames: Iterable[str] = None) -> Tuple[List[Tuple[str, List[List[Union[str, int]]]]], bool]: - content: Dict[str, List] = {} - # list of prefixes to ignore - ignores = self.domain.env.config['modindex_common_prefix'] - ignores = sorted(ignores, key=len, reverse=True) - # list of all modules, sorted by module name - modules = sorted(self.domain.data['modules'].items(), - key=lambda x: x[0].lower()) - # sort out collapsable modules - prev_modname = '' - num_top_levels = 0 - for modname, (docname, synopsis, platforms, deprecated) in modules: - if docnames and docname not in docnames: - continue - - for ignore in ignores: - if modname.startswith(ignore): - modname = modname[len(ignore):] - stripped = ignore - break - else: - stripped = '' - - # we stripped the whole module name? - if not modname: - modname, stripped = stripped, '' - - entries = content.setdefault(modname[0].lower(), []) - - package = modname.split('.')[0] - if package != modname: - # it's a submodule - if prev_modname == package: - # first submodule - make parent a group head - if entries: - entries[-1][1] = 1 - elif not prev_modname.startswith(package): - # submodule without parent in list, add dummy entry - entries.append([stripped + package, 1, '', '', '', '', '']) - subtype = 2 - else: - num_top_levels += 1 - subtype = 0 - - qualifier = deprecated and _('Deprecated') or '' - entries.append([stripped + modname, subtype, docname, - 'module-' + stripped + modname, platforms, - qualifier, synopsis]) - prev_modname = modname - - # apply heuristics when to collapse modindex at page load: - # only collapse if number of toplevel modules is larger than - # number of submodules - collapse = len(modules) - num_top_levels < num_top_levels - - # sort by first letter - sorted_content = sorted(content.items()) - - return sorted_content, collapse - - -class MadDomain(Domain): - """Mad language domain.""" - name = 'mad' - label = 'Mad' - object_types: Dict[str, ObjType] = { - 'constant': ObjType(_('constant'), 'const', 'obj'), - 'function': ObjType(_('function'), 'func', 'obj'), - 'data': ObjType(('data'), 'data', 'obj'), - 'class': ObjType(_('class'), 'class', 'exc', 'obj'), - 'alias': ObjType(_('alias'), 'alias', 'obj'), - 'exception': ObjType(_('exception'), 'exc', 'class', 'obj'), - 'method': ObjType(_('method'), 'meth', 'obj'), - 'classmethod': ObjType(_('class method'), 'meth', 'obj'), - 'staticmethod': ObjType(_('static method'), 'meth', 'obj'), - 'attribute': ObjType(_('attribute'), 'attr', 'obj'), - 'module': ObjType(_('module'), 'mod', 'obj'), - } - - directives = { - 'constant': MadModuleLevel, - 'function': MadModuleLevel, - 'data': MadModuleLevel, - 'class': MadClassLike, - 'alias': MadAliasObject, - 'exception': MadClassLike, - 'method': MadClassMember, - 'classmethod': MadClassMember, - 'staticmethod': MadClassMember, - 'attribute': MadClassAttribute, - 'module': MadModule, - 'currentmodule': MadCurrentModule, - } - roles = { #These will appear as black bold and sometimes have a link if in context of class or module - 'data': MadXRefRole(), #Data - 'exc': MadXRefRole(), #Exception - 'const': MadXRefRole(), #Constant - 'expr': MadXRefRole(), #Expression - 'func': MadXRefRole(), #Function - 'class': MadXRefRole(), #Class - to remove? - 'alias': MadXRefRole(), #Alias - remove? - 'attr': MadXRefRole(), #Attribute - 'meth': MadXRefRole(), #Method - 'mod': MadXRefRole(), #Module - 'obj': MadXRefRole(), #Object - 'arg': MadXRefRole(), #Argument - 'var': MadXRefRole(), #Variable - } - initial_data: Dict[str, Dict[str, Tuple[Any]]] = { - 'objects': {}, # fullname -> docname, objtype - 'modules': {}, # modname -> docname, synopsis, platform, deprecated - } - indices = [ - MadModuleIndex, - ] - - def clear_doc(self, doc_name: str) -> None: - for fullname, (fn, _l) in list(self.data['objects'].items()): - if fn == doc_name: - del self.data['objects'][fullname] - for modname, (fn, _x, _x, _x) in list(self.data['modules'].items()): - if fn == doc_name: - del self.data['modules'][modname] - - def merge_domaindata(self, doc_names: List[str], other_data: Dict) -> None: - # XXX check duplicates? - for fullname, (fn, objtype) in other_data['objects'].items(): - if fn in doc_names: - self.data['objects'][fullname] = (fn, objtype) - for modname, data in other_data['modules'].items(): - if data[0] in doc_names: - self.data['modules'][modname] = data - - def find_obj(self, env: BuildEnvironment, modname: str, class_name: str, name: str, type: Optional[str], - search_mode: int = 0) -> List[Tuple[str, Any]]: - """Find a Mad object for "name", perhaps using the given module - and/or classname. Returns a list of (name, object entry) tuples. - """ - # skip parens - if name[-2:] == '()': - name = name[:-2] - - if not name: - return [] - - objects = self.data['objects'] - matches: List[Tuple[str, Any]] = [] - - new_name = None - - # NOTE: searching for exact match, object type is not considered - if name in objects: - new_name = name - elif type == 'mod': - # only exact matches allowed for modules - return [] - elif class_name and class_name + '.' + name in objects: - new_name = class_name + '.' + name - elif modname and modname + '.' + name in objects: - new_name = modname + '.' + name - elif modname and class_name and \ - modname + '.' + class_name + '.' + name in objects: - new_name = modname + '.' + class_name + '.' + name - # special case: object methods - elif type in ('func', 'meth') and '.' not in name and \ - 'object.' + name in objects: - new_name = 'object.' + name - - if new_name is not None: - matches.append((new_name, objects[new_name])) - - return matches - - def resolve_xref(self, env: BuildEnvironment, from_doc_name: str, builder: Builder, - type: str, target: str, node: nodes.Element, cont_node: nodes.Node)-> Optional[nodes.Node]: - modname = node.get('mad:module') - class_name = node.get('mad:class') - search_mode = 0 - matches = self.find_obj(env, modname, class_name, target, - type, search_mode) - if not matches: - return None - elif len(matches) > 1: - logger.warning('more than one target found for cross-reference %r: %s', - target, ', '.join(match[0] for match in matches), - type='ref', subtype='mad', location=node) - - name, obj = matches[0] - - if obj[1] == 'module': - return self._make_module_refnode(builder, from_doc_name, name, - cont_node) - else: - return make_refnode(builder, from_doc_name, obj[0], name, - cont_node, name) - - def resolve_any_xref(self, env: BuildEnvironment, from_doc_name: str, builder: Builder, target: str, - node: nodes.Node, cont_node: nodes.Node) -> List[Tuple[str, nodes.Node]]: - modname = node.get('mad:module') - class_name = node.get('mad:class') - results: List[Tuple[str, nodes.Node]] = [] - - # always search in "refspecific" mode with the :any: role - matches = self.find_obj(env, modname, class_name, target, None, 1) - for name, obj in matches: - if obj[1] == 'module': - results.append(('mad:mod', - self._make_module_refnode(builder, from_doc_name, - name, cont_node))) - else: - results.append(('mad:' + self.role_for_objtype(obj[1]), - make_refnode(builder, from_doc_name, obj[0], name, - cont_node, name))) - return results - - def _make_module_refnode(self, builder: Builder, fromdocname: str, name: str, cont_node: nodes.Node) -> nodes.Node: - # get additional info for modules - docname, synopsis, platform, deprecated = self.data['modules'][name] - title = name - if synopsis: - title += ': ' + synopsis - if deprecated: - title += _(' (deprecated)') - if platform: - title += ' (' + platform + ')' - return make_refnode(builder, fromdocname, docname, - 'module-' + name, cont_node, title) - - def get_objects(self) -> Iterator[Tuple[str, str, str, str, str, int]]: - for modname, info in self.data['modules'].items(): - yield (modname, modname, 'module', info[0], 'module-' + modname, 0) - for refname, (docname, type) in self.data['objects'].items(): - if type != 'module': # modules are already handled - yield (refname, refname, type, docname, refname, 1) - - def get_full_qualified_name(self, node: nodes.Element) -> Optional[str]: - modname = node.get('mad:module') - class_name = node.get('mad:class') - target = node.get('reftarget') - if target is None: - return None - else: - return '.'.join(filter(None, [modname, class_name, target])) - - -def setup(app): - app.add_domain(MadDomain) - - return { - 'version': 'builtin', - 'parallel_read_safe': True, - 'parallel_write_safe': True, - } diff --git a/docs/source/_static/css/custom.css b/docs/source/_static/css/custom.css deleted file mode 100644 index dcc01e2fa..000000000 --- a/docs/source/_static/css/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -table.docutils col { - width: auto !important; -} \ No newline at end of file diff --git a/docs/source/alignments.rst b/docs/source/alignments.rst deleted file mode 100644 index 7e25acc00..000000000 --- a/docs/source/alignments.rst +++ /dev/null @@ -1,5 +0,0 @@ -.. _ch.phy.align: - -Misalignments -============= - diff --git a/docs/source/aperture.rst b/docs/source/aperture.rst deleted file mode 100644 index 47730154a..000000000 --- a/docs/source/aperture.rst +++ /dev/null @@ -1,4 +0,0 @@ -.. _ch.phy.aper: - -Aperture -======== diff --git a/docs/source/beam.rst b/docs/source/beam.rst deleted file mode 100644 index 04cc87dab..000000000 --- a/docs/source/beam.rst +++ /dev/null @@ -1,231 +0,0 @@ -Beams -===== -.. _ch.gen.beam: - -The ``beam`` object is the *root object* of beams that store information relative to particles and particle beams. It also provides a simple interface to the particles and nuclei database. - -The ``beam`` module extends the :doc:`typeid ` module with the ``is_beam`` *function*, which returns ``true`` if its argument is a ``beam`` object, ``false`` otherwise. - -Attributes ----------- - -The ``beam`` *object* provides the following attributes: - -**particle** - A *string* specifying the name of the particle. (default: ``"positron"``). - -**mass** - A *number* specifying the energy-mass of the particle [GeV]. (default: ``emass``). - -**charge** - A *number* specifying the charge of the particle in [q] unit of ``qelect``. [#f1]_ (default: ``1``). - -**spin** - A *number* specifying the spin of the particle. (default: ``0``). - -**emrad** - A *lambda* returning the electromagnetic radius of the particle [m], - - :math:`\mathrm{emrad} = \mathrm{krad\_GeV}\times\mathrm{charge}^2/\mathrm{mass}` where :math:`\mathrm{krad\_GeV} = 10^{-9} (4 \pi\varepsilon_0)^{-1} q`. - -**aphot** - A *lambda* returning the average number of photon emitted per bending unit, - - :math:`\mathrm{aphot} = \mathrm{kpht\_GeV}\times\mathrm{charge}^2*\mathrm{betgam}` where :math:`\mathrm{kpht\_GeV}` :math:`= \frac{5}{2\sqrt{3}}`. - -**energy** - A *number* specifying the particle energy [GeV]. (default: ``1``). - -**pc** - A *lambda* returning the particle momentum times the speed of light [GeV], - - :math:`\mathrm{pc} = (\mathrm{energy}^2 - \mathrm{mass}^2)^{\frac{1}{2}}`. - -**beta** - A *lambda* returning the particle relativistic :math:`\beta=\frac{v}{c}`, - - :math:`\mathrm{beta} = (1 - (\mathrm{mass}/\mathrm{energy})^2)^{\frac{1}{2}}`. - -**gamma** - A *lambda* returning the particle Lorentz factor :math:`\gamma=(1-\beta^2)^{-\frac{1}{2}}`, - - :math:`\mathrm{gamma} = \mathrm{energy}/\mathrm{mass}`. - -**betgam** - A *lambda* returning the product :math:`\beta\gamma`, - - :math:`\mathrm{betgam} = (\mathrm{gamma}^2 - 1)^\frac{1}{2}`. - -**pc2** - A *lambda* returning :math:`\mathrm{pc}^2`, avoiding the square root. - -**beta2** - A *lambda* returning :math:`\mathrm{beta}^2`, avoiding the square root. - -**betgam2** - A *lambda* returning :math:`\mathrm{betgam}^2`, avoiding the square root. - -**brho** - A *lambda* returning the magnetic rigidity [T.m], - - :literal:`brho = GeV_c * pc/|charge|` where ``GeV_c`` = :math:`10^{9}/c` - -**ex** - A *number* specifying the horizontal emittance :math:`\epsilon_x` [m]. (default: ``1``). - -**ey** - A *number* specifying the vertical emittance :math:`\epsilon_y` [m]. (default: ``1``). - -**et** - A *number* specifying the longitudinal emittance :math:`\epsilon_t` [m]. (default: :literal:`1e-3`). - -**exn** - A *lambda* returning the normalized horizontal emittance [m], - - :literal:`exn = ex * betgam`. - -**eyn** - A *lambda* returning the normalized vertical emittance [m], - - :literal:`eyn = ey * betgam`. - -**etn** - A *lambda* returning the normalized longitudinal emittance [m], - - :literal:`etn = et * betgam`. - -**nbunch** - A *number* specifying the number of particle bunches in the machine. (default: ``0``). - -**npart** - A *number* specifying the number of particles per bunch. (default: ``0``). - -**sigt** - A *number* specifying the bunch length in :math:`c \sigma_t`. (default: ``1``). - -**sige** - A *number* specifying the relative energy spread in :math:`\sigma_E/E` [GeV]. (default: :literal:`1e-3`). - - -The ``beam`` *object* also implements a special protect-and-update mechanism for its attributes to ensure consistency and precedence between the physical quantities stored internally: - -#. The following attributes are *read-only*, i.e. writing to them triggers an error: - ``mass, charge, spin, emrad, aphot`` - -#. The following attributes are *read-write*, i.e. hold values, with their accepted numerical ranges: - ``particle, energy`` :math:`>` ``mass``, - ``ex`` :math:`>0`, ``ey`` :math:`>0`, ``et`` :math:`>0`, - ``nbunch`` :math:`>0`, ``npart`` :math:`>0`, ``sigt`` :math:`>0`, ``sige`` :math:`>0`. - -#. The following attributes are *read-update*, i.e. setting these attributes update the ``energy``, with their accepted numerical ranges: - ``pc`` :math:`>0`, :math:`0.9>` ``beta`` :math:`>0`, ``gamma`` :math:`>1`, ``betgam`` :math:`>0.1`, ``brho`` :math:`>0`, - ``pc2``, ``beta2``, ``betgam2``. -#. The following attributes are *read-update*, i.e. setting these attributes update the emittances ``ex``, ``ey``, and ``et`` repectively, with their accepted numerical ranges: - ``exn`` :math:`>0`, ``eyn`` :math:`>0`, ``etn`` :math:`>0`. - - -Methods -------- - -The ``beam`` object provides the following methods: - -**new_particle** - A *method* ``(particle, mass, charge, [spin])`` creating new particles or nuclei and store them in the particles database. The arguments specify in order the new ``particle``'s name, energy-``mass`` [GeV], ``charge`` [q], and ``spin`` (default: ``0``). These arguments can also be grouped into a *table* with same attribute names as the argument names and passed as the solely argument. - -**set_variables** - A *method* ``(set)`` returning ``self`` with the attributes set to the pairs (*key*, *value*) contained in ``set``. This method overrides the original one to implement the special protect-and-update mechanism, but the order of the updates is undefined. It also creates new particle on-the-fly if the ``mass`` and the ``charge`` are defined, and then select it. Shortcut ``setvar``. - -**showdb** - A *method* ``([file])`` displaying the content of the particles database to ``file`` (default: ``io.stdout``). - - -Metamethods ------------ - -The ``beam`` object provides the following metamethods: - -**__init** - A *metamethod* ``()`` returning ``self`` after having processed the attributes with the special protect-and-update mechanism, where the order of the updates is undefined. It also creates new particle on-the-fly if the ``mass`` and the ``charge`` are defined, and then select it. - -**__newindex** - A *metamethod* ``(key, val)`` called by the assignment operator ``[key]=val`` to create new attributes for the pairs (*key*, *value*) or to update the underlying physical quantity of the ``beam`` objects. - - -The following attribute is stored with metamethods in the metatable, but has different purpose: - - -**__beam** - A unique private *reference* that characterizes beams. - - -Particles database ------------------- - -The ``beam`` *object* manages the particles database, which is shared by all ``beam`` instances. The default set of supported particles is: - electron, positron, proton, antiproton, neutron, antineutron, ion, muon, - antimuon, deuteron, antideuteron, negmuon (=muon), posmuon (=antimuon). - -New particles can be added to the database, either explicitly using the ``new_particle`` method, or by creating or updating a beam *object* and specifying all the attributes of a particle, i.e. ``particle``'s name, ``charge``, ``mass``, and (optional) ``spin``: - -.. code-block:: lua - - local beam in MAD - local nmass, pmass, mumass in MAD.constant - - -- create a new particle - beam:new_particle{ particle='mymuon', mass=mumass, charge=-1, spin=1/2 } - - -- create a new beam and a new nucleus - local pbbeam = beam { particle='pb208', mass=82*pmass+126*nmass, charge=82 } - -The particles database can be displayed with the ``showdb`` method at any time from any beam: - -.. code-block:: lua - - beam:showdb() -- check that both, mymuon and pb208 are in the database. - - -Particle charges ----------------- - -The physics of \MAD is aware of particle charges. To enable the compatibility with codes like MAD-X that ignores the particle charges, the global option ``nocharge`` can be used to control the behavior of created beams as shown by the following example: - -.. code-block:: lua - - local beam, option in MAD - local beam1 = beam { particle="electron" } -- beam with negative charge - print(beam1.charge, option.nocharge) -- display: -1 false - - option.nocharge = true -- disable particle charges - local beam2 = beam { particle="electron" } -- beam with negative charge - print(beam2.charge, option.nocharge) -- display: 1 true - - -- beam1 was created before nocharge activation... - print(beam1.charge, option.nocharge) -- display: -1 true - -This approach ensures consistency of beams behavior during their entire lifetime. [#f2]_ - -Examples --------- - - - -.. code-block:: lua - - local beam in MAD - local lhcb1, lhcb2 in MADX - local nmass, pmass, amass in MAD.constant - local pbmass = 82*pmass+126*nmass - - -- attach a new beam with a new particle to lhcb1 and lhcb2. - lhc1.beam = beam 'Pb208' { particle='pb208', mass=pbmass, charge=82 } - lhc2.beam = lhc1.beam -- let sequences share the same beam... - - -- print Pb208 nuclei energy-mass in GeV and unified atomic mass. - print(lhcb1.beam.mass, lhcb1.beam.mass/amass) - - -.. rubric:: Footnotes - -.. [#f1] The ``qelect`` value is defined in the :doc:`constants` module.`` -.. [#f2] The option ``rbarc`` in MAD-X is too volatile and does not ensure such consistency... diff --git a/docs/source/beta0.rst b/docs/source/beta0.rst deleted file mode 100644 index 3db9f5f18..000000000 --- a/docs/source/beta0.rst +++ /dev/null @@ -1,48 +0,0 @@ -Beta0 Blocks -============ -.. _ch.gen.beta0: - - - -The ``beta0`` object is the *root object* of beta0 blocks that store information relative to the phase space at given positions, e.g. initial conditions, Poincaré section. - -The ``beta0`` module extends the :doc:`typeid ` module with the ``is_beta0`` *function*, which returns ``true`` if its argument is a ``beta0`` object, ``false`` otherwise. - -Attributes ----------- - -The ``beta0`` *object* provides the following attributes: - -**particle** - A *string* specifying the name of the particle. (default: ``"positron"``). - - -Methods -------- - -The ``beta0`` object provides the following methods: - -**showdb** - A *method* ``([file])`` displaying the content of the particles database to ``file`` (default: ``io.stdout``). - - -Metamethods ------------ - -The ``beta0`` object provides the following metamethods: - -**__init** - A *metamethod* ``()`` returning \SLF after having processed the attributes with the special protect-and-update mechanism, where the order of the updates is undefined. It also creates new particle on-the-fly if the ``mass`` and the ``charge`` are defined, and then select it. - - - - -**__beta0** - A unique private *reference* that characterizes beta0 blocks. - - -Examples --------- - -.. rubric:: Footnotes - diff --git a/docs/source/cffi.rst b/docs/source/cffi.rst deleted file mode 100644 index 824ea2b35..000000000 --- a/docs/source/cffi.rst +++ /dev/null @@ -1,4 +0,0 @@ -.. _ch.prg.cffi: - -Using C FFI -=========== \ No newline at end of file diff --git a/docs/source/cofind.rst b/docs/source/cofind.rst deleted file mode 100644 index c013bf69b..000000000 --- a/docs/source/cofind.rst +++ /dev/null @@ -1,239 +0,0 @@ -Cofind -====== -.. _ch.cmd.cofind: - -The ``cofind`` command (i.e. closed orbit finder) provides a simple interface to find a closed orbit using the Newton algorithm on top of the ``track`` command. - -Command synopsis ----------------- - - - -.. code-block:: lua - :caption: Synopsis of the ``cofind`` command with default setup. - :name: fig-cofind-synop - - mtbl, mflw = cofind} { - sequence=sequ, -- sequence (required) - beam=nil, -- beam (or sequence.beam, required) - range=nil, -- range of tracking (or sequence.range) - dir=nil, -- s-direction of tracking (1 or -1) - s0=nil, -- initial s-position offset [m] - X0=nil, -- initial coordinates (or damap, or beta block) - O0=nil, -- initial coordinates of reference orbit - deltap=nil, -- initial deltap(s) - nturn=nil, -- number of turns to track - nslice=nil, -- number of slices (or weights) for each element - mapdef=true, -- setup for damap (or list of, true => {}) - method=nil, -- method or order for integration (1 to 8) - model=nil, -- model for integration ('DKD' or 'TKT') - ptcmodel=nil, -- use strict PTC thick model (override option) - implicit=nil, -- slice implicit elements too (e.g. plots) - misalign=nil, -- consider misalignment - fringe=nil, -- enable fringe fields (see element.flags.fringe) - radiate=nil, -- radiate at slices - totalpath=nil, -- variable 't' is the totalpath - save=false, -- create mtable and save results - title=nil, -- title of mtable (default seq.name) - observe=nil, -- save only in observed elements (every n turns) - savesel=nil, -- save selector (predicate) - savemap=nil, -- save damap in the column __map - atentry=nil, -- action called when entering an element - atslice=nil, -- action called after each element slices - atexit=nil, -- action called when exiting an element - ataper=nil, -- action called when checking for aperture - atsave=nil, -- action called when saving in mtable - atdebug=fnil, -- action called when debugging the element maps - codiff=1e-10, -- finite differences step for jacobian - coiter=20, -- maximum number of iterations - cotol=1e-8, -- closed orbit tolerance (i.e.~|dX|) - X1=0, -- optional final coordinates translation - info=nil, -- information level (output on terminal) - debug=nil, -- debug information level (output on terminal) - usrdef=nil, -- user defined data attached to the mflow - mflow=nil, -- mflow, exclusive with other attributes - } - -The ``cofind`` command format is summarized in :numref:`fig-cofind-synop`, including the default setup of the attributes. Most of these attributes are set to :const:`nil` by default, meaning that ``cofind`` relies on the ``track`` command defaults. - -The ``cofind`` command supports the following attributes: - -.. _cofind.attr: - **sequence** - The *sequence* to track. (no default, required). - Example: ``sequence = lhcb1``. - - **beam** - The reference *beam* for the tracking. If no beam is provided, the command looks for a beam attached to the sequence, i.e. the attribute ``seq.beam``. - Example: ``beam = beam 'lhcbeam' { beam-attributes }``. [#f1]_ - - **range** - A *range* specifying the span of the sequence track. If no range is provided, the command looks for a range attached to the sequence, i.e. the attribute . (default: :const:`nil`). - Example: ``range = "S.DS.L8.B1/E.DS.R8.B1"``. - - **dir** - The :math:`s`-direction of the tracking: ``1`` forward, ``-1`` backward. (default: :const:`nil`). - Example: ``dir = - 1``. - - **s0** - A *number* specifying the initial :math:`s`-position offset. (default: :const:`nil`). - Example: ``s0 = 5000``. - - **X0** - A *mappable* (or a list of *mappable*) specifying initial coordinates ``{x,px,y,py, t,pt}``, damap, or beta block for each tracked object, i.e. particle or damap. The beta blocks are converted to damaps, while the coordinates are converted to damaps only if ``mapdef`` is specified, but both will use ``mapdef`` to setup the damap constructor. Each tracked object may also contain a ``beam`` to override the reference beam, and a *logical* ``nosave`` to discard this object from being saved in the mtable. (default: :const:`nil`). - Example: ``X0 = { x=1e- 3, px=- 1e- 5 }``. - - **O0** - A *mappable* specifying initial coordinates ``{x,px,y,py,t,pt}`` of the reference orbit around which X0 definitions take place. If it has the attribute ``cofind == true``, it will be used as an initial guess to search for the reference closed orbit. (default: ``0`` ). - Example: ``O0 = { x=1e- 4, px=- 2e- 5, y=- 2e- 4, py=1e- 5 }``. - - **deltap** - A *number* (or list of *number*) specifying the initial :math:`\delta_p` to convert (using the beam) and add to the ``pt`` of each tracked particle or damap. (default::const:`nil`). - Example: ``s0 = 5000``. - - **nturn** - A *number* specifying the number of turn to track. (default: :const:`nil`). - Example: ``nturn = 2``. - - **nstep** - A *number* specifying the number of element to track. A negative value will track all elements. (default: :const:`nil`). - Example: ``nstep = 1``. - - **nslice** - A *number* specifying the number of slices or an *iterable* of increasing relative positions or a *callable* ``(elm, mflw, lw)`` returning one of the two previous kind of positions to track in the elements. The arguments of the callable are in order, the current element, the tracked map flow, and the length weight of the step. This attribute can be locally overridden by the element. (default: :const:`nil`). - Example: ``nslice = 5``. - - **mapdef** - A *logical* or a *damap* specification as defined by the :doc:`DAmap ` module to track DA maps instead of particles coordinates. A value of ``true`` is equivalent to invoke the *damap* constructor with ``{}`` as argument. A value of ``false`` or :const:`nil` disable the use of damaps and force ``cofind`` to replace each particles or damaps by seven particles to approximate their Jacobian by finite difference. (default: ``true``). - Example: ``mapdef = { xy=2, pt=5 }``. - - **method** - A *number* specifying the order of integration from 1 to 8, or a *string* specifying a special method of integration. Odd orders are rounded to the next even order to select the corresponding Yoshida or Boole integration schemes. The special methods are ``simple`` (equiv. to ``DKD`` order 2), ``collim`` (equiv. to ``MKM`` order 2), and ``teapot`` (Teapot splitting order 2). (default: :const:`nil`). - Example: ``method = 'teapot'``. - - **model** - A *string* specifying the integration model, either ``'DKD'`` for *Drift-Kick-Drift* thin lens integration or ``'TKT'`` for *Thick-Kick-Thick* thick lens integration. [#f2]_ (default: :const:`nil`) - Example: ``model = 'DKD'``. - - **ptcmodel** - A *logical* indicating to use strict PTC model. [#f3]_ (default: :const:`nil`) - Example: ``ptcmodel = true``. - - **implicit** - A *logical* indicating that implicit elements must be sliced too, e.g. for smooth plotting. (default: :const:`nil`). - Example: ``implicit = true``. - - **misalign** - A *logical* indicating that misalignment must be considered. (default: :const:`nil`). - Example: ``misalign = true``. - - **fringe** - A *logical* indicating that fringe fields must be considered or a *number* specifying a bit mask to apply to all elements fringe flags defined by the element module. The value ``true`` is equivalent to the bit mask , i.e. allow all elements (default) fringe fields. (default: :const:`nil`). - Example: ``fringe = false``. - - **radiate** - A *logical* enabling or disabling the radiation or the *string* specifying the ``'average'`` type of radiation during the closed orbit search. The value ``true`` is equivalent to ``'average'`` and the value ``'quantum'`` is converted to ``'average'``. (default: :const:`nil`). - Example: ``radiate = 'average'``. - - **totalpath** - A *logical* indicating to use the totalpath for the fifth variable ``'t'`` instead of the local path. (default: :const:`nil`). - Example: ``totalpath = true``. - - **save** - A *logical* specifying to create a *mtable* and record tracking information at the observation points. The ``save`` attribute can also be a *string* specifying saving positions in the observed elements: ``"atentry"``, ``"atslice"``, ``"atexit"`` (i.e. ``true``), ``"atbound"`` (i.e. entry and exit), ``"atbody"`` (i.e. slices and exit) and ``"atall"``. (default: ``false``). - Example: ``save = false``. - - **title** - A *string* specifying the title of the *mtable*. If no title is provided, the command looks for the name of the sequence, i.e. the attribute ``seq.name``. (default: :const:`nil`). - Example: ``title = "track around IP5"``. - - **observe** - A *number* specifying the observation points to consider for recording the tracking information. A zero value will consider all elements, while a positive value will consider selected elements only, checked with method :meth:`:is_observed`, every :math:`>0` turns. (default: :const:`nil`). - Example: ``observe = 1``. - - **savesel** - A *callable* ``(elm, mflw, lw, islc)`` acting as a predicate on selected elements for observation, i.e. the element is discarded if the predicate returns ``false``. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :const:`nil`) - Example: ``savesel = \LMB e -> mylist[e.name] ~= nil``. - - **savemap** - A *logical* indicating to save the damap in the column ``__map`` of the *mtable*. (default: :const:`nil`). - Example: ``savemap = true``. - - **atentry** - A *callable* ``(elm, mflw, 0, - 1)`` invoked at element entry. The arguments are in order, the current element, the tracked map flow, zero length and the slice index ``-1``. (default: :const:`nil`). - Example: ``atentry = myaction``. - - **atslice** - A *callable* ``(elm, mflw, lw, islc)`` invoked at element slice. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :const:`nil`). - Example: ``atslice = myaction``. - - **atexit** - A *callable* ``(elm, mflw, 0, - 2)`` invoked at element exit. The arguments are in order, the current element, the tracked map flow, zero length and the slice index . (default: :const:`nil`). - Example: ``atexit = myaction``. - - **ataper** - A *callable* ``(elm, mflw, lw, islc)`` invoked at element aperture checks, by default at last slice. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. If a particle or a damap hits the aperture, then its ``status~=~"lost"`` and it is removed from the list of tracked items. (default: :const:`fnil`). - Example: ``ataper = myaction``. - - **atsave** - A *callable* ``(elm, mflw, lw, islc)`` invoked at element saving steps, by default at exit. The arguments are in order, the current element, the tracked map flow, the length weight of the slice and the slice index. (default: :const:`nil`). - Example: ``atsave = myaction``. - - **atdebug** - A *callable* ``(elm, mflw, lw, [msg], [...])`` invoked at the entry and exit of element maps during the integration steps, i.e. within the slices. The arguments are in order, the current element, the tracked map flow, the length weight of the integration step and a *string* specifying a debugging message, e.g. ``"map_name:0"`` for entry and ``":1"`` for exit. If the level ``debug`` :math:`\geq 4` and ``atdebug`` is not specified, the default *function* ``mdump`` is used. In some cases, extra arguments could be passed to the method. (default: :const:`fnil`). - Example: ``atdebug = myaction``. - - **codiff** - A *number* specifying the finite difference step to approximate the Jacobian when damaps are disabled. If ``codiff`` is larger than :math:`100\times`\ ``cotol``, it will be adjusted to ``cotol`` :math:`/100` and a warning will be emitted. (default: ``1e- 8``). - Example: ``codiff = 1e- 8``. - - **coiter** - A *number* specifying the maximum number of iteration. If this threshold is reached, all the remaining tracked objects are tagged as ``"unstable"``. (default: 20). - Example: ``coiter = 5``. - - **cotol** - A *number* specifying the closed orbit tolerance. If all coordinates update of a particle or a damap are smaller than ``cotol``, then it is tagged as ``"stable"``. (default: ``1e-8``). - Example: ``cotol = 1e- 6``. - - **X1** - A *mappable* specifying the coordinates ``{x,px,y,py,t,pt}`` to *subtract* to the final coordinates of the particles or the damaps. (default: ``0``). - Example: ``X1 = { t=100, pt=10 }``. - - **info** - A *number* specifying the information level to control the verbosity of the output on the console. (default: :const:`nil`). - Example: ``info = 2``. - - **debug** - A *number* specifying the debug level to perform extra assertions and to control the verbosity of the output on the console. (default: :const:`nil`). - Example: ``debug = 2``. - - **usrdef** - Any user defined data that will be attached to the tracked map flow, which is internally passed to the elements method ``:track`` and to their underlying maps. (default: :const:`nil`). - Example: ``usrdef = { myvar=somevalue }``. - - **mflow** - A *mflow* containing the current state of a ``track`` command. If a map flow is provided, all attributes are discarded except ``nstep``, ``info`` and ``debug``, as the command was already set up upon its creation. (default: :const:`nil`). - Example: ``mflow = mflow0``. - -The ``cofind`` command stops when all particles or damap are tagged as ``"stable"``, ``"unstable"``, ``"singular"`` or ``"lost"``. The ``cofind`` command returns the following objects in this order: - - **mtbl** - A *mtable* corresponding to the TFS table of the ``track`` command where the ``status`` column may also contain the new values ``"stable"``, ``"unstable"`` or ``"singular"``. - - **mflw** - A *mflow* corresponding to the map flow of the ``track`` command. The particles or damaps ``status`` are tagged and ordered by ``"stable"``, ``"unstable"``, ``"singular"``, ``"lost"`` and ``id``. - -Cofind mtable -------------- -.. _sec.cofind.mtable: - -The ``cofind`` command returns the ``track`` *mtable* unmodified except for the ``status`` column. The tracked objects id will appear once per iteration at the ``\$end`` marker, and other defined observation points if any, until they are removed from the list of tracked objects. - -Examples --------- - -TODO - -.. [#f1] Initial coordinates ``X0`` may override it by providing a beam per particle or damap. -.. [#f2] The ``TKT`` scheme (Yoshida) is automatically converted to the ``MKM`` scheme (Boole) when appropriate. -.. [#f3] In all cases, MAD-NG uses PTC setup ``time=true, exact=true``. diff --git a/docs/source/commands.rst b/docs/source/commands.rst deleted file mode 100644 index 4b38ee878..000000000 --- a/docs/source/commands.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _ch.prg.cmd: - -Commands -======== - - -Adding Commands ---------------- - diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 0266f70a0..000000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,130 +0,0 @@ -import sys, os, sphinx_rtd_theme -sys.path.append(os.path.abspath("./_ext")) #Add to path here! - -# Configuration file for the Sphinx documentation builder. -# For the full list of built-in configuration values, see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html -from pygments_mad_lexer import MadLexer - -from sphinx.highlighting import lexers -lexers['mad'] = MadLexer() - -# -- Project information ----------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information - -master_doc = 'index' -project = 'MAD-NG' -copyright = '2022, Laurent Deniau' -author = 'Laurent Deniau' -release = '0.9.6' - -# -- General configuration --------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration - -primary_domain = "mad" #Use .. default-domain:: c to change to c then .. default-domain:: mad to change back to mad -extensions = [ - "customRoles", - "sphinx-mad-domain", - ] - -source_suffix = { - '.rst': 'restructuredtext', -} - -highlight_language = "mad" -numfig = True - -templates_path = ['_templates'] -exclude_patterns = [] - -# -- Options for HTML output ------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output - -html_theme = 'alabaster' -html_static_path = ['_static'] - -html_css_files = [ - 'css/custom.css', -] - -pygments_style = 'sphinx' - -html_theme = 'sphinx_rtd_theme' -html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] - -html_theme_options = { - 'display_version': True, - 'prev_next_buttons_location': 'both' -} - - -# -- Options for latexpdf output ---------------------------------------------- -latex_toplevel_sectioning = 'part' -latex_docclass = { - 'manual': 'cernrep', - 'howto': 'cernrep' -} -latex_elements = { - 'preamble': ''' - \\usepackage{nameref} % For getting chapter name - - \\renewcommand\sphinxtableofcontentshook{} - \\addto\\captionsenglish{\\renewcommand{\\contentsname}{Table of contents}} - - %table spacing - %\\setlength{\\tabcolsep}{10pt} % Default value: 6pt - %\\renewcommand{\\arraystretch}{1.5} % Default value: 1 - - %Change the title formats - \\titleformat{\\chapter }{\\normalfont\\LARGE\\bfseries}{Chapter \\thechapter . }{1em}{} - \\titlespacing*{\\chapter}{0pt}{-20pt}{10pt} - \\titleformat{\\section }{\\normalfont\\Large\\bfseries}{\\thesection }{1em}{} - \\titleformat{\\subsection }{\\normalfont\\large\\bfseries}{\\thesubsection }{1em}{} - \\titleformat{\\subsubsection}{\\normalfont\\large\\bfseries}{\\thesubsubsection}{1em}{} - - \\makeatletter - %Changes headers and footers - \\fancypagestyle{normal}{ % After page 3 - \\fancyhf{} - \\fancyhead[R]{\\thepage} - \\fancyhead[L]{\\it{\\thechapter . \\MakeUppercase{\\@currentlabelname}}} - \\renewcommand{\\headrulewidth}{1pt} - \\renewcommand{\\footrulewidth}{0pt} - } - \\fancypagestyle{plain}{ % for up to page 3 - \\fancyhf{} - \\fancyhead[R]{\\thepage} - } - \\makeatother - ''', - 'fncychap': '', - 'sphinxsetup': "InnerLinkColor={rgb}{0,0,1}, OuterLinkColor={rgb}{0,0,1}",#'verbatimwithframe = false', #Remove border around code blocks - 'tableofcontents': '\\tableofcontents', - 'maketitle': """ - \\institute{ - Accelerator Beam Physics,\\\\ - CERN, Meyrin, Switzerland.} - - \\begin{abstract} - The Methodical Accelerator Design -- Next Generation application is an all-in-one standalone versatile tool for particle accelerator design, modeling, and optimization, and for beam dynamics and optics studies. Its general purpose scripting language is based on the simple yet powerful Lua programming language (with a few extensions) and embeds the state-of-art Just-In-Time compiler LuaJIT. Its physics is based on symplectic integration of differential maps made out of GTPSA (Generalized Truncated Power Series). The physics of the transport maps and the normal form analysis were both strongly inspired by the PTC/FPP library from E. Forest. MAD-NG development started in 2016 by the author as a side project of MAD-X, hence MAD-X users should quickly become familiar with its ecosystem, e.g. lattices definition. - \\begin{center} - \\texttt{http://cern.ch/mad} - \\end{center} - \\end{abstract} - - \\keywords{Methodical Accelerator Design; Accelerator beam physics; Scientific computing; JIT compiler; C and Lua programming.} - - \\maketitle""", - 'extraclassoptions': "oneside" -} -latex_table_style = ['booktabs'] -latex_additional_files = ["latex_additional_files/" + x for x in os.listdir("latex_additional_files/")] - -# -- Options for MAN output ------------------------------------------------- - -man_pages = [ - (master_doc, 'MAD-NG Refence Manual', 'MAD-NG man pages',[author], 1), - ("sequences", 'Sequence', 'Object man page',[author], 2), - ("elemfunc", 'Elementary Constants and Functions', 'Elementary Constants and Functions man page',[author], 3), - #Continually list to get all, could automate this? -] diff --git a/docs/source/constants.rst b/docs/source/constants.rst deleted file mode 100644 index 5430930d2..000000000 --- a/docs/source/constants.rst +++ /dev/null @@ -1,103 +0,0 @@ -.. index:: - Constants - -********* -Constants -********* - -This chapter describes some constants uniquely defined as macros in the C header :file:`mad_cst.h` and available from modules :mod:`MAD.constant` and :mod:`MAD._C` (C API) as floating point double precision variables. - -Numerical Constants -=================== - -.. index:: - Numerical constants - -These numerical constants are provided by the system libraries. Note that the constant :const:`huge` differs from :const:`math.huge`, which corresponds in fact to :const:`inf`. - -=================== ====================== ========================= ====================== -MAD constants C macros C constants Values -=================== ====================== ========================= ====================== -:const:`eps` :c:macro:`DBL_EPSILON` :const:`mad_cst_EPS` Smallest representable step near one -:const:`tiny` :c:macro:`DBL_MIN` :const:`mad_cst_TINY` Smallest representable number -:const:`huge` :c:macro:`DBL_MAX` :const:`mad_cst_HUGE` Largest representable number -:const:`inf` :c:macro:`INFINITY` :const:`mad_cst_INF` Positive infinity, :math:`1/0` -:const:`nan` :c:macro:`NAN` :const:`mad_cst_NAN` Canonical NaN [#f1]_, :math:`0/0` -=================== ====================== ========================= ====================== - -Mathematical Constants -====================== - -.. index:: - Mathematical constants - -This section describes some mathematical constants uniquely defined as macros in the C header :file:`mad_cst.h` and available from C and MAD modules as floating point double precision variables. If these mathematical constants are already provided by the system libraries, they will be used instead of their local definitions. - -=================== ====================== ========================= ====================== -MAD constants C macros C constants Values -=================== ====================== ========================= ====================== -:const:`e` :c:macro:`M_E` :const:`mad_cst_E` :math:`e` -:const:`log2e` :c:macro:`M_LOG2E` :const:`mad_cst_LOG2E` :math:`\log_2(e)` -:const:`log10e` :c:macro:`M_LOG10E` :const:`mad_cst_LOG10E` :math:`\log_{10}(e)` -:const:`ln2` :c:macro:`M_LN2` :const:`mad_cst_LN2` :math:`\ln(2)` -:const:`ln10` :c:macro:`M_LN10` :const:`mad_cst_LN10` :math:`\ln(10)` -:const:`lnpi` :c:macro:`M_LNPI` :const:`mad_cst_LNPI` :math:`\ln(\pi)` -:const:`pi` :c:macro:`M_PI` :const:`mad_cst_PI` :math:`\pi` -:const:`twopi` :c:macro:`M_2PI` :const:`mad_cst_2PI` :math:`2\pi` -:const:`pi_2` :c:macro:`M_PI_2` :const:`mad_cst_PI_2` :math:`\pi/2` -:const:`pi_4` :c:macro:`M_PI_4` :const:`mad_cst_PI_4` :math:`\pi/4` -:const:`one_pi` :c:macro:`M_1_PI` :const:`mad_cst_1_PI` :math:`1/\pi` -:const:`two_pi` :c:macro:`M_2_PI` :const:`mad_cst_2_PI` :math:`2/\pi` -:const:`sqrt2` :c:macro:`M_SQRT2` :const:`mad_cst_SQRT2` :math:`\sqrt 2` -:const:`sqrt3` :c:macro:`M_SQRT3` :const:`mad_cst_SQRT3` :math:`\sqrt 3` -:const:`sqrtpi` :c:macro:`M_SQRTPI` :const:`mad_cst_SQRTPI` :math:`\sqrt{\pi}` -:const:`sqrt1_2` :c:macro:`M_SQRT1_2` :const:`mad_cst_SQRT1_2` :math:`\sqrt{1/2}` -:const:`sqrt1_3` :c:macro:`M_SQRT1_3` :const:`mad_cst_SQRT1_3` :math:`\sqrt{1/3}` -:const:`one_sqrtpi` :c:macro:`M_1_SQRTPI` :const:`mad_cst_1_SQRTPI` :math:`1/\sqrt{\pi}` -:const:`two_sqrtpi` :c:macro:`M_2_SQRTPI` :const:`mad_cst_2_SQRTPI` :math:`2/\sqrt{\pi}` -:const:`rad2deg` :c:macro:`M_RAD2DEG` :const:`mad_cst_RAD2DEG` :math:`180/\pi` -:const:`deg2rad` :c:macro:`M_DEG2RAD` :const:`mad_cst_DEG2RAD` :math:`\pi/180` -=================== ====================== ========================= ====================== - -Physical Constants -================== - -.. index:: - Physical constants - CODATA - -This section describes some physical constants uniquely defined as macros in the C header :file:`mad_cst.h` and available from C and MAD modules as floating point double precision variables. - -=============== =================== ======================= ====================== -MAD constants C macros C constants Values -=============== =================== ======================= ====================== -:const:`minlen` :c:macro:`P_MINLEN` :const:`mad_cst_MINLEN` Min length tolerance, default :math:`10^{-10}` in :unit:`[m]` -:const:`minang` :c:macro:`P_MINANG` :const:`mad_cst_MINANG` Min angle tolerance, default :math:`10^{-10}` in :unit:`[1/m]` -:const:`minstr` :c:macro:`P_MINSTR` :const:`mad_cst_MINSTR` Min strength tolerance, default :math:`10^{-10}` in :unit:`[rad]` -=============== =================== ======================= ====================== - -The following table lists some physical constants from the `CODATA 2018 `_ sheet. - -================= ===================== ========================= ====================== -MAD constants C macros C constants Values -================= ===================== ========================= ====================== -:const:`clight` :c:macro:`P_CLIGHT` :const:`mad_cst_CLIGHT` Speed of light, :math:`c` in :unit:`[m/s]` -:const:`mu0` :c:macro:`P_MU0` :const:`mad_cst_MU0` Permeability of vacuum, :math:`\mu_0` in :unit:`[T.m/A]` -:const:`epsilon0` :c:macro:`P_EPSILON0` :const:`mad_cst_EPSILON0` Permittivity of vacuum, :math:`\epsilon_0` in :unit:`[F/m]` -:const:`qelect` :c:macro:`P_QELECT` :const:`mad_cst_QELECT` Elementary electric charge, :math:`e` in :unit:`[C]` -:const:`hbar` :c:macro:`P_HBAR` :const:`mad_cst_HBAR` Reduced Plack's constant, :math:`\hbar` in :unit:`[GeV.s]` -:const:`amass` :c:macro:`P_AMASS` :const:`mad_cst_AMASS` Unified atomic mass, :math:`m_u\,c^2` in :unit:`[GeV]` -:const:`emass` :c:macro:`P_EMASS` :const:`mad_cst_EMASS` Electron mass, :math:`m_e\,c^2` in :unit:`[GeV]` -:const:`pmass` :c:macro:`P_PMASS` :const:`mad_cst_PMASS` Proton mass, :math:`m_p\,c^2` in :unit:`[GeV]` -:const:`nmass` :c:macro:`P_NMASS` :const:`mad_cst_NMASS` Neutron mass, :math:`m_n\,c^2` in :unit:`[GeV]` -:const:`mumass` :c:macro:`P_MUMASS` :const:`mad_cst_MUMASS` Muon mass, :math:`m_{\mu}\,c^2` in :unit:`[GeV]` -:const:`deumass` :c:macro:`P_DEUMASS` :const:`mad_cst_DEUMASS` Deuteron mass, :math:`m_d\,c^2` in :unit:`[GeV]` -:const:`eradius` :c:macro:`P_ERADIUS` :const:`mad_cst_ERADIUS` Classical electron radius, :math:`r_e` in :unit:`[m]` -:const:`alphaem` :c:macro:`P_ALPHAEM` :const:`mad_cst_ALPHAEM` Fine-structure constant, :math:`\alpha` -================= ===================== ========================= ====================== - -.. ------------------------------------------------------------ - -.. rubric:: Footnotes - -.. [#f1] Canonical NaN bit patterns may differ between MAD and C for the mantissa, but both should exibit the same behavior. diff --git a/docs/source/correct.rst b/docs/source/correct.rst deleted file mode 100644 index d21c8b9b0..000000000 --- a/docs/source/correct.rst +++ /dev/null @@ -1,210 +0,0 @@ -Correct -======= -.. _ch.cmd.correct: - -The ``correct`` command (i.e. orbit correction) provides a simple interface to compute the orbit steering correction and setup the kickers of the sequences from the analysis of their ``track`` and ``twiss`` mtables. - -.. code-block:: - :caption: Synopsis of the ``correct`` command with default setup. - :name: fig-correct-synop - - mlst = correct { - sequence=nil, -- sequence(s) (required) - range=nil, -- sequence(s) range(s) (or sequence.range) - title=nil, -- title of mtable (default seq.name) - model=nil, -- mtable(s) with twiss functions (required) - orbit=nil, -- mtable(s) with measured orbit(s), or use model - target=nil, -- mtable(s) with target orbit(s), or zero orbit - kind='ring', --\ 'line' or 'ring' - plane='xy', --\ 'x', 'y' or 'xy' - method='micado',--\ 'LSQ', 'SVD' or 'MICADO' - ncor=0, -- number of correctors to consider by method, 0=all - tol=1e-5, -- rms tolerance on the orbit - units=1, -- units in [m] of the orbit - corcnd=false, -- precond of correctors using 'svdcnd' or 'pcacnd' - corcut=0, -- value to theshold singular values in precond - cortol=0, -- value to theshold correctors in svdcnd - corset=true, -- update correctors correction strengths - monon=false, -- fraction (0` module to find the orbit correction, namely ``solve``, ``ssolve`` or ``nsolve``. (default: ``'micado'``). - Example: ``method = 'svd'``. - - **ncor** - A *number* specifying the number of correctors to consider with the method ``micado``, zero meaning all available correctors. (default: ``0``). - Example: ``ncor = 4``. - - **tol** - A *number* specifying the rms tolerance on the residuals for the orbit correction. (default: 1e-6). - Example: ``tol = 1e- 6``. - - **unit** - A *number* specifying the unit of the ``orbit`` and ``target`` coordinates. (default: ``1`` [m]). - Example: ``units = 1e- 3`` [m], i.e. [mm]. - - **corcnd** - A *log* or a *string* specifying the method to use among ``svdcnd`` and ``pcacnd`` from the :doc:`linear algebra ` module for the preconditioning of the system. A ``true`` value corresponds to . (default: ``false``). - Example: ``corcnd = 'pcacnd'``. - - **corcut** - A *number* specifying the thresholds for the singular values to pass to the ``svdcnd`` and ``pcacnd`` method for the preconditioning of the system. (default: ``0``). - Example: ``cortol = 1e- 6``. - - **cortol** - A *number* specifying the thresholds for the correctors to pass to the ``svdcnd`` method for the preconditioning of the system. (default: ``0``). - Example: ``cortol = 1e- 8``. - - **corset** - A *log* specifying to update the correctors strengths for the corrected orbit. (default: ``true``). - Example: ``corset = false``. - - **monon** - A *number* specifying a fraction of available monitors selected from a uniform RNG. (default: ``false``). - Example: ``monon = 0.8``, keep 80% of the monitors. - - **moncut** - A *number* specifying a threshold in number of sigma to cut monitor considered as outliers. (default: ``false``). - Example: ``moncut = 2``, cut monitors above :math:`2\sigma`. - - **monerr** - A *number* in ``0..3`` specifying the type of monitor reading errors to consider: ``1`` use scaling errors ``msex`` and ``msey``, ``2`` use alignment errors ``mrex``, ``mrey`` and ``dpsi``, ``3`` use both. (default: ``false``). - Example: ``monerr = 3``. - - **info** - A *number* specifying the information level to control the verbosity of the output on the console. (default: ``nil``). - Example: ``info = 2``. - - **debug** - A *number*\ specifying the debug level to perform extra assertions and to control the verbosity of the output on the console. (default: ``nil``). - Example: ``debug = 2``. - - -The ``correct`` command returns the following object: - - ``mlst`` - A *mtable* (or a list of *mtable*) corresponding to the TFS table of the ``correct`` command. It is a list when multiple sequences are corrected together. - - -Correct mtable --------------- -.. _sec.correct.mtable: - -The ``correct`` command returns a *mtable* where the information described hereafter is the default list of fields written to the TFS files. [#f1]_ - - - - **name** - The name of the command that created the ``"correct"``. - **type** - The type of the ``"correct"``. - **title** - The value of the command attribute ``title``. - **origin** - The origin of the application that created the ``"MAD 1.0.0 OSX 64"``. - **date** - The date of the creation of the ``"27/05/20"``. - **time** - The time of the creation of the ``"19:18:36"``. - **refcol** - The reference *column* for the *mtable* dictionnary, e.g. ``"name"``. - **range** - The value of the command attribute ``range``. [#f2]_ - **__seq** - The *sequence* from the command attribute ``sequence``. [#f3]_ .. _ref.track.mtbl1}: - - - - **name** - The name of the element. - **kind** - The kind of the element. - **s** - The :math:`s`-position at the end of the element slice. - **l** - The length from the start of the element to the end of the element slice. - **x_old** - The local coordinate :math:`x` at the :math:`s`-position before correction. - **y_old** - The local coordinate :math:`y` at the :math:`s`-position before correction. - **x** - The predicted local coordinate :math:`x` at the :math:`s`-position after correction. - **y** - The predicted local coordinate :math:`y` at the :math:`s`-position after correction. - **rx** - The predicted local residual :math:`r_x` at the :math:`s`-position after correction. - **ry** - The predicted local residual :math:`r_y` at the :math:`s`-position after correction. - **hkick_old** - The local horizontal kick at the :math:`s`-position before correction. - **vkick_old** - The local vertical kick at the :math:`s`-position before correction. - **hkick** - The predicted local horizontal kick at the :math:`s`-position after correction. - **vkick** - The predicted local vertical kick at the :math:`s`-position after correction. - **shared** - A *log* indicating if the element is shared with another sequence. - **eidx** - The index of the element in the sequence. - -Note that ``correct`` does not take into account the particles and damaps ``id``s present in the (augmented) ``track`` *mtable*, hence the provided tables should contain single particle or damap information. - -Examples --------- - - - -.. rubric:: Footnotes - -.. [#f1] The output of mtable in TFS files can be fully customized by the user. -.. [#f2] This field is not saved in the TFS table by default. -.. [#f3] Fields and columns starting with two underscores are protected data and never saved to TFS files.\label{ref:track:mtbl1 diff --git a/docs/source/cplxnum.rst b/docs/source/cplxnum.rst deleted file mode 100644 index ebfa0cfc1..000000000 --- a/docs/source/cplxnum.rst +++ /dev/null @@ -1,400 +0,0 @@ -.. index:: - Complex numbers - -*************** -Complex Numbers -*************** - -This chapter describes the :type:`complex` numbers as supported by MAD-NG. The module for `Complex numbers `_ is not exposed, only the contructors are visible from the :mod:`MAD` environment and thus, complex numbers are handled directly by their methods or by the generic functions of the same name from the module :mod:`MAD.gmath`. Note that :type:`complex` have value semantic like a pair of :type:`number` equivalent to a C structure or an array :expr:`const num_t[2]` for direct compliance with the C API. - -Types promotion -=============== - -The operations on complex numbers may involve other data types like real numbers leading to few combinations of types. In order to simplify the descriptions, the generic names :var:`num` and :var:`cpx` are used for real and complex numbers respectively. The following table summarizes all valid combinations of types for binary operations involving at least one :type:`complex` type: - -================= ================== =============== -Left Operand Type Right Operand Type Result Type -================= ================== =============== -:type:`number` :type:`complex` :type:`complex` -:type:`complex` :type:`number` :type:`complex` -:type:`complex` :type:`complex` :type:`complex` -================= ================== =============== - -Constructors -============ - -The constructors for :type:`complex` numbers are directly available from the :mod:`MAD` environment, except for the special case of the imaginary postfix, which is part of the language definition. - -.. constant:: i - - The imaginary postfix that qualifies literal numbers as imaginary numbers, i.e. :const:`1i` is the imaginary unit, and :const:`1+2i` is the :type:`complex` number :math:`1+2i`. - -.. function:: complex(re_, im_) - - Return the :type:`complex` number equivalent to :expr:`re + im * 1i`. Default: :expr:`re_ = 0`, :expr:`im_ = 0`. - -.. function:: tocomplex(str) - - Return the :type:`complex` number decoded from the string :var:`str` containing the literal complex number :const:`"a+bi"` (with no spaces) where :var:`a` and :var:`b` are literal numbers, i.e. the strings :const:`"1"`, :const:`"2i"` and :const:`"1+2i"` will give respectively the :type:`complex` numbers :math:`1+0i`, :math:`0+2i` and :math:`1+2i`. - -Attributes -========== - -.. constant:: cpx.re - - The real part of the :type:`complex` number :var:`cpx`. - -.. constant:: cpx.im - - The imaginary part of the :type:`complex` number :var:`cpx`. - -Functions -========= - -.. function:: is_complex(a) - - Return :const:`true` if :var:`a` is a :type:`complex` number, :const:`false` otherwise. This function is only available from the module :mod:`MAD.typeid`. - -.. function:: is_scalar(a) - - Return :const:`true` if :var:`a` is a :type:`number` or a :type:`complex` number, :const:`false` otherwise. This function is only available from the module :mod:`MAD.typeid`. - -Methods -======= - -Operator-like Methods ---------------------- - -================= =================== =================== ============================= -Functions Return values Metamethods C functions -================= =================== =================== ============================= -:func:`z:unm()` :math:`-z` :func:`__unm(z,_)` -:func:`z:add(z2)` :math:`z + z_2` :func:`__add(z,z2)` -:func:`z:sub(z2)` :math:`z - z_2` :func:`__sub(z,z2)` -:func:`z:mul(z2)` :math:`z \cdot z_2` :func:`__mul(z,z2)` -:func:`z:div(z2)` :math:`z / z_2` :func:`__div(z,z2)` :c:func:`mad_cpx_div_r` [#f1]_ -:func:`z:mod(z2)` :math:`z \mod z_2` :func:`__mod(z,z2)` :c:func:`mad_cpx_mod_r` -:func:`z:pow(z2)` :math:`z ^ {z_2}` :func:`__pow(z,z2)` :c:func:`mad_cpx_pow_r` -:func:`z:eq(z2)` :math:`z = z_2` :func:`__eq(z,z2)` -================= =================== =================== ============================= - -Real-like Methods ------------------ - -============================= ==================================================================== ============================ -Functions Return values C functions -============================= ==================================================================== ============================ -:func:`z:abs()` :math:`|z|` :c:func:`mad_cpx_abs_r` -:func:`z:acos()` :math:`\cos^{-1} z` :c:func:`mad_cpx_acos_r` -:func:`z:acosh()` :math:`\cosh^{-1} z` :c:func:`mad_cpx_acosh_r` -:func:`z:acot()` :math:`\cot^{-1} z` :c:func:`mad_cpx_atan_r` -:func:`z:acoth()` :math:`\coth^{-1} z` :c:func:`mad_cpx_atanh_r` -:func:`z:asin()` :math:`\sin^{-1} z` :c:func:`mad_cpx_asin_r` -:func:`z:asinc()` :math:`\frac{\sin^{-1} z}{z}` :c:func:`mad_cpx_asinc_r` -:func:`z:asinh()` :math:`\sinh^{-1} x` :c:func:`mad_cpx_asinh_r` -:func:`z:asinhc()` :math:`\frac{\sinh^{-1} z}{z}` :c:func:`mad_cpx_asinhc_r` -:func:`z:atan()` :math:`\tan^{-1} z` :c:func:`mad_cpx_atan_r` -:func:`z:atanh()` :math:`\tanh^{-1} z` :c:func:`mad_cpx_atanh_r` -:func:`z:ceil()` :math:`\lceil\Re(z)\rceil+i\,\lceil\Im(z)\rceil` -:func:`z:cos()` :math:`\cos z` :c:func:`mad_cpx_cos_r` -:func:`z:cosh()` :math:`\cosh z` :c:func:`mad_cpx_cosh_r` -:func:`z:cot()` :math:`\cot z` :c:func:`mad_cpx_tan_r` -:func:`z:coth()` :math:`\coth z` :c:func:`mad_cpx_tanh_r` -:func:`z:exp()` :math:`\exp z` :c:func:`mad_cpx_exp_r` -:func:`z:floor()` :math:`\lfloor\Re(z)\rfloor+i\,\lfloor\Im(z)\rfloor` -:func:`z:frac()` :math:`z - \operatorname{trunc}(z)` -:func:`z:hypot(z2)` :math:`\sqrt{z^2+z_2^2}` [#f2]_ -:func:`z:hypot3(z2,z3)` :math:`\sqrt{z^2+z_2^2+z_3^2}` [#f2]_ -:func:`z:inv(v_)` :math:`\frac{v}{z}` :c:func:`mad_cpx_inv_r` [#f1]_ -:func:`z:invsqrt(v_)` :math:`\frac{v}{\sqrt z}` :c:func:`mad_cpx_invsqrt_r` [#f1]_ -:func:`z:log()` :math:`\log z` :c:func:`mad_cpx_log_r` -:func:`z:log10()` :math:`\log_{10} z` :c:func:`mad_cpx_log10_r` -:func:`z:powi(n)` :math:`z^n` :c:func:`mad_cpx_powi_r` -:func:`z:round()` :math:`\lfloor\Re(z)\rceil+i\,\lfloor\Im(z)\rceil` -:func:`z:sin()` :math:`\sin z` :c:func:`mad_cpx_sin_r` -:func:`z:sinc()` :math:`\frac{\sin z}{z}` :c:func:`mad_cpx_sinc_r` -:func:`z:sinh()` :math:`\sinh z` :c:func:`mad_cpx_sinh_r` -:func:`z:sinhc()` :math:`\frac{\sinh z}{z}` :c:func:`mad_cpx_sinhc_r` -:func:`z:sqr()` :math:`z \cdot z` -:func:`z:sqrt()` :math:`\sqrt{z}` :c:func:`mad_cpx_sqrt_r` -:func:`z:tan()` :math:`\tan z` :c:func:`mad_cpx_tan_r` -:func:`z:tanh()` :math:`\tanh z` :c:func:`mad_cpx_tanh_r` -:func:`z:trunc()` :math:`\operatorname{trunc} \Re(z)+i\,\operatorname{trunc} \Im(z)` -:func:`z:unit()` :math:`\frac{z}{|z|}` :c:func:`mad_cpx_unit_r` -============================= ==================================================================== ============================ - -In methods :func:`inv()` and :func:`invsqrt()`, default is :expr:`v_ = 1`. - -Complex-like Methods --------------------- - -================= ============================================== ========================== -Functions Return values C functions -================= ============================================== ========================== -:func:`z:cabs()` :math:`|z|` :c:func:`mad_cpx_abs_r` -:func:`z:carg()` :math:`\arg z` :c:func:`mad_cpx_arg_r` -:func:`z:conj()` :math:`z^*` -:func:`z:fabs()` :math:`|\Re(z)|+i\,|\Im(z)|` -:func:`z:imag()` :math:`\Im(z)` -:func:`z:polar()` :math:`|z|\,e^{i \arg z}` :c:func:`mad_cpx_polar_r` -:func:`z:proj()` :math:`\operatorname{proj}(z)` :c:func:`mad_cpx_proj_r` -:func:`z:real()` :math:`\Re(z)` -:func:`z:rect()` :math:`\Re(z)\cos \Im(z)+i\,\Re(z)\sin \Im(z)` :c:func:`mad_cpx_rect_r` -:func:`z:reim()` :math:`\Re(z), \Im(z)` -================= ============================================== ========================== - -Error-like Methods ------------------- - -Error-like methods call C wrappers to the corresponding functions from the `Faddeeva library `_ from the MIT, considered as one of the most accurate and fast implementation over the complex plane [FADDEEVA]_ (see :file:`mad_num.c`). - -======================= ========================================================== ====================== -Functions Return values C functions -======================= ========================================================== ====================== -:func:`z:erf(rtol_)` :math:`\frac{2}{\sqrt\pi}\int_0^z e^{-t^2} dt` :c:func:`mad_cpx_erf_r` -:func:`z:erfc(rtol_)` :math:`1-\operatorname{erf}(z)` :c:func:`mad_cpx_erfc_r` -:func:`z:erfi(rtol_)` :math:`-i\operatorname{erf}(i z)` :c:func:`mad_cpx_erfi_r` -:func:`z:erfcx(rtol_)` :math:`e^{z^2}\operatorname{erfc}(z)` :c:func:`mad_cpx_erfcx_r` -:func:`z:wf(rtol_)` :math:`e^{-z^2}\operatorname{erfc}(-i z)` :c:func:`mad_cpx_wf_r` -:func:`z:dawson(rtol_)` :math:`\frac{-i\sqrt\pi}{2}e^{-z^2}\operatorname{erf}(iz)` :c:func:`mad_cpx_dawson_r` -======================= ========================================================== ====================== - -Operators -========= - -The operators on :type:`complex` follow the conventional mathematical operations of `Complex numbers `__. - -.. function:: -cpx - - Return a :type:`complex` resulting from the negation of the operand as computed by :func:`cpx:unm()`. - -.. function:: num + cpx - cpx + num - cpx + cpx - - Return a :type:`complex` resulting from the sum of the left and right operands as computed by :func:`cpx:add()`. - -.. function:: num - cpx - cpx - num - cpx - cpx - - Return a :type:`complex` resulting from the difference of the left and right operands as computed by :func:`cpx:sub()`. - -.. function:: num * cpx - cpx * num - cpx * cpx - - Return a :type:`complex` resulting from the product of the left and right operands as computed by :func:`cpx:mul()`. - -.. function:: num / cpx - cpx / num - cpx / cpx - - Return a :type:`complex` resulting from the division of the left and right operands as computed by :func:`cpx:div()`. If the right operand is a complex number, the division uses a robut and fast algorithm implemented in :c:func:`mad_cpx_div_r` [#f1]_. - -.. function:: num % cpx - cpx % num - cpx % cpx - - Return a :type:`complex` resulting from the rest of the division of the left and right operands, i.e. :math:`x - y \lfloor \frac{x}{y} \rfloor`, as computed by :func:`cpx:mod()`. If the right operand is a complex number, the division uses a robut and fast algorithm implemented in :c:func:`mad_cpx_div_r` [#f1]_. - -.. function:: num ^ cpx - cpx ^ num - cpx ^ cpx - - Return a :type:`complex` resulting from the left operand raised to the power of the right operand as computed by :func:`cpx:pow()`. - -.. function:: num == cpx - cpx == num - cpx == cpx - - Return :const:`false` if the real or the imaginary part differ between the left and right operands, :const:`true` otherwise. A number :var:`a` will be interpreted as :math:`a+i0` for the comparison. - -C API -===== - -These functions are provided for performance reason and compliance (i.e. branch cut) with the C API of other modules dealing with complex numbers like the linear and the differential algebra. For the same reason, some functions hereafter refer to the section 7.3 of the C Programming Language Standard [ISOC99CPX]_. - -.. c:function:: num_t mad_cpx_abs_r (num_t x_re, num_t x_im) - - Return the modulus of the :type:`complex` :var:`x` as computed by :c:func:`cabs()`. - -.. c:function:: num_t mad_cpx_arg_r (num_t x_re, num_t x_im) - - Return the argument in :math:`[-\pi, +\pi]` of the :type:`complex` :var:`x` as computed by :c:func:`carg()`. - -.. c:function:: void mad_cpx_unit_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the :type:`complex` :var:`x` divided by its modulus as computed by :c:func:`cabs()`. - -.. c:function:: void mad_cpx_proj_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the projection of the :type:`complex` :var:`x` on the Riemann sphere as computed by :c:func:`cproj()`. - -.. c:function:: void mad_cpx_rect_r (num_t rho, num_t ang, cpx_t *r) - - Put in :var:`r` the rectangular form of the :type:`complex` :expr:`rho * exp(i*ang)`. - -.. c:function:: void mad_cpx_polar_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the polar form of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_inv_r (num_t x_re, num_t x_im, cpx_t *r) - cpx_t mad_cpx_inv (cpx_t x) - - Put in :var:`r` or return the inverse of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_invsqrt_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the square root of the inverse of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_div_r (num_t x_re, num_t x_im, num_t y_re, num_t y_im, cpx_t *r) - cpx_t mad_cpx_div (cpx_t x, cpx_t y) - - Put in :var:`r` or return the :type:`complex` :var:`x` divided by the :type:`complex` :var:`y`. - -.. c:function:: void mad_cpx_mod_r (num_t x_re, num_t x_im, num_t y_re, num_t y_im, cpx_t *r) - - Put in :var:`r` the remainder of the division of the :type:`complex` :var:`x` by the :type:`complex` :var:`y`. - -.. c:function:: void mad_cpx_pow_r (num_t x_re, num_t x_im, num_t y_re, num_t y_im, cpx_t *r) - - Put in :var:`r` the :type:`complex` :var:`x` raised to the power of :type:`complex` :var:`y` using :c:func:`cpow()`. - -.. c:function:: void mad_cpx_powi_r (num_t x_re, num_t x_im, int n, cpx_t *r) - cpx_t mad_cpx_powi (cpx_t x, int n) - - Put in :var:`r` or return the :type:`complex` :var:`x` raised to the power of the :type:`integer` :var:`n` using a fast algorithm. - -.. c:function:: void mad_cpx_sqrt_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the square root of the :type:`complex` :var:`x` as computed by :c:func:`csqrt()`. - -.. c:function:: void mad_cpx_exp_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the exponential of the :type:`complex` :var:`x` as computed by :c:func:`cexp()`. - -.. c:function:: void mad_cpx_log_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the natural logarithm of the :type:`complex` :var:`x` as computed by :c:func:`clog()`. - -.. c:function:: void mad_cpx_log10_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the logarithm of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_sin_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the sine of the :type:`complex` :var:`x` as computed by :c:func:`csin()`. - -.. c:function:: void mad_cpx_cos_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the cosine of the :type:`complex` :var:`x` as computed by :c:func:`ccos()`. - -.. c:function:: void mad_cpx_tan_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the tangent of the :type:`complex` :var:`x` as computed by :c:func:`ctan()`. - -.. c:function:: void mad_cpx_sinh_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the hyperbolic sine of the :type:`complex` :var:`x` as computed by :c:func:`csinh()`. - -.. c:function:: void mad_cpx_cosh_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the hyperbolic cosine of the :type:`complex` :var:`x` as computed by :c:func:`ccosh()`. - -.. c:function:: void mad_cpx_tanh_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the hyperbolic tangent of the :type:`complex` :var:`x` as computed by :c:func:`ctanh()`. - -.. c:function:: void mad_cpx_asin_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the arc sine of the :type:`complex` :var:`x` as computed by :c:func:`casin()`. - -.. c:function:: void mad_cpx_acos_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the arc cosine of the :type:`complex` :var:`x` as computed by :c:func:`cacos()`. - -.. c:function:: void mad_cpx_atan_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the arc tangent of the :type:`complex` :var:`x` as computed by :c:func:`catan()`. - -.. c:function:: void mad_cpx_asinh_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the hyperbolic arc sine of the :type:`complex` :var:`x` as computed by :c:func:`casinh()`. - -.. c:function:: void mad_cpx_acosh_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the hyperbolic arc cosine of the :type:`complex` :var:`x` as computed by :c:func:`cacosh()`. - -.. c:function:: void mad_cpx_atanh_r (num_t x_re, num_t x_im, cpx_t *r) - - Put in :var:`r` the hyperbolic arc tangent of the :type:`complex` :var:`x` as computed by :c:func:`catanh()`. - -.. c:function:: void mad_cpx_sinc_r (num_t x_re, num_t x_im, cpx_t *r) - cpx_t mad_cpx_sinc (cpx_t x) - - Put in :var:`r` or return the sine cardinal of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_sinhc_r (num_t x_re, num_t x_im, cpx_t *r) - cpx_t mad_cpx_sinhc (cpx_t x) - - Put in :var:`r` or return the hyperbolic sine cardinal of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_asinc_r (num_t x_re, num_t x_im, cpx_t *r) - cpx_t mad_cpx_asinc (cpx_t x) - - Put in :var:`r` or return the arc sine cardinal of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_asinhc_r (num_t x_re, num_t x_im, cpx_t *r) - cpx_t mad_cpx_asinhc (cpx_t x) - - Put in :var:`r` or return the hyperbolic arc sine cardinal of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_wf_r (num_t x_re, num_t x_im, num_t relerr, cpx_t *r) - cpx_t mad_cpx_wf (cpx_t x, num_t relerr) - - Put in :var:`r` or return the Faddeeva function of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_erf_r (num_t x_re, num_t x_im, num_t relerr, cpx_t *r) - cpx_t mad_cpx_erf (cpx_t x, num_t relerr) - - Put in :var:`r` or return the error function of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_erfc_r (num_t x_re, num_t x_im, num_t relerr, cpx_t *r) - cpx_t mad_cpx_erfc (cpx_t x, num_t relerr) - - Put in :var:`r` or return the complementary error function of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_erfcx_r (num_t x_re, num_t x_im, num_t relerr, cpx_t *r) - cpx_t mad_cpx_erfcx (cpx_t x, num_t relerr) - - Put in :var:`r` or return the scaled complementary error function of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_erfi_r (num_t x_re, num_t x_im, num_t relerr, cpx_t *r) - cpx_t mad_cpx_erfi (cpx_t x, num_t relerr) - - Put in :var:`r` or return the imaginary error function of the :type:`complex` :var:`x`. - -.. c:function:: void mad_cpx_dawson_r (num_t x_re, num_t x_im, num_t relerr, cpx_t *r) - cpx_t mad_cpx_dawson (cpx_t x, num_t relerr) - - Put in :var:`r` or return the Dawson integral for the :type:`complex` :var:`x`. - -References -========== - -.. [CPXDIV] R. L. Smith, *"Algorithm 116: Complex division"*, Commun. ACM, 5(8):435, 1962. - -.. [CPXDIV2] M. Baudin and R. L. Smith, *"A robust complex division in Scilab"*, October 2012. http://arxiv.org/abs/1210.4539. - -.. [FADDEEVA] A. Oeftiger, R. De Maria, L. Deniau et al, *"Review of CPU and GPU Faddeeva Implementations"*, IPAC2016. https://cds.cern.ch/record/2207430/files/wepoy044.pdf. - -.. [ISOC99CPX] ISO/IEC 9899:1999 Programming Languages - C. https://www.iso.org/standard/29237.html. - -.. --------------------------------------- - -.. rubric:: Footnotes - -.. [#f1] Division and inverse use a robust and fast complex division algorithm, see [CPXDIV]_ and [CPXDIV2]_ for details. -.. [#f2] Hypot and hypot3 methods use a trivial implementation that may lead to numerical overflow/underflow. - diff --git a/docs/source/diffalg.rst b/docs/source/diffalg.rst deleted file mode 100644 index 30379d10c..000000000 --- a/docs/source/diffalg.rst +++ /dev/null @@ -1,32 +0,0 @@ -.. index:: - Differential algebra - Taylor Series - Truncated Power Series Algebra, TPSA - -******************** -Differential Algebra -******************** - -This chapter describes real :type:`tpsa` and complex :type:`ctpsa` objects as supported by MAD-NG. The module for the Generalized Truncated Power Series Algebra (GTPSA) that represents parametric multivariate finite `Taylor Series `_ is not exposed, only the contructors are visible from the :mod:`MAD` environment and thus, TPSAs are handled directly by their methods or by the generic functions of the same name from the module :mod:`MAD.gmath`. Note that both :type:`tpsa` and :type:`ctpsa` are defined as C structure for direct compliance with the C API. - -Introduction -============ - -Constructors -============ - -Functions -========= - -Methods -======= - -Operators -========= - -Iterators -========= - -C API -===== - diff --git a/docs/source/diffmap.rst b/docs/source/diffmap.rst deleted file mode 100644 index 501711606..000000000 --- a/docs/source/diffmap.rst +++ /dev/null @@ -1,33 +0,0 @@ -.. index:: - Differential maps - Taylor Series - Truncated Power Series Algebra, TPSA - -***************** -Differential Maps -***************** - -This chapter describes real :type:`damap` and complex :type:`cdamap` objects as supported by MAD-NG. They are useful abstractions to represent non-linear parametric multivariate differential maps, i.e. `Diffeomorphisms `_, `Vector Fields `_, `Exponential Maps `_ and `Lie Derivative `_. The module for the differential maps is not exposed, only the contructors are visible from the :mod:`MAD` environment and thus, differential maps are handled directly by their methods or by the generic functions of the same name from the module :mod:`MAD.gmath`. Note that :type:`damap` and :type:`cdamap` are defined as C structure for direct compliance with the C API. - -Introduction -============ - - -Constructors -============ - -Functions -========= - -Methods -======= - -Operators -========= - -Iterators -========= - -C API -===== - diff --git a/docs/source/dynmap.rst b/docs/source/dynmap.rst deleted file mode 100644 index ef05b9628..000000000 --- a/docs/source/dynmap.rst +++ /dev/null @@ -1,4 +0,0 @@ -.. _ch.phy.dynmap: - -Dynamic Maps -============ diff --git a/docs/source/elements.rst b/docs/source/elements.rst deleted file mode 100644 index d370a53f9..000000000 --- a/docs/source/elements.rst +++ /dev/null @@ -1,776 +0,0 @@ -Elements -======== -.. _ch.gen.elems: - -The ``element`` object is the *root object* of all elements used to model particle accelerators, including sequences and drifts. It provides most default values inherited by all elements. - -The ``element`` module extends the :doc:`typeid ` module with the ``is_element`` *function*, which returns ``true`` if its argument is an ``element`` object, ``false`` otherwise. - -Taxonomy --------- - -The classes defined by the ``element`` module are organized according to the kinds and the roles of their instances. The classes defining the kinds are: - -**thin** - The *thin* elements have zero-length and their physics does not depend on it, i.e. the attribute ``l`` is discarded or forced to zero in the physics. - -**thick** - The *thick* elements have a length and their physics depends on it. Elements like ``sbend``, ``rbend``, ``quadrupole``, ``solenoid``, and ``elseparator`` trigger a runtime error if they have zero-length. Other thick elements will accept to have zero-length for compatibility with MAD-X [#f1]_ , but their physics will have to be adjusted. [#f2]_ - -**drift** - The *drift* elements have a length with a ``drift``-like physics if :math:`l\geq` ``minlen`` [#f3]_ otherwise they are discarded or ignored. Any space between elements with a length :math:`l\geq` ``minlen`` are represented by an ``implicit`` drift created on need by the :math:`s`-iterator of sequences and discarded afterward. - -**patch** - The *patch* elements have zero-length and the purpose of their physics is to change the reference frame. - -**extrn** - The *extern* elements are never part of sequences. If they are present in a sequence definition, they are expanded and replaced by their content, i.e. stay external to the lattice. - -**specl** - The *special* elements have special roles like *marking* places (i.e. ``maker``) or *branching* sequences (i.e. ``slink``). - -These classes are not supposed to be used directly, except for extending the hierarchy defined by the ``element`` module and schematically reproduced hereafter to help users understanding: - -.. code-block:: lua - - thin_element = element 'thin_element' { is_thin = true } - thick_element = element 'thick_element' { is_thick = true } - drift_element = element 'drift_element' { is_drift = true } - patch_element = element 'patch_element' { is_patch = true } - extrn_element = element 'extrn_element' { is_extern = true } - specl_element = element 'specl_element' { is_special = true } - - sequence = extrn_element 'sequence' { } - assembly = extrn_element 'assembly' { } - bline = extrn_element 'bline' { } - - marker = specl_element 'marker' { } - slink = specl_element 'slink' { } - - drift = drift_element 'drift' { } - collimator = drift_element 'collimator' { } - instrument = drift_element 'instrument' { } - placeholder = drift_element 'placeholder' { } - - sbend = thick_element 'sbend' { } - rbend = thick_element 'rbend' { } - quadrupole = thick_element 'quadrupole' { } - sextupole = thick_element 'sextupole' { } - octupole = thick_element 'octupole' { } - decapole = thick_element 'decapole' { } - dodecapole = thick_element 'dodecapole' { } - solenoid = thick_element 'solenoid' { } - tkicker = thick_element 'tkicker' { } - wiggler = thick_element 'wiggler' { } - elseparator = thick_element 'elseparator' { } - rfcavity = thick_element 'rfcavity' { } - genmap = thick_element 'genmap' { } - - beambeam = thin_element 'beambeam' { } - multipole = thin_element 'multipole' { } - - xrotation = patch_element 'xrotation' { } - yrotation = patch_element 'yrotation' { } - srotation = patch_element 'srotation' { } - translate = patch_element 'translate' { } - changeref = patch_element 'changeref' { } - changedir = patch_element 'changedir' { } - changenrj = patch_element 'changenrj' { } - - -- specializations - rfmultipole = rfcavity 'rfmultipole' { } - crabcavity = rfmultipole 'crabcavity' { } - - monitor = instrument 'monitor' { } - hmonitor = monitor 'hmonitor' { } - vmonitor = monitor 'vmonitor' { } - - kicker = tkicker 'kicker' { } - hkicker = kicker 'hkicker' { } - vkicker = kicker 'vkicker' { } - - -All the classes above, including ``element``, define the attributes ``kind = name`` and ``is_name = true`` where ``name`` correspond to the class name. These attributes help to identify the kind and the role of an element as shown in the following code excerpt: - -.. code-block:: lua - - local drift, hmonitor, sequence in MAD.element - local dft = drift {} - local bpm = hmonitor {} - local seq = sequence {} - print(dft.kind) -- display: drift - print(dft.is_drift) -- display: true - print(dft.is_drift_element) -- display: true - print(bpm.kind) -- display: hmonitor - print(bpm.is_hmonitor) -- display: true - print(bpm.is_monitor) -- display: true - print(bpm.is_instrument) -- display: true - print(bpm.is_drift_element) -- display: true - print(bpm.is_element) -- display: true - print(bpm.is_drift) -- display: true - print(bpm.is_thick_element) -- display: nil (not defined = false) - print(seq.kind) -- display: sequence - print(seq.is_element) -- display: true - print(seq.is_extrn_element) -- display: true - print(seq.is_thick_element) -- display: nil (not defined = false) - - -Attributes ----------- - -The ``element`` *object* provides the following attributes: - -**l** - A *number* specifying the physical length of the element on the design orbit [m]. (default: ``0``). - -**lrad** - A *number* specifying the field length of the element on the design orbit considered by the radiation [m]. (default: :literal:`lrad = \s -> s.l`). - -**angle** - A *number* specifying the bending angle :math:`\alpha` of the element [rad]. A positive angle represents a bend to the right, i.e. a :math:`-y`-rotation towards negative x values. (default: ``0``). - -**tilt** - A *number* specifying the physical tilt of the element [rad]. All the physical quantities defined by the element are in the tilted frame, except ``misalign`` that comes first when tracking through an element, see the :doc:`track ` command for details. (default: ``0``). - -**model** - A *string* specifying the integration model ``"DKD"`` or ``"TKT"`` to use when tracking through the element and overriding the command attribute, see the :doc:`track ` command for details. (default: ``cmd.model``). - -**method** - A *number* specifying the integration order 2, 4, 6, or 8 to use when tracking through the element and overriding the command attribute, see the :doc:`track ` command for details. (default: ``cmd.method``). - -**nslice** - A *number* specifying the number of slices or a *list* of increasing relative positions or a *callable* ``(elm, mflw, lw)`` returning one of the two previous kind of positions specification to use when tracking through the element and overriding the command attribute, see the :doc:`survey ` or the :doc:`track ` commands for details. (default: ``cmd.nslice``). - -**refpos** - A *string* holding one of ``"entry"``, ``"centre"`` or ``"exit"``, or a *number* specifying a position in [m] from the start of the element, all of them resulting in an offset to substract to the ``at`` attribute to find the :math:`s`-position of the element entry when inserted in a sequence, see :ref:`element positions` for details. (default: ``nil`` :math:`\equiv` ``seq.refer``). - -**aperture** - A *mappable* specifying aperture attributes, see :ref:`Aperture ` for details. \\ - (default: ``{kind='circle', 1}``). - -**apertype** - A *string* specifying the aperture type, see :ref:`Aperture ` for details. \\ - (default: :literal:`\s -> s.aperture.kind or 'circle'`). [#f4]_ - -**misalign** - A *mappable* specifying misalignment attributes, see :ref:`Misalignment ` for details. \\ - - - -The ``thick_element`` *object* adds the following multipolar and fringe fields attributes: - -**knl, ksl** - A *list* specifying respectively the **multipolar** and skew integrated strengths of the element [m\ :math:`^{-i+1}`]. (default: ). - -**dknl, dksl** - A *list* specifying respectively the multipolar and skew integrated strengths errors of the element [m\ :math:`^{-i+1}`]. (default: ). - -**e1, e2** - A *number* specifying respectively the horizontal angle of the pole faces at entry and exit of the element [rad]. A positive angle goes toward inside the element, see Figures ``_ and ``_. (default: ``0``). - -**h1, h2** - A *number* specifying respectively the horizontal curvature of the pole faces at entry and exit of the element [m\ :math:`^{-1}`]. A positive curvature goes toward inside the element. (default: ). - -**hgap** - A *number* specifying half of the vertical gap at the center of the pole faces of the element [m]. (default: ``0``). - -**fint** - A *number* specifying the fringe field integral at entrance of the element. (default: ``0``). - -**fintx** - A *number* specifying the fringe field integral at exit of the element. (default: ``fint``). - -**fringe** - A *number* specifying the bitmask to activate fringe fields of the element, see :ref:`Flags ` for details. (default: ``0``). - -**fringemax** - A *number* specifying the maximum order for multipolar fringe fields of the element. (default: ``2``). - -**kill_ent_fringe** - A *log* specifying to kill the entry fringe fields of the element. (default: ``false``). - -**kill_exi_fringe** - A *log* specifying to kill the entry fringe fields of the element. (default: ``false``). - -**f1, f2** - A *number* specifying quadrupolar fringe field first and second parameter of SAD. (default: ``0``). - - -Methods -------- - -The ``element`` object provides the following methods: - -**select** - A *method* ``([flg])`` to select the element for the flags ``flg`` (default: ``selected``). - -**deselect** - A *method* ``([flg])`` to deselect the element for the flags ``flg`` (default: ``selected``). - -**is_selected** - A *method* ``([flg])`` to test the element for the flags ``flg`` (default: ``selected``). - -**is_disabled** - A *method* ``()`` to test if the element is *disabled*, which is equivalent to call the method ``is_selected(disabled)``. - -**is_observed** - A *method* ``()`` to test if the element is *observed*, which is equivalent to call the method ``is_selected(observed)``. - -**is_implicit** - A *method* ``()`` to test if the element is *implicit*, which is equivalent to call the method ``is_selected(implicit)``. - - -The ``drift_element`` and ``thick_element`` objects provide the following extra methods, see :ref:`sub-elements ` for details about the ``sat`` attribute: - -**index_sat** - A *method* ``(sat, [cmp])`` returning the lowest index ``idx`` (starting from 1) of the first sub-element with a relative position from the element entry that compares ``true`` with the *number* ``sat`` using the optional \CALBLA{cmp(sat, self[idx].sat)} (default: ``"=="``), or ``#self+1``. In the presence of multiple equal positions, ``"<="`` (resp. ``">="``) will return the lowest index of the position while ``"<"`` (resp. ``">"``) the lowest index next to the position for ascending (resp. descending) order. - -**insert_sat** - A *method* ``(elm, [cmp])`` returning the element after inserting the sub-element ``elm`` at the index determined by ``:index_sat(elm.sat, [cmp])`` using the optional \CALBLA{cmp} (default: ``"<"``). - -**replace_sat** - A *method* ``(elm)`` returning the replaced sub-element found at the index determined by ``:index_sat(elm.sat)`` by the new sub-element ``elm``, or ``nil``. - -**remove_sat** - A *method* ``(sat)`` returning the removed sub-element found at the index determined by ``:index_sat(sat)``, or ``nil``. - - -Metamethods ------------ - -The ``element`` object provides the following metamethods: - -**__len** - A *metamethod* ``()`` overloading the length operator ``#`` to return the number of subelements in the *list* part of the element. - -**__add** - A *metamethod* ``(obj)`` overloading the binary operator ``+`` to build a ``bline`` object from the juxtaposition of two elements. - -**__mul** - A *metamethod* ``(n)`` overloading the binary operator ``*`` to build a ``bline`` object from the repetition of an element ``n`` times, i.e. one of the two operands must be a *number*. - -**__unm** - A *metamethod* ``(n)`` overloading the unary operator ``-`` to build a ``bline`` object from the turning of an element, i.e. reflect the element. - -**__tostring** - A *metamethod* ``()`` returning a *string* built from the element information, e.g. ``print(monitor 'bpm' {})`` display the *string* ``":monitor: 'bpm' memory-address`` - - -The operators overloading of elements allows to unify sequence and beamline definitions in a consistent and simple way, noting that ``sequence`` and ``bline`` are (external) elements too. - - - -**__elem** - A unique private *reference* that characterizes elements. - - -Elements --------- - -Some elements define new attributes or override the default values provided by the *root object* ``element``. The following subsections describe the elements supported by \MAD. - -SBend -""""" - -The ``sbend`` element is a sector bending magnet with a curved reference system as shown in :numref:`fig-gen-sbend`, and defines or overrides the following attributes: - -**k0** - A ``number`` specifying the dipolar strength of the element [:math:`\mathrm{m}^{-1}`]. - (default: :literal:`k0 = \s -> s.angle/s.l`). [#f5]_ [#f6]_ - -**k0s** - A *number* specifying the dipolar skew strength of the element [m\ :math:`^{-1}`]. (default: ``0``). - -**k1, k1s** - A *number* specifying respectively the quadrupolar and skew strengths of the element [m\ :math:`^{-2}`]. (default: ``0``). - -**k2, k2s** - A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). - -**fringe** - Set to flag ``fringe.bend`` to activate the fringe fields by default, see :ref:`Flags ` for details. - -.. figure:: fig/elm_refsys_sbend.jpg - :name: fig-gen-sbend - :align: center - - Reference system for a sector bending magnet. - -RBend -""""" - -The ``rbend`` element is a rectangular bending magnet with a straight reference system as shown in :numref:`fig-gen-rbend`, and defines or overrides the following attributes: - -**k0** - A ``number`` specifying the dipolar strength of the element [:math:`\mathrm{m}^{-1}`]. - (default: :literal:`k0 = \s -> s.angle/s.l`). [#f5]_ [#f6]_ - -**k0s** - A *number* specifying the dipolar skew strength of the element [m\ :math:`^{-1}`]. (default: ``0``). - -**k1, k1s** - A *number* specifying respectively the quadrupolar and skew strengths of the element [m\ :math:`^{-2}`]. (default: ``0``). - -**k2, k2s** - A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). - -**fringe** - Set to flag ``fringe.bend`` to activate the fringe fields by default, see :ref:`Flags ` for details. - -**true_rbend** - A *log* specifying if this ``rbend`` element behaves like (``false``) a ``sbend`` element with parallel pole faces, i.e. :math:`e_1=e_2=\alpha/2` in Figure ``_ , or like (``true``) a rectangular bending magnet with a straight reference system as shown in Figure ``_ . (default: ``false``). [#f6]_ - -.. figure:: fig/elm_refsys_rbend.jpg - :name: fig-gen-rbend - :align: center - - Reference system for a rectangular bending magnet. - -Quadrupole -"""""""""" - -The ``quadrupole`` element is a straight focusing element and defines the following attributes: - -**k0, k0s** - A *number* specifying respectively the dipolar and skew strengths of the element [m\ :math:`^{-1}`]. (default: ``0``). - -**k1, k1s** - A *number* specifying respectively the quadrupolar and skew strengths of the element [m\ :math:`^{-2}`]. (default: ``0``). - -**k2, k2s** - A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). - - -Sextupole -""""""""" - -The ``sextupole`` element is a straight element and defines the following attributes: - -**k2, k2s** - A *number* specifying respectively the sextupolar and skew strengths of the element [m\ :math:`^{-3}`]. (default: ``0``). - - -Octupole -"""""""" - -The ``octupole`` element is a straight element and defines the following attributes: - -**k3, k3s** - A *number* specifying respectively the octupolar and skew strengths of the element [m\ :math:`^{-4}`]. (default: ``0``). - - -Decapole -"""""""" - -The ``decapole`` element is a straight element and defines the following attributes: - -**k4, k4s** - A *number* specifying respectively the decapolar and skew strength of the element [m\ :math:`^{-5}`]. (default: ``0``). - - -Dodecapole -"""""""""" - -The ``dodecapole`` element is a straight element and defines the following attributes: - -**k5, k5s** - A *number* specifying respectively the dodecapolar and skew strength of the element [m\ :math:`^{-6}`]. (default: ``0``). - - -Solenoid -"""""""" - -The ``solenoid`` element defines the following attributes: - -**ks, ksi** - A *number* specifying respectively the strength [rad/m] and the integrated strength [rad] of the element. A positive value points toward positive :math:`s`. (default: ``0``). - - -Multipole -""""""""" - -The ``multipole`` element is a thin element and defines the following attributes: - -**knl, ksl** - A *list* specifying respectively the multipolar and skew integrated strengths of the element [m\ :math:`^{-i+1}`]. (default: ``{}``). - -**dknl, dksl** - A *list* specifying respectively the multipolar and skew integrated strengths errors of the element [m\ :math:`^{-i+1}`]. (default: ``{}``). - - -TKicker -""""""" - -The ``tkicker`` element is the *root object* of kickers and defines or overrides the following attributes: - -**hkick** - A *number* specifying the horizontal strength of the element [m\ :math:`^{-1}`]. By convention, a kicker with a positive horizontal strength kicks in the direction of the reference orbit, e.g. ``hkick`` :math:`\equiv` ``- knl[1]``. (default: ``0``). - -**vkick** - A *number* specifying the vertical strength of the element [m\ :math:`^{-1}`]. By convention, a kicker with a positive vertical strength kicks toward the reference orbit, e.g. ``vkick`` :math:`\equiv` ``ksl[1]``}. (default: ``0``). - -**method** - Set to ``2`` if ``ptcmodel`` is not set to enforce pure momentum kick and avoid dipolar strength integration that would introduce dispersion. - - -Kicker, HKicker, VKicker -"""""""""""""""""""""""" - -The ``kicker`` element inheriting from the ``tkicker`` element, is the *root object* of kickers involved in the orbit correction and defines the following attributes: - -**chkick, cvkick** - A *number* specifying respectively the horizontal and vertical correction strength of the element set by the :doc:`correct ` command [m\ :math:`^{-1}`]. (default: ). - - -The ``hkicker`` (horizontal kicker) and ``vkicker`` (vertical kicker) elements define the following attribute: - -**kick** - A *number* specifying the strength of the element in its main direction [m\ :math:`^{-1}`]. (default: ). - - -Monitor, HMonitor, VMonitor -""""""""""""""""""""""""""" - -The ``monitor`` element is the root object of monitors involved in the orbit correction and defines the following attributes: - -**mredx, mredy** - A *number* specifying respectively the readout :math:`x`\ , :math:`y`\ -offset error of the element [m]. The offset is added to the beam position during orbit correction (after scaling). (default: ``0``). - -**mresx, mresy** - A *number* specifying respectively the readout :math:`x`\ ,:math:`y`\ -scaling error of the element. The scale factor multiplies the beam position by ``1+mres`` (before offset) during orbit correction. [#f7]_ (default: ``0``). - - -The ``hmonitor`` (horizontal monitor) and ``vmonitor`` (vertical monitor) elements are specialisations inheriting from the ``monitor`` element. - -RFCavity -"""""""" - -The ``rfcavity`` element defines the following attributes: - -**volt** - A *number* specifying the peak RF voltage of the element [MV]. (default: ``0``). - -**freq** - A *number* specifying a non-zero RF frequency of the element [MHz]. (default: ``0``). - -**lag** - A *number* specifying the RF phase lag of the element in unit of :math:`2\pi`. (default: ``0``). - -**harmon** - A *number* specifying the harmonic number of the element if ``freq`` is zero. (default: ``0``). - -**n_bessel** - A *number* specifying the transverse focussing effects order of the element. (default: ``0``). - -**totalpath** - A *log* specifying if the totalpath must be used in the element. (default: ``true``). - - -RFMultipole -""""""""""" - -The ``rfmultipole`` element defines the following attributes: - -**pnl, psl** - A *list* specifying respectively the multipolar and skew phases of the element [rad]. (default: :literal:`{}`). - -**dpnl, dpsl** - A *list* specifying respectively the multipolar and skew phases errors of the element [rad]. (default: :literal:`{}`). - - -ElSeparator -""""""""""" - -The ``elseparator`` element defines the following attributes: - -**ex, ey** - A *number* specifying respectively the electric field :math:`x`\ , :math:`y`\ -strength of the element [MV/m]. (default: ``0``). - -**exl, eyl** - A *number* specifying respectively the integrated electric field :math:`x`\ , :math:`y`\ -strength of the element [MV]. (default: ``0``). - - -Wiggler -""""""" - -The ``wiggler`` element defines the following attributes: NYI, TBD - -BeamBeam -"""""""" - -The ``beambeam`` element defines the following attributes: NYI, TBD - -GenMap -"""""" - -The ``genmap`` element defines the following attributes: [#f8]_ - -**damap** - A ``damap`` used for thick integration. - -**update** - A *callable* ``(elm, mflw, lw)`` invoked before each step of thick integration to update the ``damap``. (default: ``nil``) - -**nslice** - A *number* specifying the number of slices or a *list* of increasing relative positions or a *callable* ``(elm, mflw, lw)`` returning one of the two previous kind of positions specification to use when tracking through the element and overriding the command attribute, see the :doc:`survey ` or the :doc:`track ` commands for details. (default: ``1``). - - -SLink -""""" - -The ``slink`` element defines the following attributes: [#f9]_ - -**sequence** - A *sequence* to switch to right after exiting the element. (default: ``nil``) - -**range** - A *range* specifying the span over the sequence to switch to, as expected by the sequence method ``:siter``. (default: ``nil``). - -**nturn** - A *number* specifying the number of turn to track the sequence to switch to, as expected by the sequence method ``:siter``. (default: ``nil``). - -**dir** - A *number* specifying the :math:`s`-direction of the tracking of the sequence to switch to, as expected by the sequence method ``:siter``. (default: ``nil``). - -**update** - A *callable* ``(elm, mflw)`` invoked before retrieving the other attributes when entering the element. (default: ``nil``) - - -Translate -""""""""" - -The ``translate`` element is a patch element and defines the following attributes: - -**dx, dy, ds** - A *number* specifying respectively :math:`x`\ , :math:`y`\ , :math:`s`-translation of the reference frame [m]. (default: ``0``) - - -XRotation, YRotation, SRotation -""""""""""""""""""""""""""""""" - -The ``xrotation`` (rotation around :math:`x`-axis), ``yrotation`` (rotation around :math:`y`-axis) and ``srotation`` (rotation around :math:`s`-axis) elements are patches element and define the following attribute: - -**angle** - A *number* specifying the rotation angle around the axis of the element [rad]. (default: ``0``). - - -ChangeRef -""""""""" - -The ``changeref`` element is a patch element and defines the following attributes: - -**dx, dy, ds** - A *number* specifying respectively :math:`x`\ , :math:`y`\ , :math:`s`-translation of the reference frame [m]. (default: ``0``) - -**dtheta, dphi, dpsi** - A *number* specifying respectively :math:`y`\ , :math:`-x`\ , :math:`s`-rotation of the reference frame applied in this order after any translation [rad]. (default: ``0``) - - -ChangeDir -""""""""" - -The ``changedir`` element is a patch element that reverses the direction of the sequence during the tracking. - -ChangeNrj -""""""""" - -The ``changenrj`` element is a patch element and defines the following attributes: - -**dnrj** - A *number* specifying the change by :math:`\delta_E` of the *reference* beam energy [GeV]. The momenta of the particles or damaps belonging to the reference beam (i.e. not owning a beam) are updated, while other particles or damaps owning their beam are ignored. (default: ``0``) - -.. _sec.elm.flgs: - -Flags ------ - -The ``element`` module exposes the following *object* flags through ``MAD.element.flags`` to use in conjunction with the methods ``select`` and ``deselect``: [#f10]_ - -**none** - All bits zero. - -**selected** - Set if the element has been selected. - -**disabled** - Set if the element has been disabled, e.g. for orbit correction. - -**observed** - Set if the element has been selected for observation, e.g. for output to TFS table. - The ``$end`` markers are selected for observation by default, and commands with the ``observe`` attribute set to ``0`` discard this flag and consider all elements as selected for observation. - -**implicit** - Set if the element is implicit, like the temporary *implicit* drifts created on-the-fly by the ``sequence`` :math:`s`-iterator with indexes at half integers. This flag is used by commands with the ``implicit`` attribute. - -**playout** - Set if the element ``angle`` must be used by layout plot. This flag is useful to plot multiple sequence layouts around interaction points, like ``lhcb1`` and ``lhcb2`` around ``IP1`` and ``IP5``. - -.. _sec.elm.frng: - -Fringe fields -------------- - -The ``element`` module exposes the following flags through ``MAD.element.flags.fringe`` to *control* the elements fringe fields through their attribute ``fringe``, or to *restrict* the activated fringe fields with the commands attribute ``fringe``: [#f11]_ - -**none** - All bits zero. - -**bend** - Control the element fringe fields for bending fields. - -**mult** - Control the element fringe fields for multipolar fields up to ``fringemax`` order. - -**rfcav** - Control the element fringe fields for rfcavity fields. - -**qsad** - Control the element fringe fields for multipolar fields with extra terms for quadrupolar fields for compatibility with SAD. - -**comb** - Control the element fringe fields for combined bending and multipolar fields. - -**combqs** - Control the element fringe fields for combined bending and multipolar fields with extra terms for quadrupolar fields for compatibility with SAD. - -The ``thick_element`` provides a dozen of attributes to parametrize the aforementionned fringe fields. Note that in some future, part of these attributes may be grouped into a *mappable* to ensure a better consistency of their parametrization. - -.. _sec.elm.subelm: - -Sub-elements ------------- - -An element can have thin or thick sub-elements stored in its *list* part, hence the length operator ``#`` returns the number of them. The attribute ``sat`` of sub-elements, i.e. read ``s``\ ub-\ ``at``\ , is interpreted as their relative position from the entry of their enclosing main element, that is a fractional of its length. The positions of the sub-elements can be made absolute by dividing their ``sat`` attribute by the length of their main element using lambda expressions. The sub-elements are only considered and valid in the ``drift_element`` and ``thick_element`` kinds that implement the methods ``:index_sat``, ``:insert_sat``, ``:remove_sat``, and ``:replace_sat`` to manage sub-elements from their ``sat`` attribute. The sequence method ``:install`` updates the ``sat`` attribute of the elements installed as sub-elements if the *log* ``elements.subelem`` of the packed form is enabled, i.e. when the :math:`s`-position determined by the ``at``, ``from`` and ``refpos`` attributes falls inside a non-zero length element already installed in the sequence that is not an *implicit* drift. The physics of thick sub-elements will shield the physics of their enclosing main element along their length, unless they combine their attributes with those of their main element using lambda expressions to select some combined function physics. - -.. _sec.elm.aper: - -Aperture --------- - -All the apertures are *mappable* defined by the following attributes in the tilted frame of an element, see the :doc:`track ` command for details: - -**kind** - A *string* specifying the aperture shape. (no default). - -**tilt** - A *number* specifying the tilt angle of the aperture [rad]. (default: ``0``). - -**xoff, yoff** - A *number* specifying the transverse :math:`x,y`\ -offset of the aperture [m]. (default: ``0``). - -**maper** - A *mappable* specifying a smaller aperture [#f12]_ than the ``polygon`` aperture to use before checking the polygon itself to speed up the test. The attributes ``tilt``, ``xoff`` and ``yoff`` are ignored and superseded by the ones of the ``polygon`` aperture. (default: ``nil``). - - -The supported aperture shapes are listed hereafter. The parameters defining the shapes are expected to be in the *list* part of the apertures and defines the top-right sector shape, except for the ``polygon``: - -**square** - A square shape with one parameter defining the side half-length. It is the default aperture check with limits set to ``1``. - -**rectangle** - A rectangular shape with two parameters defining the :math:`x`\ , :math:`y`\ -half lengths (default: ``1`` [m]). - -**circle** - A circular shape with one parameter defining the radius. - -**ellipse** - A elliptical shape with two parameters defining the :math:`x`\ , :math:`y`\ -radii. (default: ``1`` [m]). - -**rectcircle** - A rectangular shape intersected with a circular shape with three parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the radius. (default: ``1`` [m]). - -**rectellipse** - A rectangular shape intersected with an elliptical shape with four parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the :math:`x`\ , :math:`y`\ -radii. - -**racetrack** - A rectangular shape with corners rounded by an elliptical shape with four parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the corners :math:`x`\ , :math:`y`\ -radii. - -**octagon** - A rectangular shape with corners truncated by a triangular shape with four parameters defining the :math:`x`\ , :math:`y`\ -half lengths and the triangle :math:`x`\ , :math:`y`\ -side lengths. An octagon can model hexagon or diamond shapes by equating the triangle lengths to the rectangle half-lengths. - -**polygon** - A polygonal shape defined by two vectors ``vx`` and ``vy`` holding the vertices coordinates. The polygon does not need to be convex, simple or closed, but in the latter case it will be closed automatically by joining the first and the last vertices. - -**bbox** - A 6D bounding box with six parameters defining the upper limits of the absolute values of the six coordinates. - - - - -.. code-block:: lua - - local quadrupole in MAD.element - local mq = quadrupole 'mq' { l=1, -- new class - aperture = { kind='racetrack', - tilt=pi/2, xoff=1e-3, yoff=5e-4, -- attributes - 0.06,0.06,0.01,0.01 } -- parameters - } - local mqdiam = quadrupole 'mqdiam' { l=1, -- new class - aperture = { kind='octagon', xoff=1e-3, yoff=1e-3, -- attributes - 0.06,0.04,0.06,0.04 } -- parameters - } - local mqpoly = quadrupole 'mqpoly' { l=1, -- new class - aperture = { kind='polygon', tilt=pi/2, xoff=1e-3, yoff=1e-3, -- attributes - vx=vector{0.05, ...}, vy=vector{0, ...}, -- parameters - aper={kind='circle', 0.05} -- 2nd aperture - } - -.. _sec.elm.misalign: - -Misalignment ------------- - -The misalignments are *mappable* defined at the entry of an element by the following attributes, see the :doc:`track ` command for details: - -**dx, dy, ds** - A *number* specifying the :math:`x`\ , :math:`y`\ , :math:`s`\ -displacement at the element entry [m], see :numref:`fig-gen-dispxs` and :numref:`fig-gen-dispys` . (default: ``0``). - -**dtheta** - A *number* specifying the :math:`y`-rotation angle (azimuthal) at the element entry [rad], see :numref:`fig-gen-dispxs`. (default: ``0``). - -**dphi** - A *number* specifying the :math:`-x`-rotation angle (elevation) at the entry of the element [rad], see :numref:`fig-gen-dispxy` . (default: ``0``). - -**dpsi** - A *number* specifying the :math:`s`-rotation angle (roll) at the element entry [rad], see :numref:`fig-gen-dispxy` . (default: ``0``). - -Two kinds of misalignments are available for an element and summed beforehand: - - -* The *absolute* misalignments of the element versus its local reference frame, and specified by its ``misalign`` attribute. These misalignments are always considered. - -* The *relative* misalignments of the element versus a given sequence, and specified by the ``:misalign`` of ``sequence``. These misalignments can be considered or not depending of command settings. - -.. figure:: fig/elm_dsplmnt_xs.jpg - :name: fig-gen-dispxs - :align: center - - Displacements in the :math:`(x, s)` plane. - -.. figure:: fig/elm_dsplmnt_ys.jpg - :name: fig-gen-dispys - :align: center - - Displacements in the :math:`(y, s)` plane. - - -.. figure:: fig/elm_dsplmnt_xy.jpg - :name: fig-gen-dispxy - :align: center - - Displacements in the :math:`(x, y)` plane. - -.. rubric:: Footnotes - -.. [#f1] In MAD-X, zero-length ``sextupole`` and ``octupole`` are valid but may have surprising effects... -.. [#f2] E.g. zero-length ``sextupole`` must define their strength with ``knl[3]`` instead of ``k2`` to have the expected effect. -.. [#f3] By default ``minlen`` = :math:`10^{-12}` m. -.. [#f4] This attribute was introduced to ease the translation of MAD-X sequences and may disappear in some future. -.. [#f5] By default bending magnets are ideal bends, that is ``angle = k0*l`` -.. [#f6] For compatibility with MAD-X. -.. [#f7] This definition comes from MAD-X default zeroed values such that undefined attribute gives a scale of ``1``. -.. [#f8] This element is a generalization of the ``matrix`` element of MAD-X, to use with care! -.. [#f9] This element allows to switch between sequences during tracking, kind of ``if-then-else`` for tracking. -.. [#f10] Remember that flags are *not* inherited nor copied as they are qualifying the object itself. -.. [#f11] Those flags are *not* object flags, but fringe fields flags. -.. [#f12] It is the responsibility of the user to ensure that ``maper`` defines a smaller aperture than the polygon aperture. \ No newline at end of file diff --git a/docs/source/emit.rst b/docs/source/emit.rst deleted file mode 100644 index 5569dcd1f..000000000 --- a/docs/source/emit.rst +++ /dev/null @@ -1,8 +0,0 @@ -Emit -==== -.. _ch.cmd.emit: - -This command is not yet implemented in MAD. It will probably be implemented as a layer on top of the Twiss and Match commands. - -.. rubric:: Footnotes - diff --git a/docs/source/extern.rst b/docs/source/extern.rst deleted file mode 100644 index c7ac53593..000000000 --- a/docs/source/extern.rst +++ /dev/null @@ -1,3 +0,0 @@ -External modules -================ -.. _ch.mod.extrn: diff --git a/docs/source/fig/dyna-trck-slice-crop.png b/docs/source/fig/dyna-trck-slice-crop.png deleted file mode 100644 index 7333de0ce..000000000 Binary files a/docs/source/fig/dyna-trck-slice-crop.png and /dev/null differ diff --git a/docs/source/fig/dyna-trck-slice.png b/docs/source/fig/dyna-trck-slice.png deleted file mode 100644 index fb1c10851..000000000 Binary files a/docs/source/fig/dyna-trck-slice.png and /dev/null differ diff --git a/docs/source/fig/elm_dsplmnt_xs.jpg b/docs/source/fig/elm_dsplmnt_xs.jpg deleted file mode 100644 index 77131cea1..000000000 Binary files a/docs/source/fig/elm_dsplmnt_xs.jpg and /dev/null differ diff --git a/docs/source/fig/elm_dsplmnt_xy.jpg b/docs/source/fig/elm_dsplmnt_xy.jpg deleted file mode 100644 index 5fc0190f7..000000000 Binary files a/docs/source/fig/elm_dsplmnt_xy.jpg and /dev/null differ diff --git a/docs/source/fig/elm_dsplmnt_ys.jpg b/docs/source/fig/elm_dsplmnt_ys.jpg deleted file mode 100644 index 60709a757..000000000 Binary files a/docs/source/fig/elm_dsplmnt_ys.jpg and /dev/null differ diff --git a/docs/source/fig/elm_refsys_rbend.jpg b/docs/source/fig/elm_refsys_rbend.jpg deleted file mode 100644 index 7dbeee150..000000000 Binary files a/docs/source/fig/elm_refsys_rbend.jpg and /dev/null differ diff --git a/docs/source/fig/elm_refsys_sbend.jpg b/docs/source/fig/elm_refsys_sbend.jpg deleted file mode 100644 index 2a1c0a3de..000000000 Binary files a/docs/source/fig/elm_refsys_sbend.jpg and /dev/null differ diff --git a/docs/source/fig/geom-trck-slice-crop.png b/docs/source/fig/geom-trck-slice-crop.png deleted file mode 100644 index 058a028e2..000000000 Binary files a/docs/source/fig/geom-trck-slice-crop.png and /dev/null differ diff --git a/docs/source/fig/madng-ecosys-crop.png b/docs/source/fig/madng-ecosys-crop.png deleted file mode 100644 index e669399f0..000000000 Binary files a/docs/source/fig/madng-ecosys-crop.png and /dev/null differ diff --git a/docs/source/fig/objmod-lookup-crop.png b/docs/source/fig/objmod-lookup-crop.png deleted file mode 100644 index 5891a31b5..000000000 Binary files a/docs/source/fig/objmod-lookup-crop.png and /dev/null differ diff --git a/docs/source/fig/phys_refsys_glo.jpg b/docs/source/fig/phys_refsys_glo.jpg deleted file mode 100644 index de66ce414..000000000 Binary files a/docs/source/fig/phys_refsys_glo.jpg and /dev/null differ diff --git a/docs/source/fig/phys_refsys_loc.jpg b/docs/source/fig/phys_refsys_loc.jpg deleted file mode 100644 index 899c08e1d..000000000 Binary files a/docs/source/fig/phys_refsys_loc.jpg and /dev/null differ diff --git a/docs/source/functions.rst b/docs/source/functions.rst deleted file mode 100644 index bd1baf036..000000000 --- a/docs/source/functions.rst +++ /dev/null @@ -1,395 +0,0 @@ -.. index:: - Functions - -********* -Functions -********* - -This chapter describes some functions provided by the modules :mod:`MAD.gmath` and :mod:`MAD.gfunc`. - -The module :mod:`gmath` extends the standard LUA module :mod:`math` with *generic* functions working on any types that support the methods with the same names. For example, the code :func:`gmath.sin(a)` will call :func:`math.sin(a)` if :var:`a` is a :type:`number`, otherwise it will call the method :func:`a:sin()`, i.e. delegate the invocation to :obj:`a`. This is how MAD-NG handles several types like :type:`numbers`, :type:`complex` number and :type:`TPSA` within a single *polymorphic* code that expects scalar-like behavior. - -The module :mod:`gfunc` provides useful functions to help dealing with operators as functions and to manipulate functions in a `functional `_ way [#f1]_. - -Mathematical Functions -====================== - -Generic Real-like Functions ---------------------------- - -Real-like generic functions forward the call to the method of the same name from the first argument when the latter is not a :type:`number`. The optional argument :var:`r_` represents a destination placeholder for results with reference semantic, i.e. avoiding memory allocation, which is ignored by results with value semantic. The C functions column lists the C implementation used when the argument is a :type:`number` and the implementation does not rely on the standard :code:`math` module but on functions provided with MAD-NG or by the standard math library described in the C Programming Language Standard [ISOC99]_. - -=============================== ======================================================= ============= -Functions Return values C functions -=============================== ======================================================= ============= -:func:`abs(x,r_)` :math:`|x|` -:func:`acos(x,r_)` :math:`\cos^{-1} x` -:func:`acosh(x,r_)` :math:`\cosh^{-1} x` :c:func:`acosh` -:func:`acot(x,r_)` :math:`\cot^{-1} x` -:func:`acoth(x,r_)` :math:`\coth^{-1} x` :c:func:`atanh` -:func:`asin(x,r_)` :math:`\sin^{-1} x` -:func:`asinc(x,r_)` :math:`\frac{\sin^{-1} x}{x}` :c:func:`mad_num_asinc` -:func:`asinh(x,r_)` :math:`\sinh^{-1} x` :c:func:`asinh` -:func:`asinhc(x,r_)` :math:`\frac{\sinh^{-1} x}{x}` :c:func:`mad_num_asinhc` -:func:`atan(x,r_)` :math:`\tan^{-1} x` -:func:`atan2(x,y,r_)` :math:`\tan^{-1} \frac{x}{y}` -:func:`atanh(x,r_)` :math:`\tanh^{-1} x` :c:func:`atanh` -:func:`ceil(x,r_)` :math:`\lceil x \rceil` -:func:`cos(x,r_)` :math:`\cos x` -:func:`cosh(x,r_)` :math:`\cosh x` -:func:`cot(x,r_)` :math:`\cot x` -:func:`coth(x,r_)` :math:`\coth x` -:func:`exp(x,r_)` :math:`\exp x` -:func:`floor(x,r_)` :math:`\lfloor x \rfloor` -:func:`frac(x,r_)` :math:`x - \operatorname{trunc}(x)` -:func:`hypot(x,y,r_)` :math:`\sqrt{x^2+y^2}` :c:func:`hypot` -:func:`hypot3(x,y,z,r_)` :math:`\sqrt{x^2+y^2+z^2}` :c:func:`hypot` -:func:`inv(x,v_,r_)` [#f2]_ :math:`\frac{v}{x}` -:func:`invsqrt(x,v_,r_)` [#f2]_ :math:`\frac{v}{\sqrt x}` -:func:`lgamma(x,tol_,r_)` :math:`\ln|\Gamma(x)|` :c:func:`lgamma` -:func:`log(x,r_)` :math:`\log x` -:func:`log10(x,r_)` :math:`\log_{10} x` -:func:`powi(x,n,r_)` :math:`x^n` :c:func:`mad_num_powi` -:func:`round(x,r_)` :math:`\lfloor x \rceil` :c:func:`round` -:func:`sign(x)` :math:`-1, 0\text{ or }1` :c:func:`mad_num_sign` [#f3]_ -:func:`sign1(x)` :math:`-1\text{ or }1` :c:func:`mad_num_sign1` [#f3]_ -:func:`sin(x,r_)` :math:`\sin x` -:func:`sinc(x,r_)` :math:`\frac{\sin x}{x}` :c:func:`mad_num_sinc` -:func:`sinh(x,r_)` :math:`\sinh x` -:func:`sinhc(x,r_)` :math:`\frac{\sinh x}{x}` :c:func:`mad_num_sinhc` -:func:`sqrt(x,r_)` :math:`\sqrt{x}` -:func:`tan(x,r_)` :math:`\tan x` -:func:`tanh(x,r_)` :math:`\tanh x` -:func:`tgamma(x,tol_,r_)` :math:`\Gamma(x)` :c:func:`tgamma` -:func:`trunc(x,r_)` :math:`\lfloor x \rfloor, x\geq 0;\lceil x \rceil, x<0` -:func:`unit(x,r_)` :math:`\frac{x}{|x|}` -=============================== ======================================================= ============= - -Generic Complex-like Functions ------------------------------- - -Complex-like generic functions forward the call to the method of the same name from the first argument when the latter is not a :type:`number`, otherwise it implements a real-like compatibility layer using the equivalent representation :math:`z=x+0i`. The optional argument :var:`r_` represents a destination for results with reference semantic, i.e. avoiding memory allocation, which is ignored by results with value semantic. - -======================= ================================== -Functions Return values -======================= ================================== -:func:`cabs(z,r_)` :math:`|z|` -:func:`carg(z,r_)` :math:`\arg z` -:func:`conj(z,r_)` :math:`z^*` -:func:`cplx(x,y,r_)` :math:`x+i\,y` -:func:`fabs(z,r_)` :math:`|\Re(z)|+i\,|\Im(z)|` -:func:`imag(z,r_)` :math:`\Im(z)` -:func:`polar(z,r_)` :math:`|z|\,e^{i \arg z}` -:func:`proj(z,r_)` :math:`\operatorname{proj}(z)` -:func:`real(z,r_)` :math:`\Re(z)` -:func:`rect(z,r_)` :math:`\Re(z)\cos \Im(z)+i\,\Re(z)\sin \Im(z)` -:func:`reim(z,re_,im_)` :math:`\Re(z), \Im(z)` -======================= ================================== - -Generic Vector-like Functions ------------------------------ - -Vector-like functions (also known as MapFold or MapReduce) are functions useful when used as high-order functions passed to methods like :func:`:map2()`, :func:`:foldl()` (fold left) or :func:`:foldr()` (fold right) of containers like lists, vectors and matrices. - -==================== ======================== -Functions Return values -==================== ======================== -:func:`sumsqr(x,y)` :math:`x^2 + y^2` -:func:`sumabs(x,y)` :math:`|x| + |y|` -:func:`minabs(x,y)` :math:`\min(|x|, |y|)` -:func:`maxabs(x,y)` :math:`\max(|x|, |y|)` -:func:`sumsqrl(x,y)` :math:`x + y^2` -:func:`sumabsl(x,y)` :math:`x + |y|` -:func:`minabsl(x,y)` :math:`\min(x, |y|)` -:func:`maxabsl(x,y)` :math:`\max(x, |y|)` -:func:`sumsqrr(x,y)` :math:`x^2 + y` -:func:`sumabsr(x,y)` :math:`|x| + y` -:func:`minabsr(x,y)` :math:`\min(|x|, y)` -:func:`maxabsr(x,y)` :math:`\max(|x|, y)` -==================== ======================== - -Generic Error-like Functions ----------------------------- - -Error-like generic functions forward the call to the method of the same name from the first argument when the latter is not a :type:`number`, otherwise it calls C wrappers to the corresponding functions from the `Faddeeva library `_ from the MIT (see :file:`mad_num.c`). The optional argument :var:`r_` represents a destination for results with reference semantic, i.e. avoiding memory allocation, which is ignored by results with value semantic. - -========================== ========================================================== ======================== -Functions Return values C functions -========================== ========================================================== ======================== -:func:`erf(z,rtol_,r_)` :math:`\frac{2}{\sqrt\pi}\int_0^z e^{-t^2} dt` :c:func:`mad_num_erf` -:func:`erfc(z,rtol_,r_)` :math:`1-\operatorname{erf}(z)` :c:func:`mad_num_erfc` -:func:`erfi(z,rtol_,r_)` :math:`-i\operatorname{erf}(i z)` :c:func:`mad_num_erfi` -:func:`erfcx(z,rtol_,r_)` :math:`e^{z^2}\operatorname{erfc}(z)` :c:func:`mad_num_erfcx` -:func:`wf(z,rtol_,r_)` :math:`e^{-z^2}\operatorname{erfc}(-i z)` :c:func:`mad_num_wf` -:func:`dawson(z,rtol_,r_)` :math:`\frac{-i\sqrt\pi}{2}e^{-z^2}\operatorname{erf}(iz)` :c:func:`mad_num_dawson` -========================== ========================================================== ======================== - -Special Functions ------------------ - -The special function :func:`fact()` supports negative integers as input as it uses extended factorial definition, and the values are cached to make its complexity in :math:`O(1)` after warmup. - -The special function :func:`rangle()` adjust the angle :var:`a` versus the *previous* right angle :var:`r`, e.g. during phase advance accumulation, to ensure proper value when passing through the :math:`\pm 2k\pi` boundaries. - -=================== ================================================ ========================= -Functions Return values C functions -=================== ================================================ ========================= -:func:`fact(n)` :math:`n!` :c:func:`mad_num_fact` -:func:`rangle(a,r)` :math:`a + 2\pi \lfloor \frac{r-a}{2\pi} \rceil` :c:func:`round` -=================== ================================================ ========================= - -Functions for Circular Sector ------------------------------ - -Basic functions for arc and cord lengths conversion rely on the following elementary relations: - -.. math:: - - l_{\text{arc}} &= a r = \frac{l_{\text{cord}}}{\operatorname{sinc} \frac{a}{2}} - - l_{\text{cord}} &= 2 r \sin \frac{a}{2} = l_{\text{arc}} \operatorname{sinc} \frac{a}{2} - -where :math:`r` stands for the radius and :math:`a` for the angle of the `Circular Sector `_. - -===================== ===================================== -Functions Return values -===================== ===================================== -:func:`arc2cord(l,a)` :math:`l_{\text{arc}} \operatorname{sinc} \frac{a}{2}` -:func:`arc2len(l,a)` :math:`l_{\text{arc}} \operatorname{sinc} \frac{a}{2}\, \cos a` -:func:`cord2arc(l,a)` :math:`\frac{l_{\text{cord}}}{\operatorname{sinc} \frac{a}{2}}` -:func:`cord2len(l,a)` :math:`l_{\text{cord}} \cos a` -:func:`len2arc(l,a)` :math:`\frac{l}{\operatorname{sinc} \frac{a}{2}\, cos a}` -:func:`len2cord(l,a)` :math:`\frac{l}{\cos a}` -===================== ===================================== - -.. ---------------------------------------------- - -Operators as Functions -====================== - -The module :mod:`MAD.gfunc` provides many functions that are named version of operators and useful when operators cannot be used directly, e.g. when passed as argument or to compose together. These functions can also be retrieved from the module :mod:`MAD.gfunc.opstr` by their associated string (if available). - -Math Operators --------------- - -Functions for math operators are wrappers to associated mathematical operators, which themselves can be overridden by their associated metamethods. - -================ ================= =============== =================== -Functions Return values Operator string Metamethods -================ ================= =============== =================== -:func:`unm(x)` :math:`-x` :const:`"~"` :func:`__unm(x,_)` -:func:`inv(x)` :math:`1 / x` :const:`"1/"` :func:`__div(1,x)` -:func:`sqr(x)` :math:`x \cdot x` :const:`"^2"` :func:`__mul(x,x)` -:func:`add(x,y)` :math:`x + y` :const:`"+"` :func:`__add(x,y)` -:func:`sub(x,y)` :math:`x - y` :const:`"-"` :func:`__sub(x,y)` -:func:`mul(x,y)` :math:`x \cdot y` :const:`"*"` :func:`__mul(x,y)` -:func:`div(x,y)` :math:`x / y` :const:`"/"` :func:`__div(x,y)` -:func:`mod(x,y)` :math:`x \mod y` :const:`"%"` :func:`__mod(x,y)` -:func:`pow(x,y)` :math:`x ^ y` :const:`"^"` :func:`__pow(x,y)` -================ ================= =============== =================== - -Element Operators ------------------ - -Functions for element-wise operators [#f4]_ are wrappers to associated mathematical operators of vector-like objects, which themselves can be overridden by their associated metamethods. - -==================== ===================== =============== ==================== -Functions Return values Operator string Metamethods -==================== ===================== =============== ==================== -:func:`emul(x,y,r_)` :math:`x\,.*\,y` :const:`".*"` :func:`__emul(x,y,r_)` -:func:`ediv(x,y,r_)` :math:`x\,./\,y` :const:`"./"` :func:`__ediv(x,y,r_)` -:func:`emod(x,y,r_)` :math:`x\,.\%\,y` :const:`".%"` :func:`__emod(x,y,r_)` -:func:`epow(x,y,r_)` :math:`x\,.\hat\ \ y` :const:`".^"` :func:`__epow(x,y,r_)` -==================== ===================== =============== ==================== - -Logical Operators ------------------ - -Functions for logical operators are wrappers to associated logical operators. - -================= =============================================================== =============== -Functions Return values Operator string -================= =============================================================== =============== -:func:`lfalse()` :const:`true` :const:`"T"` -:func:`ltrue()` :const:`false` :const:`"F"` -:func:`lnot(x)` :math:`\lnot x` :const:`"!"` -:func:`lbool(x)` :math:`\lnot\lnot x` :const:`"!!"` -:func:`land(x,y)` :math:`x \land y` :const:`"&&"` -:func:`lor(x,y)` :math:`x \lor y` :const:`"||"` -:func:`lnum(x)` :math:`\lnot x\rightarrow 0`, :math:`\lnot\lnot x\rightarrow 1` :const:`"!#"` -================= =============================================================== =============== - -Relational Operators --------------------- - -Functions for relational operators are wrappers to associated logical operators, which themselves can be overridden by their associated metamethods. Relational ordering operators are available only for objects that are ordered. - -================ ========================= ============================== ================= -Functions Return values Operator string Metamethods -================ ========================= ============================== ================= -:func:`eq(x,y)` :math:`x = y` :const:`"=="` :func:`__eq(x,y)` -:func:`ne(x,y)` :math:`x \neq y` :const:`"!="` or :const:`"~="` :func:`__eq(x,y)` -:func:`lt(x,y)` :math:`x < y` :const:`"<"` :func:`__lt(x,y)` -:func:`le(x,y)` :math:`x \leq y` :const:`"<="` :func:`__le(x,y)` -:func:`gt(x,y)` :math:`x > y` :const:`">"` :func:`__le(y,x)` -:func:`ge(x,y)` :math:`x \geq y` :const:`">="` :func:`__lt(y,x)` -:func:`cmp(x,y)` :math:`(x > y) - (x < y)` :const:`"?="` -================ ========================= ============================== ================= - -The special relational operator :func:`cmp()` returns the number :const:`1` for :math:`xy`, and :const:`0` otherwise. - -Object Operators ----------------- - -Functions for object operators are wrappers to associated object operators, which themselves can be overridden by their associated metamethods. - -=================== ============== =============== ================= -Functions Return values Operator string Metamethods -=================== ============== =============== ================= -:func:`get(x,k)` :math:`x[k]` :const:`"->"` :func:`__index(x,k)` -:func:`set(x,k,v)` :math:`x[k]=v` :const:`"<-"` :func:`__newindex(x,k,v)` -:func:`len(x)` :math:`\#x` :const:`"#"` :func:`__len(x)` -:func:`cat(x,y)` :math:`x .. y` :const:`".."` :func:`__concat(x,y)` -:func:`call(x,...)` :math:`x(...)` :const:`"()"` :func:`__call(x,...)` -=================== ============== =============== ================= - -Bitwise Functions -================= - -Functions for bitwise operations are those from the LuaJIT module :mod:`bit` and imported into the module :mod:`MAD.gfunc` for convenience, see http://bitop.luajit.org/api.html for details. Note that all these functions have *value semantic* and normalise their arguments to the numeric range of a 32 bit integer before use. - -==================== ==================================================== -Functions Return values -==================== ==================================================== -:func:`tobit(x)` Return the normalized value of :var:`x` to the range of a 32 bit integer -:func:`tohex(x,n_)` Return the hex string of :var:`x` with :var:`n` digits (:math:`n<0` use caps) -:func:`bnot(x)` Return the bitwise reverse of :var:`x` bits -:func:`band(x,...)` Return the bitwise *AND* of all arguments -:func:`bor(x,...)` Return the bitwise *OR* of all arguments -:func:`bxor(x,...)` Return the bitwise *XOR* of all arguments -:func:`lshift(x,n)` Return the bitwise left shift of :var:`x` by :var:`n` bits with 0-bit shift-in -:func:`rshift(x,n)` Return the bitwise right shift of :var:`x` by :var:`n` bits with 0-bit shift-in -:func:`arshift(x,n)` Return the bitwise right shift of :var:`x` by :var:`n` bits with sign bit shift-in -:func:`rol(x,n)` Return the bitwise left rotation of :var:`x` by :var:`n` bits -:func:`ror(x,n)` Return the bitwise right rotation of :var:`x` by :var:`n` bits -:func:`bswap(x)` Return the swapped bytes of :var:`x`, i.e. convert big endian to/from little endian -==================== ==================================================== - -Flags Functions ---------------- - -A flag is 32 bit unsigned integer used to store up to 32 binary states with the convention that :const:`0` means disabled/cleared and :const:`1` means enabled/set. Functions on flags are useful aliases to, or combination of, bitwise operations to manipulate their states (i.e. their bits). Flags are mainly used by the object model to keep track of hidden and user-defined states in a compact and efficient format. - -=================== ==================================================== -Functions Return values -=================== ==================================================== -:func:`bset(x,n)` Return the flag :var:`x` with state :var:`n` enabled -:func:`bclr(x,n)` Return the flag :var:`x` with state :var:`n` disabled -:func:`btst(x,n)` Return :const:`true` if state :var:`n` is enabled in :var:`x`, :const:`false` otherwise -:func:`fbit(n)` Return a flag with only state :var:`n` enabled -:func:`fnot(x)` Return the flag :var:`x` with all states flipped -:func:`fset(x,...)` Return the flag :var:`x` with disabled states flipped if enabled in any flag passed as argument -:func:`fcut(x,...)` Return the flag :var:`x` with enabled states flipped if disabled in any flag passed as argument -:func:`fclr(x,f)` Return the flag :var:`x` with enabled states flipped if enabled in :var:`f` -:func:`ftst(x,f)` Return :const:`true` if all states enabled in :var:`f` are enabled in :var:`x`, :const:`false` otherwise -:func:`fall(x)` Return :const:`true` if all states are enabled in :var:`x`, :const:`false` otherwise -:func:`fany(x)` Return :const:`true` if any state is enabled in :var:`x`, :const:`false` otherwise -=================== ==================================================== - -Special Functions -================= - -The module :mod:`MAD.gfunc` provides some useful functions when passed as argument or composed with other functions. - -====================== ==================================================== -Functions Return values -====================== ==================================================== -:func:`narg(...)` Return the number of arguments -:func:`ident(...)` Return all arguments unchanged, i.e. functional identity -:func:`fnil()` Return :const:`nil`, i.e. functional nil -:func:`ftrue()` Return :const:`true`, i.e. functional true -:func:`ffalse()` Return :const:`false`, i.e. functional false -:func:`fzero()` Return :const:`0`, i.e. functional zero -:func:`fone()` Return :const:`1`, i.e. functional one -:func:`first(a)` Return first argument and discard the others -:func:`second(a,b)` Return second argument and discard the others -:func:`third(a,b,c)` Return third argument and discard the others -:func:`swap(a,b)` Return first and second arguments swapped and discard the other arguments -:func:`swapv(a,b,...)` Return first and second arguments swapped followed by the other arguments -:func:`echo(...)` Return all arguments unchanged after echoing them on stdout -====================== ==================================================== - -C API -===== - -These functions are provided for performance reason and compliance with the C API of other modules. - -.. c:function:: int mad_num_sign (num_t x) - - Return an integer amongst :const:`{-1, 0, 1}` representing the sign of the :type:`number` :var:`x`. - -.. c:function:: int mad_num_sign1 (num_t x) - - Return an integer amongst :const:`{-1, 1}` representing the sign of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_fact (int n) - - Return the extended factorial the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_powi (num_t x, int n) - - Return the :type:`number` :var:`x` raised to the power of the :type:`integer` :var:`n` using a fast algorithm. - -.. c:function:: num_t mad_num_sinc (num_t x) - - Return the sine cardinal of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_sinhc (num_t x) - - Return the hyperbolic sine cardinal of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_asinc (num_t x) - - Return the arc sine cardinal of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_asinhc (num_t x) - - Return the hyperbolic arc sine cardinal of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_wf (num_t x, num_t relerr) - - Return the Faddeeva function of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_erf (num_t x, num_t relerr) - - Return the error function of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_erfc (num_t x, num_t relerr) - - Return the complementary error function of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_erfcx (num_t x, num_t relerr) - - Return the scaled complementary error function of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_erfi (num_t x, num_t relerr) - - Return the imaginary error function of the :type:`number` :var:`x`. - -.. c:function:: num_t mad_num_dawson (num_t x, num_t relerr) - - Return the Dawson integral for the :type:`number` :var:`x`. - -.. ------------------------------------------------------------ - -References -========== - -.. [ISOC99] ISO/IEC 9899:1999 Programming Languages - C. https://www.iso.org/standard/29237.html. - -.. rubric:: Footnotes - -.. [#f1] For *true* Functional Programming, see the module :mod:`MAD.lfun`, a binding of the `LuaFun `_ library adapted to the ecosystem of MAD-NG. -.. [#f2] Default: :expr:`v_ = 1`. -.. [#f3] Sign and sign1 functions take care of special cases like ±0, ±inf and ±NaN. -.. [#f4] Element-wise operators are not available directly in the programming language, here we use the Matlab-like notation for convenience. diff --git a/docs/source/functor.rst b/docs/source/functor.rst deleted file mode 100644 index d316d2475..000000000 --- a/docs/source/functor.rst +++ /dev/null @@ -1,64 +0,0 @@ -.. index:: - Functors - -******** -Functors -******** - -This chapter describes how to create, combine and use *functors* from the :mod:`MAD` environment. Functors are objects that behave like functions with :type:`callable` semantic, and also like readonly arrays with :type:`indexable` semantic, where the index is translated as a unique argument into the function call. They are mainly used by the object model to distinguish them from functions which are interpreted as deferred expressions and evaluated automatically on reading, and by the Survey and Track tracking codes to handle (user-defined) actions. - -Constructors -============ - -This module provides mostly constructors to create functors from functions, functors and any objects with :type:`callable` semantic, and combine them all together. - -.. function:: functor(f) - - Return a :type:`functor` that encapsulates the function (or any callable object) :var:`f`. Calling the returned functor is like calling :var:`f` itself with the same arguments. - -.. function:: compose(f, g) - - Return a :type:`functor` that encapsulates the composition of :var:`f` and :var:`g`. Calling the returned functor is like calling :math:`(f \circ g)(\dots)`. The operator :code:`f ^ g` is a shortcut for :func:`compose` if :var:`f` is a :type:`functor`. - -.. function:: chain(f, g) - - Return a :type:`functor` that encapsulates the calls chain of :var:`f` and :var:`g`. Calling the returned functor is like calling :math:`f(\dots) ; g(\dots)`. The operator :code:`f .. g` is a shortcut for :func:`chain` if :var:`f` is a :type:`functor`. - -.. function:: achain(f, g) - - Return a :type:`functor` that encapsulates the *AND*-ed calls chain of :var:`f` and :var:`g`. Calling the returned functor is like calling :math:`f(\dots) \land g(\dots)`. - -.. function:: ochain(f, g) - - Return a :type:`functor` that encapsulates the *OR*-ed calls chain of :var:`f` and :var:`g`. Calling the returned functor is like calling :math:`f(\dots) \lor g(\dots)`. - -.. function:: bind1st(f, a) - - Return a :type:`functor` that encapsulates :var:`f` and binds :var:`a` as its first argument. Calling the returned functor is like calling :math:`f(a,\dots)`. - -.. function:: bind2nd(f, b) - - Return a :type:`functor` that encapsulates :var:`f` and binds :var:`b` as its second argument. Calling the returned functor is like calling :math:`f(a,b,\dots)` where :var:`a` may or may not be provided. - -.. function:: bind3rd(f, c) - - Return a :type:`functor` that encapsulates :var:`f` and binds :var:`c` as its third argument. Calling the returned functor is like calling :math:`f(a,b,c,\dots)` where :var:`a` and :var:`b` may or may not be provided. - -.. function:: bind2st(f, a, b) - - Return a :type:`functor` that encapsulates :var:`f` and binds :var:`a` and :var:`b` as its two first arguments. Calling the returned functor is like calling :math:`f(a,b,\dots)`. - -.. function:: bind3st(f, a, b, c) - - Return a :type:`functor` that encapsulates :var:`f` and binds :var:`a`, :var:`b` and :var:`c` as its three first arguments. Calling the returned functor is like calling :math:`f(a,b,c,\dots)`. - -.. function:: bottom() - - Return a :type:`functor` that encapsulates the identity function :func:`ident` to define the *bottom* symbol of functors. Bottom is also available in the operator strings table :mod:`opstr` as :const:`"_|_"`. - -Functions -========= - -.. function:: is_functor(a) - - Return :const:`true` if :var:`a` is a :type:`functor`, :const:`false` otherwise. This function is only available from the module :mod:`MAD.typeid`. diff --git a/docs/source/geomap.rst b/docs/source/geomap.rst deleted file mode 100644 index 7606ede2f..000000000 --- a/docs/source/geomap.rst +++ /dev/null @@ -1,4 +0,0 @@ -.. _ch.phy.geomap: - -Geometric Maps -============== \ No newline at end of file diff --git a/docs/source/gphys.rst b/docs/source/gphys.rst deleted file mode 100644 index 2d9209edd..000000000 --- a/docs/source/gphys.rst +++ /dev/null @@ -1,4 +0,0 @@ -Generic Physics -=============== - -Just a link (never written) diff --git a/docs/source/index.rst b/docs/source/index.rst deleted file mode 100644 index db9b2b546..000000000 --- a/docs/source/index.rst +++ /dev/null @@ -1,44 +0,0 @@ -.. MAD-NG documentation master file, created by - sphinx-quickstart on Wed Aug 24 15:30:21 2022. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -Welcome to MAD-NG's Reference Manual! -===================================== - -.. toctree:: - :maxdepth: 3 - :caption: Part I: - - /part-I.rst - -.. toctree:: - :maxdepth: 3 - :caption: Part II: - - /part-II.rst - -.. toctree:: - :maxdepth: 3 - :caption: Part III: - - /part-III.rst - -.. toctree:: - :maxdepth: 3 - :caption: Part IV: - - /part-IV.rst - -.. toctree:: - :maxdepth: 3 - :caption: Part V: - - /part-V.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/source/integrators.rst b/docs/source/integrators.rst deleted file mode 100644 index 0ea2b8ca5..000000000 --- a/docs/source/integrators.rst +++ /dev/null @@ -1,4 +0,0 @@ -.. _ch.phy.intrg: - -Integrators -=========== diff --git a/docs/source/intro.rst b/docs/source/intro.rst deleted file mode 100644 index fa8a19c0d..000000000 --- a/docs/source/intro.rst +++ /dev/null @@ -1,202 +0,0 @@ -Introduction -============ -.. _ch.gen.intro: - -Presentation ------------- - -The Methodical Accelerator Design -- Next Generation application is an all-in-one standalone versatile tool for particle accelerator design, modeling, and optimization, and for beam dynamics and optics studies. Its general purpose scripting language is based on the simple yet powerful Lua programming language (with a few extensions) and embeds the state-of-art Just-In-Time compiler LuaJIT. Its physics is based on symplectic integration of differential maps made out of GTPSA (Generalized Truncated Power Series). The physics of the transport maps and the normal form analysis were both strongly inspired by the PTC/FPP library from E. Forest. MAD-NG development started in 2016 by the author as a side project of MAD-X, hence MAD-X users should quickly become familiar with its ecosystem, e.g. lattices definition. - -MAD-NG is free open-source software, distributed under the GNU General Public License v3. The source code, units tests, integration tests, and examples are all available on its Github `repository `_, including the `documentation `_ and its LaTeX source. For convenience, the binaries and few examples are also made available from the `releases repository `_ located on the AFS shared file system at CERN. - -Installation ------------- - -Download the binary corresponding to your platform from the `releases repository`_ and install it in a local directory. Update (or check) that the and install it in a local directory. Update (or check) that the ``PATH`` environment variable contains the path to your local directory or prefix environment variable contains the path to your local directory or prefix ``mad`` with this path to run it. Rename the application from with this path to run it. Rename the application from ``mad-arch-v.m.n`` to to ``mad`` and make it executable with the command ' and make it executable with the command '``chmod u+x mad``' on Unix systems or add the extension on Windows. - -.. code-block:: console - - $ ./mad - h - usage: ./mad [options]... [script [args]...]. - Available options are: - - e chunk Execute string 'chunk'. - - l name Require library 'name'. - - b ... Save or list bytecode. - - j cmd Perform JIT control command. - - O[opt] Control JIT optimizations. - - i Enter interactive mode after executing 'script'. - - q Do not show version information. - - M Do not load MAD environment. - - Mt[=num] Set initial MAD trace level to 'num'. - - MT[=num] Set initial MAD trace level to 'num' and location. - - E Ignore environment variables. - -- Stop handling options. - - Execute stdin and stop handling options. - -Releases version -"""""""""""""""" - -MAD-NG releases are tagged on the Github repository and use mangled binary names on the releases repository, i.e. ``mad-arch-v.m.n`` where: - -**arch** - is the platform architecture for binaries among ``linux``, ``macos`` and ``windows``. -**v** - is the **v**\ ersion number, ``0`` meaning beta-version under active development. -**m** - is the **m**\ ajor release number corresponding to features completeness. -**n** - is the mi\ **n**\ or release number corresponding to bug fixes. - - -Interactive Mode ----------------- - -To run MAD-NG in interactive mode, just typewrite its name on the Shell invite like any command-line tool. It is recommended to wrap MAD-NG with the `readline wrapper `_ in interactive mode for easier use and commands history: - -.. code-block:: console - - $ rlwrap ./mad - ____ __ ______ ______ | Methodical Accelerator Design - / \/ \ / _ \ / _ \ | release: 0.9.0 (OSX 64) - / __ / / /_/ / / /_/ / | support: http://cern.ch/mad - /__/ /_/ /__/ /_/ /_____ / | licence: GPL3 (C) CERN 2016+ - | started: 2020-08-01 20:13:51 - - -.. code-block:: - - > print "hello world!" - "hello world!" - -Here the application is assumed to be installed in the current directory '``.``' and the character '``>``' is the prompt waiting for user input in interactive mode. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt: - -.. code-block:: - - > print -- 1st level prompt, incomplete statement - >> "hello world!" -- 2nd level prompt, complete the statement - hello world! -- execute - -Typing the character '``=``' right after the 1st level prompt is equivalent to call the :literal:`print` function: - -.. code-block:: - - > = "hello world!" -- 1st level prompt followed by = - hello world! -- execute print "hello world!" - > = MAD.option.numfmt - % -.10g - - -To quit the application typewrite ``Crtl+D`` to send ``EOF`` (end-of-file) on the input, [#f2]_ ``Crtl+\`` to send the ``SIGQUIT`` (quit) signal, or ``Crtl+C`` to send the stronger ``SIGINT`` (interrupt) signal. If the application is stalled or looping for ever, typewriting a single ``Crtl+\`` or ``Crtl+C`` twice will stop it: - -.. code-block:: - - > while true do end -- loop forever, 1st Crtl+C doesn't stop it - pending interruption (*in*) VM! (next will exit) -- 2nd Crtl+C - interrupted! -- application stopped - - > while true do end -- loop forever, a single Crtl+\ does stop it - Quit: 3 -- Signal 3 caught, application stopped - - -In interactive mode, each line input is run in its own *chunk* [#f3]_, which also rules variables scopes. Hence ``local``, variables are not visible between chunks, i.e. input lines. The simple solutions are either to use global variables or to enclose local statements into the same chunk delimited by the ``do ... end`` keywords: - -.. code-block:: - - > local a = "hello" - > print(a.." world!") - stdin:1: attempt to concatenate global 'a' (a nil value) - stack traceback: - stdin:1: (*in*) main chunk - [C]: at 0x01000325c0 - - > do -- 1st level prompt, open the chunck - >> local a = "hello" -- 2nd level prompt, waiting for statement completion - >> print(a.." world!") -- same chunk, local 'a' is visible - >> end -- close and execute the chunk - hello world! - > print(a) -- here 'a' is an unset global variable - nil - > a = "hello" -- set global 'a' - > print(a.." world!") -- works but pollutes the global environment - hello world! - - -Batch Mode ----------- - -To run MAD-NG in batch mode, just run it in the shell with files as arguments on the command line: - -.. code-block:: console - - $ ./mad [mad options] myscript1.mad myscript2.mad ... - - -where the scripts contains programs written in the MAD-NG programming language (see :doc:`Scripting