Exemplo n.º 1
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Second):
         return pf
     elif issubclass(other, AtomicUnitOfTime):
         return pf / 2.418884326502e-17
     elif issubclass(other, Minute):
         return pf / 60.0
     elif issubclass(other, Hour):
         return pf / 3600.0
     elif issubclass(other, Day):
         return pf / 86400.0
     elif issubclass(other, Week):
         return pf / 604800.0
     elif issubclass(other, Year):
         return pf / 31556925.445
     elif issubclass(other, Decade):
         return pf / (31556925.445 * 10)
     elif issubclass(other, Century):
         return pf / (31556925.445 * 100)
     elif issubclass(other, Millennium):
         return pf / (31556925.445 * 1000)
     else:  # pragma: no cover
         raise NotImplementedError("Conversion from units " +
                                   classname(cls) + " to units " +
                                   classname(other) +
                                   " is not implemented.")
Exemplo n.º 2
0
 def __set_check__(self, instance, value):
     if type_checking_enabled:
         if not isinstance(value, self.types):
             raise TypeError(
                 self.type_error_text.format(cls=classname(type(instance)),
                                             got=classname(type(value))))
     return True
Exemplo n.º 3
0
 def from_groups(self, groups, units):
     """ By default, just get the last group matched.
     """
     if len(groups) == 0:
         raise ValueNotAvailableError(
             "Cannot find value of {0} for molecule:\n"
             "{1}\nand details:\n{2} in output "
             "file (no matching groups were found, "
             "check regular expressions)".format(
                 type(self).__name__,
                 self.molecule,
                 self.details
         ))
     if sanity_checking_enabled and len(groups) != 1:
         raise ValueError(
             "expecting exactly one value for ScalarProperty"
              " '{0}', but got {1}".format(
                 classname(self.__class__), len(groups)
             ))
     if type_checking_enabled and not isinstance(groups[-1], basestring):
         raise TypeError("Got non-scalar last group: ('{1}') for ScalarProperty '{0}'".format(
                             classname(type(self)), "', '".join(groups)))
     ret_val = float(groups[-1]) * units
     self.value = ret_val.in_units(self.units)
     return ret_val
Exemplo n.º 4
0
def class_property_type(attr, cls, types, got):
    type_error_text = "Property '{0}'".format(attr)
    type_error_text += " in class '{0}' "
    if isinstance(types, Iterable):
        second_part = "must be an instance of one of the following: ('{0}');".format("', '".join(map(classname, types)))
    else:
        second_part = "must be an instance of '{0}'".format(classname(types))
    type_error_text += second_part + " (got '{1}')"
    type_error_text.format(classname(cls), classname(got))
Exemplo n.º 5
0
 def __init__(cls, *args, **dic):
     if not len(args) == 0:
         if len(args) == 3 and all(isinstance(a, t) for a, t in zip(args, [basestring, tuple, dict])):
             raise TypeError("'{0}' is not a real metaclass.  It merely inherits from 'type' to "
                             "make descriptors work properly.".format(classname(cls)))
         else:
             raise TypeError("{1} constructor takes exactly 1 argument, besides keyword arguments"
                             " ({0} given)".format(len(args) + 1, classname(cls)))
     for item in dic:
         setattr(cls, item, dic[item])
Exemplo n.º 6
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Coulomb):
         return pf
     elif issubclass(other, AtomicUnitOfElectricCharge):
         return pf / ElementaryCharge.in_units(Coulomb).value
     else:  # pragma: no cover
         raise NotImplementedError("Conversion from units " +
                                   classname(cls) + " to units " +
                                   classname(other) +
                                   " is not implemented.")
Exemplo n.º 7
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Radian):
         return pf * math.pi / 180.0
     elif issubclass(other, Degree):
         return pf
     else:  # pragma: no cover
         raise NotImplementedError("Conversion from units " +
                                   classname(cls) + " to units " +
                                   classname(other) +
                                   " is not implemented.")
Exemplo n.º 8
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Bohr):
         return pf / BohrRadius.value
     elif issubclass(other, Meter):
         return 1e-10 * pf
     elif issubclass(other, Angstrom):
         return pf
     else:  # pragma: no cover
         raise NotImplementedError("Conversion from units " +
                                   classname(cls) + " to units " +
                                   classname(other) +
                                   " is not implemented.")
Exemplo n.º 9
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Second):
         return pf
     elif issubclass(other, AtomicUnitOfTime):
         return pf / 2.418884326502e-17
     elif issubclass(other, Minute):
         return pf / 60.0
     elif issubclass(other, Hour):
         return pf / 3600.0
     elif issubclass(other, Day):
         return pf / 86400.0
     elif issubclass(other, Week):
         return pf / 604800.0
     elif issubclass(other, Year):
         return pf / 31556925.445
     elif issubclass(other, Decade):
         return pf / (31556925.445 * 10)
     elif issubclass(other, Century):
         return pf / (31556925.445 * 100)
     elif issubclass(other, Millennium):
         return pf / (31556925.445 * 1000)
     else: # pragma: no cover
         raise NotImplementedError("Conversion from units " + classname(cls) + " to units " + classname(other) + " is not implemented.")
Exemplo n.º 10
0
 def __new__(cls, argname, arg, *allowed_types, **kwargs):
     allowed = listify_args(allowed_types)
     my_caller = get_kwarg(kwargs, 'caller') or (caller() + '()')
     if len(allowed) == 1:
         return TypeError('Argument {0} to {1} must be {2} (got {3})'.format(
             argname,
             my_caller,
             classname(allowed[0]),
             type(arg).__name__
         ))
     else:
         return TypeError("Argument {0} to {1} must be one of ({2}) (got {3})".format(
             argname,
             my_caller,
             ', '.join(classname(a) for a in allowed),
             type(arg).__name__
         ))
Exemplo n.º 11
0
 def __set__(self, instance, value):
     if self.is_set_for_instance(instance):
         raise FrozenObjectError("Can't modify attribute '{0}' of instance {1} of type {2} once "
                                 "it has been set.".format(self._name, instance, classname(instance)))
     else:
         super(SetOnceAttribute, self).__set__(instance, value)
         if value is not None and value is not NotImplemented:
             setattr(instance, self._private_name + SetOnceAttribute.suffix, True)
