Пример #1
0
    def add_frqs(self, index):
        """Add the spectrometer frequency info to the element.

        @param index:   The column index for the data.
        @type index:    int
        @return:        True if the frequency data exists, False otherwise.
        @rtype:         bool
        """

        # Append a column.
        self.element.InsertColumn(index, u("\u03C9H (MHz)"))

        # No data.
        if not hasattr(cdp, 'spectrum_ids'):
            return True
        if not hasattr(cdp, 'spectrometer_frq') or not len(cdp.spectrometer_frq):
            return True

        # Set the values.
        for i in range(len(cdp.spectrum_ids)):
            # No value.
            if cdp.spectrum_ids[i] not in cdp.spectrometer_frq:
                continue

            # Set the value (in MHz).
            self.element.SetStringItem(i, index, float_to_gui(cdp.spectrometer_frq[cdp.spectrum_ids[i]]/1e6))

        # Successful.
        return True
Пример #2
0
def gui_to_int(string):
    """Convert the GUI obtained string to an int.

    @param string:  The number in string form.
    @type string:   str or unicode
    @return:        The integer
    @rtype:         int or None
    """

    # No input.
    if string in ['', u(''), None]:
        return None

    # Already an int.
    if isinstance(string, int):
        return string

    # Convert.
    try:
        val = eval(string)
    except:
        val = None

    # Not an int!
    if not isinstance(val, int):
        return string

    # An int.
    return val
Пример #3
0
    def add_disp_point(self, index):
        """Add the dispersion point info to the element.

        This is either the CPMG pulse frequency or the spin-lock field strength.  Both share the same column.

        @param index:   The column index for the data.
        @type index:    int
        @return:        True if the data exists, False otherwise.
        @rtype:         bool
        """

        # Append a column.
        self.element.InsertColumn(index, u("\u03BDCPMG (Hz) or Spin-lock \u03BD1 (Hz)"))

        # No data.
        if not hasattr(cdp, 'spectrum_ids'):
            return True

        # Set the values.
        for i in range(len(cdp.spectrum_ids)):
            # Set the CPMG frequency.
            if hasattr(cdp, 'cpmg_frqs') and cdp.spectrum_ids[i] in cdp.cpmg_frqs.keys():
                self.element.SetStringItem(i, index, float_to_gui(cdp.cpmg_frqs[cdp.spectrum_ids[i]]))

            # Set the spin-lock field strength.
            if hasattr(cdp, 'spin_lock_nu1') and cdp.spectrum_ids[i] in cdp.spin_lock_nu1.keys():
                self.element.SetStringItem(i, index, float_to_gui(cdp.spin_lock_nu1[cdp.spectrum_ids[i]]))

        # Successful.
        return True
Пример #4
0
def gui_to_float(string):
    """Convert the GUI obtained string to an float.

    @param string:  The number in string form.
    @type string:   str or unicode
    @return:        The float
    @rtype:         float or None
    """

    # No input.
    if string in ['', u(''), None]:
        return None

    # Already a float.
    if isinstance(string, float):
        return string

    # Convert.
    val = eval(string)

    # An int.
    if isinstance(val, int):
        val = float(val)

    # Not a float!
    if not isinstance(val, float):
        return string

    # A float.
    return val
Пример #5
0
    def add_exp_type(self, index):
        """Add the experiment type info to the element.

        @param index:   The column index for the data.
        @type index:    int
        @return:        True if the data exists, False otherwise.
        @rtype:         bool
        """

        # Append a column.
        self.element.InsertColumn(index, u("Experiment type"))

        # No data.
        if not hasattr(cdp, 'spectrum_ids') or not hasattr(cdp, 'exp_type'):
            return True

        # Set the values.
        for i in range(len(cdp.spectrum_ids)):
            # No value.
            if cdp.spectrum_ids[i] not in cdp.exp_type.keys():
                continue

            # Set the value.
            self.element.SetStringItem(i, index, float_to_gui(cdp.exp_type[cdp.spectrum_ids[i]]))

        # Successful.
        return True