Exemplo n.º 12
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Gram):
         return pf
     if issubclass(other, AtomicMassUnit):
         # NIST
         return pf / 1.660538921e-24
         # IUPAC
         #return pf / 1.6605402e-24
     elif issubclass(other, AtomicUnitOfMass):
         return pf / ElectronMass.in_units(Gram).value
     else:  # pragma: no cover
         raise NotImplementedError("Conversion from units " +
                                   classname(cls) + " to units " +
                                   classname(other) +
                                   " is not implemented.")
Exemplo n.º 13
0
 def __freeze__(self, instance):
     if self.required_before_freeze:
         if not self.is_set_for_instance(instance):
             raise FrozenObjectError(
                 "Attribute '{0}' of instance {1} of type {2} must be set before "
                 "freezing can occur.".format(self._name, instance,
                                              classname(instance)))
     setattr(instance, self._private_name + SetOnceAttribute.suffix, True)
Exemplo n.º 14
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Radian):
         return pf * math.pi / 180.0
     elif issubclass(other, Degree):
         return pf
     else: # pragma: no cover
         raise NotImplementedError("Conversion from units " + classname(cls) + " to units " + classname(other) + " is not implemented.")
Exemplo n.º 15
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Coulomb):
         return pf
     elif issubclass(other, AtomicUnitOfElectricCharge):
         return pf / ElementaryCharge.in_units(Coulomb).value
     else: # pragma: no cover
         raise NotImplementedError("Conversion from units " + classname(cls) + " to units " + classname(other) + " is not implemented.")
Exemplo n.º 16
0
 def __set__(self, instance, value):
     if getattr(instance, 'frozen', False):
         raise FrozenObjectError(
             "Can't modify attribute '{0}' of instance {1} of type {2} once the "
             "instance has been frozen.".format(self._name, instance,
                                                classname(instance)))
     elif self._setter_func is not None:
         self._setter_func(instance, value)
     else:
         setattr(instance, self._private_name, value)
Exemplo n.º 17
0
 def __set__(self, instance, value):
     if self.is_set_for_instance(instance):
         raise FrozenObjectError(
             "Can't modify attribute '{0}' of instance {1} of type {2} once "
             "it has been set.".format(self._name, instance,
                                       classname(instance)))
     else:
         super(SetOnceAttribute, self).__set__(instance, value)
         if value is not None and value is not NotImplemented:
             setattr(instance, self._private_name + SetOnceAttribute.suffix,
                     True)
Exemplo n.º 18
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Bohr):
         return pf / BohrRadius.value
     elif issubclass(other, Meter):
         return 1e-10 * pf
     elif issubclass(other, Angstrom):
         return pf
     else: # pragma: no cover
         raise NotImplementedError("Conversion from units " + classname(cls) + " to units " + classname(other) + " is not implemented.")
Exemplo n.º 19
0
 def from_groups(self, groups, units):
     """ By default, just get the last group matched.
     """
     if len(groups) == 0:
         raise ValueNotAvailableError(
             "Cannot find value of {0} for molecule:\n"
             "{1}\nand details:\n{2} in output "
             "file (no matching groups were found, "
             "check regular expressions)".format(
                 type(self).__name__, self.molecule, self.details))
     if sanity_checking_enabled and len(groups) != 1:
         raise ValueError("expecting exactly one value for ScalarProperty"
                          " '{0}', but got {1}".format(
                              classname(self.__class__), len(groups)))
     if type_checking_enabled and not isinstance(groups[-1], basestring):
         raise TypeError(
             "Got non-scalar last group: ('{1}') for ScalarProperty '{0}'".
             format(classname(type(self)), "', '".join(groups)))
     ret_val = float(groups[-1]) * units
     self.value = ret_val.in_units(self.units)
     return ret_val
Exemplo n.º 20
0
 def get_property(self, prop_class, details=None):
     ret_val = None
     if not self.completed:
         return None
     for p in self.properties:
         # TODO figure out which should be a superset of the other
         if MolecularProperty.is_same_property(p, prop_class) and (details is None or details.is_subset_of(p.details)):
             if not ret_val is None and not p.value == ret_val.value:
                 # TODO Raise a more helpful exception class
                 raise RuntimeError("Multiple conflicting values for property " + classname(prop_class))
             ret_val = p
     return ret_val
Exemplo n.º 21
0
 def valid_parsers(self):
     valid_parsers = {}
     for property in self.needed_properties:
         for parser in self.property_parsers:
             if parser.compatible_with_details(self.computation.details):
                 if MolecularProperty.is_same_property(property, parser.property):
                     valid_parsers[property.property_type] = parser
                     break
         if not any(MolecularProperty.is_same_property(property, p) for p in valid_parsers):
             raise ComputationUnavailableError("Could not find a valid parser for {0} in class {1} compatible with details: "
                              "\n{2}".format(property.property_type.__name__, classname(self.__class__), self.computation.details))
     return valid_parsers
Exemplo n.º 22
0
 def __attr_init__(self, types, strong, type_error_text):
     self.types = tuple(listify_args(types))
     if type_error_text is None:
         self.type_error_text = "Attribute '{name}'".format(name=self.__name__)
         self.type_error_text += " in class '{cls}' "
         if isinstance(types, Iterable):
             second_part = "must be an instance of one of the following: ('{types}');".format(types="', '".join(map(classname, types)))
         else:
             second_part = "must be an instance of '{types}'".format(types=classname(types))
         self.type_error_text += second_part + " (got '{got}')"
     else:
         self.type_error_text = type_error_text
     self.strong = strong
Exemplo n.º 23
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Joule):
         return pf
     elif issubclass(other, Hartree):
         return pf / 4.35974434e-18
     elif issubclass(other, Wavenumbers):
         return pf / (PlanckConstant.value *
                      SpeedOfLight.in_units(Centimeters / Second).value)
     elif issubclass(other, KiloCaloriePerMol):
         return pf * AvogadrosNumber / 1000.0 / 4.184
     elif issubclass(other, KiloJoulePerMol):
         return pf * AvogadrosNumber / 1000.0
     elif issubclass(other, Hertz):
         return pf / PlanckConstant.value
     elif issubclass(other, ElectronVolt):
         return pf / 1.602176565e-19
     else:  # pragma: no cover
         raise NotImplementedError("Conversion from units " +
                                   classname(cls) + " to units " +
                                   classname(other) +
                                   " is not implemented.")
Exemplo n.º 24
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Gram):
         return pf
     if issubclass(other, AtomicMassUnit):
         # NIST
         return pf / 1.660538921e-24
         # IUPAC
         #return pf / 1.6605402e-24
     elif issubclass(other, AtomicUnitOfMass):
         return pf / ElectronMass.in_units(Gram).value
     else: # pragma: no cover
         raise NotImplementedError("Conversion from units " + classname(cls) + " to units " + classname(other) + " is not implemented.")
Exemplo n.º 25
0
 def validate(self):
     prop_gen = None
     for gen in self.property_generators:
         if gen.property is All or all(
                 any(MolecularProperty.is_same_property(prop, p) for p in gen.property)
                     for prop in self.needed_properties):
             if gen.compatible_with_details(self.computation.details):
                 prop_gen = gen
                 break
     # and raise an error if we can't find a property generator that will work for us
     if prop_gen is None:
         raise ComputationUnavailableError("Could not find template file capable of generating an input to compute properties [{0}]"
                                           " with details given by {1}".format(
             ", ".join(classname(prop) for prop in self.needed_properties),
             self.computation.details))
     return True
Exemplo n.º 26
0
 def __attr_init__(self, types, strong, type_error_text):
     self.types = tuple(listify_args(types))
     if type_error_text is None:
         self.type_error_text = "Attribute '{name}'".format(
             name=self.__name__)
         self.type_error_text += " in class '{cls}' "
         if isinstance(types, Iterable):
             second_part = "must be an instance of one of the following: ('{types}');".format(
                 types="', '".join(map(classname, types)))
         else:
             second_part = "must be an instance of '{types}'".format(
                 types=classname(types))
         self.type_error_text += second_part + " (got '{got}')"
     else:
         self.type_error_text = type_error_text
     self.strong = strong
Exemplo n.º 27
0
 def to(cls, other):
     cls.genre_check(other)
     pf = cls.prefix_factor(other)
     if issubclass(other, Joule):
         return pf
     elif issubclass(other, Hartree):
         return pf / 4.35974434e-18
     elif issubclass(other, Wavenumbers):
         return pf / (PlanckConstant.value * SpeedOfLight.in_units(Centimeters/Second).value)
     elif issubclass(other, KiloCaloriePerMol):
         return pf * AvogadrosNumber / 1000.0 / 4.184
     elif issubclass(other, KiloJoulePerMol):
         return pf * AvogadrosNumber / 1000.0
     elif issubclass(other, Hertz):
         return pf / PlanckConstant.value
     else: # pragma: no cover
         raise NotImplementedError("Conversion from units " + classname(cls) + " to units " + classname(other) + " is not implemented.")
Exemplo n.º 28
0
 def valid_parsers(self):
     valid_parsers = {}
     for property in self.needed_properties:
         for parser in self.property_parsers:
             if parser.compatible_with_details(self.computation.details):
                 if MolecularProperty.is_same_property(
                         property, parser.property):
                     valid_parsers[property.property_type] = parser
                     break
         if not any(
                 MolecularProperty.is_same_property(property, p)
                 for p in valid_parsers):
             raise ComputationUnavailableError(
                 "Could not find a valid parser for {0} in class {1} compatible with details: "
                 "\n{2}".format(property.property_type.__name__,
                                classname(self.__class__),
                                self.computation.details))
     return valid_parsers