Пример #6
0
def gui_to_int_or_list(string):
    """Convert the GUI obtained string to a list.

    @param string:  The list in string form.
    @type string:   str or unicode
    @return:        The integer or list of integers.
    @rtype:         int or int list
    """

    # No value.
    if string in ['', u(''), None]:
        return None

    # Already an int or list.
    if isinstance(string, int) or isinstance(string, list):
        return string

    # Convert.
    try:
        val = eval(string)

    # Failure, so return the original value.
    except NameError:
        return string


    # Return the list.
    return val
Пример #7
0
def encode_basestring(s, _PY3=PY3, _q=u('"')):
    """Return a JSON representation of a Python string

    """
    if _PY3:
        if isinstance(s, binary_type):
            s = s.decode('utf-8')
    else:
        if isinstance(s, str) and HAS_UTF8.search(s) is not None:
            s = s.decode('utf-8')
    def replace(match):
        return ESCAPE_DCT[match.group(0)]
    return _q + ESCAPE.sub(replace, s) + _q
Пример #8
0
def gui_to_bool(string):
    """Convert the GUI obtained string to a bool.

    @param string:  The bool in string form.
    @type string:   str or unicode
    @return:        The bool.
    @rtype:         bool
    """

    # No value.
    if string in ['', u(''), None]:
        return None

    # Convert.
    return eval(string)
Пример #9
0
def encode_basestring(s, _PY3=PY3, _q=u('"')):
    """Return a JSON representation of a Python string

    """
    if _PY3:
        if isinstance(s, binary_type):
            s = s.decode('utf-8')
    else:
        if isinstance(s, str) and HAS_UTF8.search(s) is not None:
            s = s.decode('utf-8')

    def replace(match):
        return ESCAPE_DCT[match.group(0)]

    return _q + ESCAPE.sub(replace, s) + _q
Пример #10
0
def gui_to_str(string):
    """Convert the GUI obtained string to a string.

    @param string:  The number in string form.
    @type string:   str or unicode
    @return:        The string.
    @rtype:         str
    """

    # No value.
    if string in ['', u(''), None]:
        return None

    # Convert.
    return str(string)
Пример #11
0
def gui_to_list(string):
    """Convert the GUI obtained string to a list.

    @param string:  The list in string form.
    @type string:   str or unicode
    @return:        The list.
    @rtype:         list
    """

    # No value.
    if string in ['', u(''), None]:
        return []

    # Convert.
    val = eval(string)
    if not isinstance(val, list):
        val = [val]

    # Return the list.
    return val
Пример #12
0
def gui_to_tuple(string):
    """Convert the GUI obtained string to a tuple.

    @param string:  The list in string form.
    @type string:   str or unicode
    @return:        The list.
    @rtype:         list
    """

    # No value.
    if string in ['', u(''), None]:
        return ()

    # Convert.
    val = eval(string)
    if isinstance(val, list):
        val = tuple(val)
    elif not isinstance(val, tuple):
        val = (val,)

    # Return the list.
    return val
Пример #13
0
def gui_to_str_or_list(string):
    """Convert the GUI obtained string to a list.

    @param string:  The list in string form.
    @type string:   str or unicode
    @return:        The integer or list of integers.
    @rtype:         int or int list
    """

    # No value.
    if string in ['', u(''), None]:
        return None

    # Try converting to a list.
    try:
        val = eval(string)

    # Catch failures, and try as a string.
    except NameError:
        return str(string)

    # Return the list.
    return val
Пример #14
0
def gui_to_py(string):
    """Super function for converting the GUI string to a Python object.

    @param string:  The Python object in string form.
    @type string:   str or unicode
    @return:        The value.
    @rtype:         python object
    """

    # No value.
    if string in ['', u(''), None]:
        return None

    # Use an eval call to create a standard object.
    try:
        value = eval(string)

    # A string or sequence of strings.
    except:
        value = str(string)

    # Return the python type.
    return value