Exemplo n.º 29
0
    def __new__(cls, *args, **kwargs):
        """
        TODO Move this to class level documentation, since it doesn't show up in Sphinx
        Takes several different forms.  Given a number of arguments (possibly nested lists), a Tensor is created as
        expected.  *This is the only form in which arguments may be specified without keywords.*
        `Tensor` can also be initialized by giving a list of dimensions for the `shape` (aliased as `dimension`)
        keyword argument, with a possible default value keyword argument `default_val`.
        Unless otherwise specified via the `dtype` keyword argument, it is assumed that the input data should be cast
        as a `numpy.float64`.

        """
        # Pop off any special args or kwargs and store their values for later
        has_indices = False
        ret_val = None
        indices = None
        units = pop_kwarg(kwargs, 'units')
        name = kwargs.pop('name', None)
        #--------------------------------------------------------------------------------#
        # pop off any kwargs that the subclass's __init__ takes...
        subclass_kwargs = {}
        for supercls in cls.__mro__:
            if supercls is Tensor:
                break
            if hasattr(supercls, '__tensor_init__') and callable(supercls.__tensor_init__):
                if hasattr(supercls.__tensor_init__, 'getargspec'):
                    argspec = supercls.__tensor_init__.getargspec()
                else:
                    argspec = inspect.getargspec(supercls.__tensor_init__)
                for arg in argspec.args[1:]:
                    subclass_kwargs[arg] = kwargs.pop(arg, None)
        #--------------------------------------------------------------------------------#
        # Check for indices...
        indices_kwarg = kwargs.pop('indices', None)
        if indices_kwarg is None and len(args) == 1 and isinstance(args[0], basestring):
            args = list(args)
            indices_kwarg = args.pop(0)
            args = tuple(args)
        index_range_set = pop_multikwarg(kwargs, 'index_range_set', 'in_set', 'set')
        if indices_kwarg is not None:
            has_indices = True
            indices = EinsumTensor.split_indices(indices_kwarg)
            if index_range_set is None:
                index_range_set = IndexRange.global_index_range_set
            shape = []
            for idx in indices:
                if idx not in index_range_set.known_ranges:
                    raise IndexError("unknown index '" + idx + "'")
                shape.append(index_range_set.known_ranges[idx].size)
            shape = tuple(shape)
            if "shape" in kwargs:
                kwshape = kwargs.pop('shape')
                if shape != kwshape:
                    raise TypeError("inconsistent shape:  indices '{}' indicate a shape of {}, but"
                                    " the keyword 'shape' was given with the shape {}".format(
                        ",".join(indices), shape, kwshape
                    ))
            kwargs['shape'] = shape
        #--------------------------------------------------------------------------------#
        # Now create a numpy.ndarray object...
        def_val = pop_kwarg(kwargs, 'default_val', 'default_value', 'default') or 0.0
        # Set the default data type to float, unless the user specifies
        dtype = get_kwarg(kwargs, 'dtype') or float
        if not callable(dtype) and grendel.show_warnings:
            warn("dtype given to {0} constructor is not Callable and thus cannot be used for casting." \
                 "  It is better to use callable types for dtype if possible; e.g. numpy.float64 instead" \
                 "of numpy.dtype('float64')".format(classname(cls)))
        kwargs['dtype'] = dtype
        # Typecast the default value
        if callable(dtype):
            def_val = dtype(def_val)
        # See if we have a shape...
        shape = pop_kwarg(kwargs, 'shape', 'dimension')
        # See if we have data...
        # This allows us to support the form Tensor(1, 2, 3, 4)
        if len(args) == 1 and isinstance(args[0], np.ndarray):
            data = args[0]
        else:
            data = listify_args(*args)
        if 'data' in kwargs:
            if data:
                raise TypeError("`data` may be specified as a keyword argument or as " \
                                "the regular arguments to {0} constructor, but not both.".format(classname(cls)))
            else:
                data = pop_kwarg('data')
        if shape and not isinstance(data, np.ndarray):
            has_content = False
            if len(args) != 0:
                has_content = True
            if not has_content:
                if def_val == 0.0:
                    try:
                        ret_val = np.zeros(shape=shape, **kwargs)
                    except:
                        raise
                else:
                    ret_val = (np.ones(shape=shape, **kwargs) * def_val)
            else:
                if grendel.sanity_checking_enabled:
                    # Check data length
                    tmp = np.array(data)
                    needed_data_size = 1
                    for dim in shape: needed_data_size *= dim
                    try:
                        tmp.reshape((needed_data_size,))
                    except ValueError:
                        raise ValueError("Data provided to {0} constructor is incompatible with the shape {1}".format(classname(cls), shape))
                    # Check data type
                ret_val = np.array(data, **kwargs).reshape(shape)
        else:
            # Just pass on the data and any surviving kwargs
            try:
                if isinstance(data, np.ndarray) and (
                        len(kwargs) == 0
                     or (len(kwargs) == 1 and 'dtype' in kwargs and kwargs['dtype'] == data.dtype)
                ):
                    # Just do a view
                    ret_val = data.view(cls)
                else:
                    # Otherwise, we need to call the numpy "constructor" (actually a factory function) of ndarray
                    ret_val = np.array(data, **kwargs)
            except:
                # debugging breakpoint hook
                raise
            if shape and ret_val.shape != shape:
                raise ValueError("Shape mismatch: data shape {0} does not match specified shape {1}".format(
                    data.shape, shape
                ))
        #--------------------------------------------------------------------------------#
        # View-cast the ret_val to the class in question, but only if we haven't already
        if not isinstance(ret_val, cls):
            ret_val = ret_val.view(cls)
        # Now assign stuff from any special args...
        if has_indices:
            ret_val.indices = indices
            ret_val.index_range_set = index_range_set
        else:
            ret_val.indices = None
        ret_val.units = units
        ret_val.name = name
        if name is None:
            ret_val.name = "(unnamed tensor)"
        # pass the remaining kwargs to the initializer...
        ret_val.__tensor_init__(**subclass_kwargs)
        return ret_val
Exemplo n.º 30
0
 def get_kwarg(arg, cls, subclass=False):
     gotten = pop_kwarg(kwargs, arg)
     if not subclass:
         if gotten is not None and not isinstance(gotten, cls):
             if not isinstance(cls, tuple):
                 raise TypeError("#{0} argument given to Computation() "\
                                 "must be an instance of the #{1} class.".format(arg, classname(cls)))
             else:
                 raise TypeError("#{0} argument given to Computation() "\
                                 "must be one of (#{1}) .".format(arg, ', '.join(classname(cl) for cl in cls)))
     else:
         if gotten is not None and not issubclass(gotten, cls):
             if not isinstance(cls, tuple):
                 raise TypeError("#{0} argument given to Computation() "\
                                 "must be an subclass of the #{1} class.".format(arg, classname(cls)))
             else:
                 raise TypeError("#{0} argument given to Computation() "\
                                 "must be subclass of one of (#{1}) .".format(arg, ', '.join(classname(cl) for cl in cls)))
     return gotten
Exemplo n.º 31
0
 def fail_if_frozen(self):
     if self.frozen:
         raise FrozenObjectError("Can't call method {0}() on instance {1} of {2} once "
                                             "it has been frozen.".format(caller(), self, classname(self)))
Exemplo n.º 32
0
 def __set_check__(self, instance, value):
     if type_checking_enabled:
         if not isinstance(value, self.types):
             raise TypeError(self.type_error_text.format(cls=classname(type(instance)), got=classname(type(value))))
     return True
Exemplo n.º 33
0
 def __mul__(self, other):
     if not isinstance(other, SymmetryOperation):
         raise TypeError("Invalid multiplication of " + classname(self) + " by " + classname(other))
     return super(Reflection, self).__mul__(other)
Exemplo n.º 34
0
 def __new__(mcs, *args, **kwargs):
     ret_val = type.__new__(mcs, classname(mcs), (), {})
     mcs.__init__(ret_val, *args, **kwargs)
     return ret_val
Exemplo n.º 35
0
def test_classname():
    assert classname(object) == "object"
    assert classname(Tensor) == "Tensor"
    assert classname("Torsion") == "Torsion"
    assert classname(Vector(1,2,3)) == "Vector"