Пример #15
0
    def generate_popup_menu(self, id=None):
        """Create the popup menu.

        @keyword id:    The spectrum ID string for the row that was clicked on.
        @type id:       str
        @return:        The popup menu.
        @rtype:         list of dict of wxID, str, str, method
        """

        # The right click popup menu.
        popup_menus = [
            {
                'id': wx.NewId(),
                'text': "Set the &baseplane RMSD",
                'icon': fetch_icon(uf_info.get_uf('spectrum.baseplane_rmsd').gui_icon),
                'method': self.action_spectrum_baseplane_rmsd
            }, {
                'id': wx.NewId(),
                'text': "&Delete the peak intensities",
                'icon': fetch_icon(uf_info.get_uf('spectrum.delete').gui_icon),
                'method': self.action_spectrum_delete
            }, {
                'id': wx.NewId(),
                'text': "Set the number of integration &points",
                'icon': fetch_icon(uf_info.get_uf('spectrum.integration_points').gui_icon),
                'method': self.action_spectrum_integration_points
            }, {
                'id': wx.NewId(),
                'text': "Specify which spectra are &replicated",
                'icon': fetch_icon(uf_info.get_uf('spectrum.replicated').gui_icon),
                'method': self.action_spectrum_replicated
            }
        ]
        if self.relax_disp_flag:
            popup_menus.append({
                'id': wx.NewId(),
                'text': "Set the &experiment type",
                'icon': None,
                'method': self.action_relax_disp_exp_type
            })
        if self.relax_fit_flag:
            popup_menus.append({
                'id': wx.NewId(),
                'text': "Set the relaxation &time",
                'icon': fetch_icon(uf_info.get_uf('relax_fit.relax_time').gui_icon),
                'method': self.action_relax_fit_relax_time
            })
        if self.relax_disp_flag:
            popup_menus.append({
                'id': wx.NewId(),
                'text': "Set the relaxation &time",
                'icon': fetch_icon(uf_info.get_uf('relax_disp.relax_time').gui_icon),
                'method': self.action_relax_disp_relax_time
            })
            popup_menus.append({
                'id': wx.NewId(),
                'text': "Set the spectrometer &frequency",
                'icon': fetch_icon("relax.spectrometer"),
                'method': self.action_spectrometer_frq
            })
        if self.relax_disp_flag and is_r1rho_exp_type(id):
            popup_menus.append({
                'id': wx.NewId(),
                'text': u("Set the spin-&lock field strength \u03BD1"),
                'icon': fetch_icon("relax.relax_disp"),
                'method': self.action_relax_disp_spin_lock_field
            })
        if self.relax_disp_flag and is_cpmg_exp_type(id):
            popup_menus.append({
                'id': wx.NewId(),
                'text': u("Set the &CPMG pulse frequency \u03BDCPMG"),
                'icon': fetch_icon("relax.relax_disp"),
                'method': self.action_relax_disp_cpmg_frq
            })

        # Return the menu.
        return popup_menus
Пример #16
0
def py_scanstring(s, end, encoding=None, strict=True,
        _b=BACKSLASH, _m=STRINGCHUNK.match, _join=u('').join,
        _PY3=PY3, _maxunicode=sys.maxunicode):
    """Scan the string s for a JSON string. End is the index of the
    character in s after the quote that started the JSON string.
    Unescapes all valid JSON string escape sequences and raises ValueError
    on attempt to decode an invalid string. If strict is False then literal
    control characters are allowed in the string.

    Returns a tuple of the decoded string and the index of the character in s
    after the end quote."""
    if encoding is None:
        encoding = DEFAULT_ENCODING
    chunks = []
    _append = chunks.append
    begin = end - 1
    while 1:
        chunk = _m(s, end)
        if chunk is None:
            raise JSONDecodeError(
                "Unterminated string starting at", s, begin)
        end = chunk.end()
        content, terminator = chunk.groups()
        # Content is contains zero or more unescaped string characters
        if content:
            if not _PY3 and not isinstance(content, text_type):
                content = text_type(content, encoding)
            _append(content)
        # Terminator is the end of string, a literal control character,
        # or a backslash denoting that an escape sequence follows
        if terminator == '"':
            break
        elif terminator != '\\':
            if strict:
                msg = "Invalid control character %r at"
                raise JSONDecodeError(msg, s, end)
            else:
                _append(terminator)
                continue
        try:
            esc = s[end]
        except IndexError:
            raise JSONDecodeError(
                "Unterminated string starting at", s, begin)
        # If not a unicode escape sequence, must be in the lookup table
        if esc != 'u':
            try:
                char = _b[esc]
            except KeyError:
                msg = "Invalid \\X escape sequence %r"
                raise JSONDecodeError(msg, s, end)
            end += 1
        else:
            # Unicode escape sequence
            msg = "Invalid \\uXXXX escape sequence"
            esc = s[end + 1:end + 5]
            escX = esc[1:2]
            if len(esc) != 4 or escX == 'x' or escX == 'X':
                raise JSONDecodeError(msg, s, end - 1)
            try:
                uni = int(esc, 16)
            except ValueError:
                raise JSONDecodeError(msg, s, end - 1)
            end += 5
            # Check for surrogate pair on UCS-4 systems
            # Note that this will join high/low surrogate pairs
            # but will also pass unpaired surrogates through
            if (_maxunicode > 65535 and
                uni & 0xfc00 == 0xd800 and
                s[end:end + 2] == '\\u'):
                esc2 = s[end + 2:end + 6]
                escX = esc2[1:2]
                if len(esc2) == 4 and not (escX == 'x' or escX == 'X'):
                    try:
                        uni2 = int(esc2, 16)
                    except ValueError:
                        raise JSONDecodeError(msg, s, end)
                    if uni2 & 0xfc00 == 0xdc00:
                        uni = 0x10000 + (((uni - 0xd800) << 10) |
                                         (uni2 - 0xdc00))
                        end += 6
            char = unichr(uni)
        # Append the unescaped character
        _append(char)
    return _join(chunks), end
Пример #17
0
    if sys.byteorder != 'big':
        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf

NaN, PosInf, NegInf = _floatconstants()

_CONSTANTS = {
    '-Infinity': NegInf,
    'Infinity': PosInf,
    'NaN': NaN,
}

STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
BACKSLASH = {
    '"': u('"'), '\\': u('\u005c'), '/': u('/'),
    'b': u('\b'), 'f': u('\f'), 'n': u('\n'), 'r': u('\r'), 't': u('\t'),
}

DEFAULT_ENCODING = "utf-8"

def py_scanstring(s, end, encoding=None, strict=True,
        _b=BACKSLASH, _m=STRINGCHUNK.match, _join=u('').join,
        _PY3=PY3, _maxunicode=sys.maxunicode):
    """Scan the string s for a JSON string. End is the index of the
    character in s after the quote that started the JSON string.
    Unescapes all valid JSON string escape sequences and raises ValueError
    on attempt to decode an invalid string. If strict is False then literal
    control characters are allowed in the string.

    Returns a tuple of the decoded string and the index of the character in s
Пример #18
0
Some of these text elements are operating system dependent due to the incompleteness of the unicode fonts on certain systems.
"""

# relax module imports.
from compat import SYSTEM, u

# OS Flags.
win = False
mac = False
if SYSTEM == 'Windows':
    win = True
if SYSTEM == 'Darwin':
    mac = True

# Relaxation data GUI text elements.
r1 = u("R\u2081")
r2 = u("R\u2082")
if win:
    r1 = "R1"
    r2 = "R2"

# Model-free GUI text elements.
s2 = u("S\u00B2")
s2f = u("S\u00B2f")
s2s = u("S\u00B2s")
local_tm = u("local \u03C4\u2098")
tm = u("\u03C4\u2098")
te = u("\u03C4e")
tf = u("\u03C4f")
ts = u("\u03C4s")
rex = u("R\u2091\u2093")
Пример #19
0
def get(s, delimiter=''):
    """Return pinyin of string, the string must be unicode
    """
    return delimiter.join(pinyin_generator(u(s)))