Exemplo n.º 36
0
 def __lt__(self, other):
     """ Determines a sort order based on Cotton ordering (or as close as possible to it...)
     (i.e. the ordering used by Cotton in his character tables)
     Note:  Cotton isn't really that consistent with his ordering, particularly for larger point groups.  This
     represents my best guess, basically just to get something consistant out on the table.
     """
     if self is other:
         return False
     if not isinstance(other, SymmetryOperation):
         raise TypeError("Comparison of SymmetryOperation with " +
                         classname(other) + " is not allowed.")
     elif not self.point_group is other.point_group:
         raise ValueError(
             "Cannot compare operations from different point groups.")
     if isinstance(self, g.IdentityOperation):
         return True
     if isinstance(other, g.IdentityOperation):
         return False
     elif isinstance(self, g.Rotation):
         if not isinstance(other, g.Rotation):
             return True
         elif (self.n, self.n - self.exponent) != (other.n, other.n -
                                                   other.exponent):
             # Reverse ordering by order, forward ordering by exponent
             return (self.n, self.n - self.exponent) > (other.n, other.n -
                                                        other.exponent)
         # Then put in the order z, y, x
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0, 0, 1)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0, 0, 1)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0, 1, 0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0, 1, 0)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(1, 0, 0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(1, 0, 0)):
             return False
         # Finally, order by proximity of axis to the z-axis (not an official part of Cotton ordering, but doesn't come up too often
         else:
             return (Vector(0, 0, 1) - self.axis).magnitude() < (
                 Vector(0, 0, 1) - other.axis).magnitude()
     elif isinstance(other, g.Rotation):
         return False
     elif isinstance(self, g.Inversion):
         return True
     elif isinstance(other, g.Inversion):
         return False
     elif isinstance(self, g.ImproperRotation):
         if not isinstance(other, g.ImproperRotation):
             return True
         elif (self.n, self.n - self.exponent) != (other.n, other.n -
                                                   other.exponent):
             # Reverse ordering by order, forward ordering by exponent
             return (self.n, self.n - self.exponent) > (other.n, other.n -
                                                        other.exponent)
         # Then put in the order z, y, x
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0, 0, 1)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0, 0, 1)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0, 1, 0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0, 1, 0)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(1, 0, 0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(1, 0, 0)):
             return False
         # Finally, order by proximity of axis to the z-axis (not an official part of Cotton ordering, but doesn't come up too often
         else:
             return (Vector(0, 0, 1) - self.axis).magnitude() < (
                 Vector(0, 0, 1) - other.axis).magnitude()
     elif isinstance(other, g.ImproperRotation):
         return False
     else:  # Both are Reflections
         if self.is_principal_reflection():
             return True
         elif other.is_principal_reflection():
             return False
         elif self.is_dihedral():
             if not other.is_dihedral():
                 return True
             # Otherwise same axis ordering as rotations
             elif SymmetryOperation.is_same_axis(self.axis, Vector(0, 0,
                                                                   1)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis,
                                                 Vector(0, 0, 1)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(0, 1,
                                                                   0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis,
                                                 Vector(0, 1, 0)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(1, 0,
                                                                   0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis,
                                                 Vector(1, 0, 0)):
                 return False
             else:
                 return (Vector(0, 0, 1) - self.axis).magnitude() < (
                     Vector(0, 0, 1) - other.axis).magnitude()
         elif other.is_dihedral():
             return False
         else:  # Both are sigma_v's
             # Same axis ordering as rotations
             if SymmetryOperation.is_same_axis(self.axis, Vector(0, 0, 1)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis,
                                                 Vector(0, 0, 1)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(0, 1,
                                                                   0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis,
                                                 Vector(0, 1, 0)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(1, 0,
                                                                   0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis,
                                                 Vector(1, 0, 0)):
                 return False
             else:
                 return (Vector(0, 0, 1) - self.axis).magnitude() < (
                     Vector(0, 0, 1) - other.axis).magnitude()
Exemplo n.º 37
0
 def __eq__(self, other):
     if not isinstance(other, SymmetryOperation):
         raise TypeError("Equality comparison of SymmetryOperation to " +
                         classname(other) + " is not allowed.")
     diff = self.matrix - other.matrix
     return diff.norm() < self.same_operation_tolerance
Exemplo n.º 38
0
 def __eq__(self, other):
     if not isinstance(other, SymmetryOperation):
         raise TypeError("Equality comparison of SymmetryOperation to " + classname(other) + " is not allowed.")
     diff = self.matrix - other.matrix
     return diff.norm() < self.same_operation_tolerance
Exemplo n.º 39
0
 def __lt__(self, other):
     """ Determines a sort order based on Cotton ordering (or as close as possible to it...)
     (i.e. the ordering used by Cotton in his character tables)
     Note:  Cotton isn't really that consistent with his ordering, particularly for larger point groups.  This
     represents my best guess, basically just to get something consistant out on the table.
     """
     if self is other:
         return False
     if not isinstance(other, SymmetryOperation):
         raise TypeError("Comparison of SymmetryOperation with " + classname(other) + " is not allowed.")
     elif not self.point_group is other.point_group:
         raise ValueError("Cannot compare operations from different point groups.")
     if isinstance(self, g.IdentityOperation):
         return True
     if isinstance(other, g.IdentityOperation):
         return False
     elif isinstance(self, g.Rotation):
         if not isinstance(other, g.Rotation):
             return True
         elif (self.n, self.n - self.exponent) != (other.n, other.n - other.exponent):
             # Reverse ordering by order, forward ordering by exponent
             return (self.n, self.n - self.exponent) > (other.n, other.n - other.exponent)
         # Then put in the order z, y, x
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0,0,1)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0,0,1)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0,1,0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0,1,0)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(1,0,0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(1,0,0)):
             return False
         # Finally, order by proximity of axis to the z-axis (not an official part of Cotton ordering, but doesn't come up too often
         else:
             return (Vector(0,0,1) - self.axis).magnitude() < (Vector(0,0,1) - other.axis).magnitude()
     elif isinstance(other, g.Rotation):
         return False
     elif isinstance(self, g.Inversion):
         return True
     elif isinstance(other, g.Inversion):
         return False
     elif isinstance(self, g.ImproperRotation):
         if not isinstance(other, g.ImproperRotation):
             return True
         elif (self.n, self.n - self.exponent) != (other.n, other.n - other.exponent):
             # Reverse ordering by order, forward ordering by exponent
             return (self.n, self.n - self.exponent) > (other.n, other.n - other.exponent)
         # Then put in the order z, y, x
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0,0,1)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0,0,1)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(0,1,0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(0,1,0)):
             return False
         elif SymmetryOperation.is_same_axis(self.axis, Vector(1,0,0)):
             return True
         elif SymmetryOperation.is_same_axis(other.axis, Vector(1,0,0)):
             return False
         # Finally, order by proximity of axis to the z-axis (not an official part of Cotton ordering, but doesn't come up too often
         else:
             return (Vector(0,0,1) - self.axis).magnitude() < (Vector(0,0,1) - other.axis).magnitude()
     elif isinstance(other, g.ImproperRotation):
         return False
     else:  # Both are Reflections
         if self.is_principal_reflection():
             return True
         elif other.is_principal_reflection():
             return False
         elif self.is_dihedral():
             if not other.is_dihedral():
                 return True
             # Otherwise same axis ordering as rotations
             elif SymmetryOperation.is_same_axis(self.axis, Vector(0,0,1)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis, Vector(0,0,1)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(0,1,0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis, Vector(0,1,0)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(1,0,0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis, Vector(1,0,0)):
                 return False
             else:
                 return (Vector(0,0,1) - self.axis).magnitude() < (Vector(0,0,1) - other.axis).magnitude()
         elif other.is_dihedral():
             return False
         else: # Both are sigma_v's
             # Same axis ordering as rotations
             if SymmetryOperation.is_same_axis(self.axis, Vector(0,0,1)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis, Vector(0,0,1)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(0,1,0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis, Vector(0,1,0)):
                 return False
             elif SymmetryOperation.is_same_axis(self.axis, Vector(1,0,0)):
                 return True
             elif SymmetryOperation.is_same_axis(other.axis, Vector(1,0,0)):
                 return False
             else:
                 return (Vector(0,0,1) - self.axis).magnitude() < (Vector(0,0,1) - other.axis).magnitude()
Exemplo n.º 40
0
 def __mul__(self, other):
     if not isinstance(other, SymmetryOperation):
         raise TypeError("Invalid multiplication of " + classname(self) +
                         " by " + classname(other))
     return super(Reflection, self).__mul__(other)
Exemplo n.º 41
0
def freeze(obj):
    if type_checking_enabled and not isinstance(obj, Freezable):
        raise TypeError("Cannot freeze unfreezable object of type {0}".format(
            classname(obj)))
    else:
        obj.freeze()
Exemplo n.º 42
0
 def __repr__(cls):
     return classname(super(Unit, cls).__repr__())
Exemplo n.º 43
0
 def fail_if_frozen(self):
     if self.frozen:
         raise FrozenObjectError(
             "Can't call method {0}() on instance {1} of {2} once "
             "it has been frozen.".format(caller(), self, classname(self)))
Exemplo n.º 44
0
 def __init__(self, unit1):
     """
     """
     name1 = unit1.name if isinstance(unit1, CompositeUnit) else classname(unit1)
     message = "Unit " + name1 + " is not a Unit that Grendel knows about."
     super(UnknownUnitError, self).__init__(message)
Exemplo n.º 45
0
 def __init__(self,
              indices,
              begin_index_or_size_or_slices,
              end_index=None,
              name=None,
              parent=None,
              index_range_set=None):
     self.indices, self.sub_indices = EinsumTensor.split_indices(
         indices, include_sub=True)
     if self.indices != self.sub_indices:
         raise ValueError(
             "can't include indices with sub-indices (such as '{}') in"
             " IndexRange declaration.".format([
                 self.indices[i] + "_" + self.sub_indices[i]
                 for i in xrange(len(self.indices))
                 if self.indices[i] != self.sub_indices[i]
             ][0]))
     self.subranges = []
     if parent:
         self.parent = parent
     if index_range_set is None:
         if self.parent is not None:
             self.index_range_set = self.parent.index_range_set
         else:
             self.index_range_set = IndexRange.global_index_range_set
     else:
         self.index_range_set = index_range_set
     self.name = name
     self._begin_is_ellipsis = False
     self._end_is_ellipsis = False
     self._parent = None
     if isinstance(begin_index_or_size_or_slices, int):
         if end_index is not None:
             if end_index is Ellipsis:
                 self._end_is_ellipsis = True
                 self.slice = slice(begin_index_or_size_or_slices, -1)
             else:
                 self.slice = slice(begin_index_or_size_or_slices,
                                    end_index)
         else:
             self.slice = slice(0, begin_index_or_size_or_slices)
     elif isinstance(begin_index_or_size_or_slices, slice):
         self.slice = begin_index_or_size_or_slices
     elif begin_index_or_size_or_slices is Ellipsis:
         self._begin_is_ellipsis = True
         if isinstance(end_index, int):
             self.slice = slice(-1, end_index)
         else:
             raise TypeError(
                 "Unsupport type for third argument to IndexRange constructor of type {0}"
                 .format(classname(end_index)))
     else:
         raise TypeError(
             "Unsupport type for third argument to IndexRange constructor of type {0}"
             .format(classname(begin_index_or_size_or_slices)))
     for idx in self.indices:
         if idx in self.index_range_set.known_ranges:
             raise IndexError(
                 u"Index {0} is already part of index range {1}.".format(
                     idx, self.index_range_set.known_ranges[idx]))
         self.index_range_set[idx] = self
Exemplo n.º 46
0
 def __init__(self, unit1, unit2):
     """
     """
     name1 = unit1.name if isinstance(unit1, CompositeUnit) else '<unitless>' if unit1 is None else classname(unit1)
     name2 = unit2.name if isinstance(unit2, CompositeUnit) else '<unitless>' if unit2 is None else classname(unit2)
     message = "Cannot convert from units " + name1 + " to units " + name2 + "."
     super(IncompatibleUnitsError, self).__init__(message)
Exemplo n.º 47
0
def forwardable(cls):
    """ Class decorator that allows for the definition of delegators (in conjunction with `def_delegators`),
    just like the Forwardable module in Ruby.  *Note that this pattern does not work for nested classes*

    :Examples:

    >>> class NameContainer(object):
    ...     name = ""
    ...     def __init__(self, name):
    ...         self.name = name
    ...
    >>> @forwardable
    ... class AppendOnlyList(object):
    ...     list = []
    ...     def_delegators('list', 'append')
    ...     # Attributes can also be delegated:
    ...     name_container = None
    ...     def_delegators('name_container', 'name')
    ...     def __init__(self, name):
    ...         self.list = []
    ...         self.name_container = NameContainer(name)
    ...     # Double-underscore methods can't be delegated.  Instead, do something like this:
    ...     def __repr__(self):
    ...         return self.list.__repr__()
    ...
    >>> foo = AppendOnlyList("foobar")
    >>> foo.append('a')
    >>> foo.append(2)
    >>> foo.append('hello')
    >>> foo
    ['a', 2, 'hello']
    >>> foo.name
    'foobar'

    """
    if 'delegates' not in forwardable.__dict__:
        return cls
    for attr in forwardable.__dict__['delegates']:
        symbols = forwardable.__dict__['delegates'][attr]
        for symb in symbols:
            if hasattr(cls, symb):
                raise ValueError("Tried to define delegator of '{0}' to '{1}', but '{0}' is already defined in" \
                                 " class {2}.".format(symb, attr, classname(cls)))
            elif (symb[0], symb[1], symb[-2], symb[-1]) == ('_', '_', '_', '_'):
                raise ValueError("You are not allowed to delegate double-underscored methods.  Do these by hand, "
                                 "keeping in mind how Python actually accesses the particular double-underscored "
                                 "method you're trying to create.")
            else:
                class _wrapped_descriptor(object):
                    attr_name = None
                    symb_name = None
                    def __init__(self, in_attr, in_symb):
                        self.attr_name = in_attr
                        self.symb_name = in_symb
                    def __get__(self, obj, type=None):
                        return getattr(getattr(obj, self.attr_name), self.symb_name)
                _wrapped = _wrapped_descriptor(attr, symb)
                _wrapped.__name__ = attr
                _wrapped.__doc__ = """Delegated to `self.{0}`.""".format(attr)
                setattr(cls, symb, _wrapped)
    # Now clear the delegates for the next use.
    forwardable.__dict__['delegates'] = {}
    return cls
Exemplo n.º 48
0
 def __new__(cls, **kwargs):
     """
     """
     def get_kwarg(arg, cls, subclass=False):
         gotten = pop_kwarg(kwargs, arg)
         if not subclass:
             if gotten is not None and not isinstance(gotten, cls):
                 if not isinstance(cls, tuple):
                     raise TypeError("#{0} argument given to Computation() "\
                                     "must be an instance of the #{1} class.".format(arg, classname(cls)))
                 else:
                     raise TypeError("#{0} argument given to Computation() "\
                                     "must be one of (#{1}) .".format(arg, ', '.join(classname(cl) for cl in cls)))
         else:
             if gotten is not None and not issubclass(gotten, cls):
                 if not isinstance(cls, tuple):
                     raise TypeError("#{0} argument given to Computation() "\
                                     "must be an subclass of the #{1} class.".format(arg, classname(cls)))
                 else:
                     raise TypeError("#{0} argument given to Computation() "\
                                     "must be subclass of one of (#{1}) .".format(arg, ', '.join(classname(cl) for cl in cls)))
         return gotten
     #--------------------------------------------------------------------------------#
     # Handle molecule, make a ResultGetter
     molecule = get_kwarg('molecule', Molecule)
     res_getter = get_kwarg('result_getter', ComputationResultGetter)
     if res_getter is None:
         res_getter = ComputationResultGetter(**kwargs)
         molecule.result_getters.append(res_getter)
     #--------------------------------------------------------------------------------#
     # Now see what package we're using
     package = get_kwarg('package', (basestring, PackageInterface))
     comp_class = cls
     interface = None
     if isinstance(package, PackageInterface):
         interface = package
     elif isinstance(package, basestring):
         interface = PackageInterface.load_package(
                         package,
                         input_generator=get_kwarg('input_generator', InputGenerator, True),
                         runner=get_kwarg('runner', Runner, True),
                         output_parser=get_kwarg('output_parser', OutputParser, True),
                         details_class=get_kwarg('details_class', ComputationDetails, True),
                         computation_class=get_kwarg('computation_class', cls, True)
                     )
     if interface.computation_class is not None:
         comp_class = cls
     ret_val = object.__new__(comp_class)
     #--------------------------------------------------------------------------------#
     ret_val.molecule = molecule
     res_getter.add_computation(ret_val)
     ret_val.input_generator = interface.input_generator(ret_val)
     ret_val.output_parser = interface.output_parser(ret_val)
     #TODO accept option for directory to put input/output files in
     #TODO accept option for input/output filenames
     #TODO support for runners that don't follow the input/output pattern
     ret_val.runner = interface.runner(input_file='input.dat', output_file='output.dat')
     #--------------------------------------------------------------------------------#
     ret_val.details = get_kwarg('details', interface.details_class)
     ret_val.properties = pop_kwarg(kwargs, 'property')
     if isinstance(ret_val.properties, Iterable):
         ret_val.properties = list(ret_val.properties)
     else:
         ret_val.properties = [ret_val.properties]
     if not all(issubclass(prop, MolecularProperty) or isinstance(prop, MolecularProperty) for prop in ret_val.properties):
         raise TypeError("property argument given to Computation() must be a list of MolecularProperty subclasses or instances.".format(classname(cls)))
     fixed_properties = []
     for prop in ret_val.properties:
         if isinstance(prop, MolecularProperty):
             fixed_properties.append(prop)
             prop.details = ret_val.details
         elif issubclass(prop, MolecularProperty):
             fixed_properties.append(prop(molecule=ret_val.molecule, details=ret_val.details))
     ret_val.properties = fixed_properties
     #--------------------------------------------------------------------------------#
     # Get input_filename and output_filename, if specified.  Make sure that neither
     #   is a path.
     # first get input_filename
     input_filename = pop_kwarg(kwargs, 'input_filename')
     if input_filename:
         if os.path.split(input_filename)[0] != '':
             raise ValueError("File name '{0}' given for argument 'input_filename' of Computation constructor "
                              "must be a single file, not a path.  Use the 'directory' argument to specify "
                              "a directory.".format(input_filename))
         ret_val.runner.input_file = input_filename
     else:
         ret_val.runner.input_file = Runner.default_input_filename
     #----------------------------------------#
     # now get output_filename
     output_filename = pop_kwarg(kwargs, 'output_filename')
     if output_filename:
         if os.path.split(output_filename)[0] != '':
             raise ValueError("File name '{0}' given for argument 'output_filename' of Computation constructor "
                              "must be a single file, not a path.  Use the 'directory' argument to specify "
                              "a directory.".format(output_filename))
         ret_val.runner.output_file = output_filename
     else:
         ret_val.runner.output_file = Runner.default_output_filename
     #--------------------------------------------------------------------------------#
     # Find out the desired directory and make new ones if necessary and allowed.
     ret_val.directory = pop_kwarg(kwargs, 'directory')
     used_template = False
     if ret_val.directory is not None:
         ret_val.directory = full_path(ret_val.directory)
     elif cls.directory_template is not None:
         ret_val.directory = cls.directory_template
         used_template = True
     else:
         ret_val.directory = full_path(os.curdir)
     #----------------------------------------#
     # Do mako-template style replacement, if the user has mako
     try:
         from mako.template import Template
         from mako import exceptions
         # Start with some obvious standard things to add...
         variables = dict(
             mol = ret_val.molecule, molecule = ret_val.molecule,
             calc = ret_val, calculation = ret_val,
             rg = res_getter, result_getter = res_getter,
             details = ret_val.details
         )
         # Get all of the known details, as strings
         det_strs = dict()
         for k, v in ret_val.details._known_details.items():
             det_strs[str(k)] = str(v)
             det_strs[str(k).lower()] = str(v)
             det_strs[str(k).upper()] = str(v)
             if k in Computation.attribute_aliases:
                 for alias in Computation.attribute_aliases[k]:
                     alias = make_safe_identifier(alias)
                     det_strs[str(alias)] = str(v)
                     det_strs[str(alias).lower()] = str(v)
                     det_strs[str(alias).upper()] = str(v)
         variables.update(det_strs)
         # Get any additional keywords specified by the user (advanced feature)
         additional = kwargs.pop('directory_creation_vars', dict())
         variables.update(additional)
         # Now run mako on the template...
         try:
             ret_val.directory = Template(
                 text=ret_val.directory,
                 strict_undefined=True
             ).render(
                 **variables
             )
         except:
             raise ValueError(
                 "invalid MAKO template:\n{}\nMako came back with error:\n{}".format(
                     indent(ret_val.directory),
                     indent(exceptions.text_error_template().render())
                 )
             )
         # and make it into a "url safe string":
         ret_val.directory = urllib.quote_plus(
             ret_val.directory,
             safe='/' + cls.additional_safe_directory_characters
         )
     except ImportError:
         # Can't do mako parsing of path.  Oh well...
         # But if the user specified additional args, they probably thought they did have
         #   mako installed...
         additional = kwargs.pop('directory_creation_vars', None)
         if additional is not None:
             raise
         # and if they have a ${ in the directory name or a <% in the directory name,
         #   they probably also thought that they had mako.
         # (Note: this could be an issue in the unlikely scenario that the user is using
         #   e.g. zsh and specifying environment variables from within Python as ${ }.
         #   If someone is having that problem, they probably have enough intelligence
         #   also to figure out how to get around it.)
         if '${' in ret_val.directory or '<%' in ret_val.directory:
             raise
         # if they're using a class-level template, they also need to have mako installed
         if used_template:
             raise
     #----------------------------------------#
     ret_val.directory = full_path(ret_val.directory)
     #----------------------------------------#
     # Now create the directory if we're allowed to and need to
     create_dirs = kwargs.pop('create_directories', cls.always_create_missing)
     if create_dirs:
         if not os.path.isdir(ret_val.directory):
             if os.path.exists(ret_val.directory):
                 raise OSError(
                     "path '{}' exists and is not a directory".format(
                         ret_val.directory
                     )
                 )
             os.makedirs(ret_val.directory)
     else:
         if not os.path.isdir(ret_val.directory):
             raise OSError(
                 "'{0}' is not a valid directory, and will not be created.  Set the "
                 "'create_directories' argument of computation to True to do directory "
                 "creation automatically.".format(
                     ret_val.directory
                 ))
     #----------------------------------------#
     # now set the input_file and output_file values
     ret_val.runner.input_file = os.path.join(ret_val.directory, ret_val.runner.input_file)
     ret_val.runner.output_file = os.path.join(ret_val.directory, ret_val.runner.output_file)
     ret_val.runner.working_directory = ret_val.directory
     #--------------------------------------------------------------------------------#
     # Pass the remaining kwargs on to the initialization, which may have been customized for the particular package.
     ret_val.__init__(**kwargs)
     return ret_val
Exemplo n.º 49
0
 def __init__(self, indices,
         begin_index_or_size_or_slices,
         end_index=None,
         name=None,
         parent=None,
         index_range_set=None):
     self.indices, self.sub_indices = EinsumTensor.split_indices(indices, include_sub=True)
     if self.indices != self.sub_indices:
         raise ValueError("can't include indices with sub-indices (such as '{}') in"
                          " IndexRange declaration.".format(
             [self.indices[i] + "_" + self.sub_indices[i] for i in xrange(len(self.indices)) if self.indices[i] != self.sub_indices[i]][0]
         ))
     self.subranges = []
     if parent:
         self.parent = parent
     if index_range_set is None:
         if self.parent is not None:
             self.index_range_set = self.parent.index_range_set
         else:
             self.index_range_set = IndexRange.global_index_range_set
     else:
         self.index_range_set = index_range_set
     self.name = name
     self._begin_is_ellipsis = False
     self._end_is_ellipsis = False
     self._parent = None
     if isinstance(begin_index_or_size_or_slices, int):
         if end_index is not None:
             if end_index is Ellipsis:
                 self._end_is_ellipsis = True
                 self.slice = slice(begin_index_or_size_or_slices, -1)
             else:
                 self.slice = slice(begin_index_or_size_or_slices, end_index)
         else:
             self.slice = slice(0, begin_index_or_size_or_slices)
     elif isinstance(begin_index_or_size_or_slices, slice):
         self.slice = begin_index_or_size_or_slices
     elif begin_index_or_size_or_slices is Ellipsis:
         self._begin_is_ellipsis = True
         if isinstance(end_index, int):
             self.slice = slice(-1, end_index)
         else:
             raise TypeError("Unsupport type for third argument to IndexRange constructor of type {0}".format(classname(end_index)))
     else:
         raise TypeError("Unsupport type for third argument to IndexRange constructor of type {0}".format(classname(begin_index_or_size_or_slices)))
     for idx in self.indices:
         if idx in self.index_range_set.known_ranges:
             raise IndexError(u"Index {0} is already part of index range {1}.".format(idx, self.index_range_set.known_ranges[idx]))
         self.index_range_set[idx] = self