Пример #20
0
def py_scanstring(s,
                  end,
                  encoding=None,
                  strict=True,
                  _b=BACKSLASH,
                  _m=STRINGCHUNK.match,
                  _join=u('').join,
                  _PY3=PY3,
                  _maxunicode=sys.maxunicode):
    """Scan the string s for a JSON string. End is the index of the
    character in s after the quote that started the JSON string.
    Unescapes all valid JSON string escape sequences and raises ValueError
    on attempt to decode an invalid string. If strict is False then literal
    control characters are allowed in the string.

    Returns a tuple of the decoded string and the index of the character in s
    after the end quote."""
    if encoding is None:
        encoding = DEFAULT_ENCODING
    chunks = []
    _append = chunks.append
    begin = end - 1
    while 1:
        chunk = _m(s, end)
        if chunk is None:
            raise JSONDecodeError("Unterminated string starting at", s, begin)
        end = chunk.end()
        content, terminator = chunk.groups()
        # Content is contains zero or more unescaped string characters
        if content:
            if not _PY3 and not isinstance(content, text_type):
                content = text_type(content, encoding)
            _append(content)
        # Terminator is the end of string, a literal control character,
        # or a backslash denoting that an escape sequence follows
        if terminator == '"':
            break
        elif terminator != '\\':
            if strict:
                msg = "Invalid control character %r at"
                raise JSONDecodeError(msg, s, end)
            else:
                _append(terminator)
                continue
        try:
            esc = s[end]
        except IndexError:
            raise JSONDecodeError("Unterminated string starting at", s, begin)
        # If not a unicode escape sequence, must be in the lookup table
        if esc != 'u':
            try:
                char = _b[esc]
            except KeyError:
                msg = "Invalid \\X escape sequence %r"
                raise JSONDecodeError(msg, s, end)
            end += 1
        else:
            # Unicode escape sequence
            msg = "Invalid \\uXXXX escape sequence"
            esc = s[end + 1:end + 5]
            escX = esc[1:2]
            if len(esc) != 4 or escX == 'x' or escX == 'X':
                raise JSONDecodeError(msg, s, end - 1)
            try:
                uni = int(esc, 16)
            except ValueError:
                raise JSONDecodeError(msg, s, end - 1)
            end += 5
            # Check for surrogate pair on UCS-4 systems
            # Note that this will join high/low surrogate pairs
            # but will also pass unpaired surrogates through
            if (_maxunicode > 65535 and uni & 0xfc00 == 0xd800
                    and s[end:end + 2] == '\\u'):
                esc2 = s[end + 2:end + 6]
                escX = esc2[1:2]
                if len(esc2) == 4 and not (escX == 'x' or escX == 'X'):
                    try:
                        uni2 = int(esc2, 16)
                    except ValueError:
                        raise JSONDecodeError(msg, s, end)
                    if uni2 & 0xfc00 == 0xdc00:
                        uni = 0x10000 + (((uni - 0xd800) << 10) |
                                         (uni2 - 0xdc00))
                        end += 6
            char = unichr(uni)
        # Append the unescaped character
        _append(char)
    return _join(chunks), end
Пример #21
0
        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf


NaN, PosInf, NegInf = _floatconstants()

_CONSTANTS = {
    '-Infinity': NegInf,
    'Infinity': PosInf,
    'NaN': NaN,
}

STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
BACKSLASH = {
    '"': u('"'),
    '\\': u('\u005c'),
    '/': u('/'),
    'b': u('\b'),
    'f': u('\f'),
    'n': u('\n'),
    'r': u('\r'),
    't': u('\t'),
}

DEFAULT_ENCODING = "utf-8"


def py_scanstring(s,
                  end,
                  encoding=None,
Пример #22
0
def get(s, delimiter=''):
    """Return pinyin of string, the string must be unicode
    """
    return delimiter.join(pinyin_generator(u(s)))