コード例 #1
0
 def to_si(self, value):
     """     
     Convert a quantity in generic units to a quantity in
     S.I. units.
     
     .. code-block:: python
                       
         >>> from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits
         >>> from amuse.units import units, constants
         >>> converter = ConvertBetweenGenericAndSiUnits(constants.c, units.s)
         >>> print converter.to_si(length)
         299792458.0 m
     """ 
     if not hasattr(value, 'unit'):
         return value
         
     factor = value.unit.factor
     number = value.number
     new_unit = 1
     base = value.unit.base
     
     if not base:
         return value
     
     for n, unit in base:
         unit_in_generic, unit_in_si = self.find_si_unit_for(unit)
         if not unit_in_si is None:
             factor = factor * (unit_in_si.factor ** n)
             new_unit *= (unit_in_si.base[0][1] ** n)
         else:
             new_unit *= (unit ** n)
     return new_quantity(number * factor, new_unit)
コード例 #2
0
 def read_inifile_parameters(self, configfile):
     self._configfile = configfile
     parser = ConfigParser()
     parser.optionxform = self._optionxform
     parser.read(configfile)
     for section in parser.sections():
         group = section
         for option in parser.options(section):
             key = (option, group)
             if key in self._inifile_parameters:
                 ptype = self._inifile_parameters[key]["ptype"]
                 dtype = self._inifile_parameters[key]["dtype"]
                 value = self.interpret_value(parser.get(group, option),
                                              dtype=dtype)
                 if is_quantity(self._inifile_parameters[key]["default"]):
                     value = new_quantity(
                         val,
                         to_quantity(
                             self._inifile_parameters[key]["default"]).unit)
                 self._inifile_parameters[key]["value"] = value
             else:
                 value = self.interpret_value(parser.get(group, option))
                 self._inifile_parameters[key] = dict(
                     group_name=group,
                     name=option,
                     set_name=group,
                     default=value,
                     value=value,
                     short=option,
                     ptype="ini",
                     dtype="unknown",
                     description="unknown parameter read from %s" %
                     configfile)
コード例 #3
0
    def read_namelist_parameters(self, inputfile):

        self._nml_file = inputfile
        self._nml_params = f90nml.read(inputfile)

        for group, d in self._nml_params.iteritems():
            for short, val in d.iteritems():
                key = (short, group.upper())
                if key in self._namelist_parameters:
                    group_name = self._namelist_parameters[key]["group_name"]
                    name = self._namelist_parameters[key]["name"]
                    parameter_set_name = self._namelist_parameters[key].get(
                        "set_name", "parameters_" + group_name)
                    parameter_set = getattr(self, parameter_set_name)
                    if is_quantity(self._namelist_parameters[key]["default"]):
                        setattr(
                            parameter_set, name,
                            new_quantity(
                                val,
                                to_quantity(self._namelist_parameters[key]
                                            ["default"]).unit))
                    else:
                        setattr(parameter_set, name, val)
                else:
                    print "'%s' of group '%s' not in the namelist_parameters" % (
                        short, group)
コード例 #4
0
ファイル: test_bhtree.py プロジェクト: tjardaboekholt/amuse
    def test13(self):

        convert_nbody = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.m)

        instance = BHTree(convert_nbody)
        instance.commit_parameters()

        particles = datamodel.Particles(2)
        self.assertEquals(len(instance.particles), 0)

        particles.mass = [30.0, 30.0] | units.kg
        particles.radius = [1.0, 1.0] | units.m
        particles.position = [[-10.0, 0.0, 0.0], [10.0, 0.0, 0.0]] | units.m
        particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]
                              ] | units.m / units.s

        instance.particles.add_particles(particles)
        instance.commit_particles()

        copyof = instance.particles.copy()

        com = instance.center_of_mass_position
        self.assertAlmostEqual(com[0], quantities.new_quantity(0.0, units.m),
                               constants.precision)
        instance.stop()
コード例 #5
0
ファイル: parameter_tools.py プロジェクト: kyliow/amuse
    def read_parameters(self, inputfile, add_missing_parameters=False):
        self._file=inputfile

        _nml_params = f90nml.read(inputfile)

        rawvals, comments = self._read_file(inputfile)

        for key, rawval in rawvals.items():      
                if key in self._parameters:
                    group_name=self._parameters[key]["group_name"]
                    name=self._parameters[key]["name"]
                    dtype=self._parameters[key]["dtype"]
                    val=self.interpret_value( rawval, dtype=dtype)
                    if is_quantity(self._parameters[key]["default"]):
                        self._parameters[key]["value"]=new_quantity(val, to_quantity(self._parameters[key]["default"]).unit)
                    else:
                        self._parameters[key]["value"]=val 
                else:
                    if not add_missing_parameters:
                        print("'{0}' of group '{1}' not in the parameters list".format(*key))
                    else:
                        value=rawval
                        description=comments.get(key, "unknown parameter read from {0}".format(inputfile))
                        self._parameters[key]=dict(
                            group_name=key[1],
                            name=key[0],
                            short_name=key[0],
                            default=value,
                            value=value,
                            short=key[0],
                            ptype=self._ptypes[0],
                            dtype=dtype_str[type(value)],
                            description=description
                            )                        
コード例 #6
0
    def to_generic(self, value):
        """
        Convert a quantity in S.I units to a quantity in
        generic units.
        
        .. code-block:: python
        
            >>> from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits
            >>> from amuse.units import units, constants
            >>> converter = ConvertBetweenGenericAndSiUnits(constants.c, units.s)
            >>> print converter.to_generic(constants.c)
            1.0 length * time**-1

        """   
    
        generic_units_in_si = self.units
        if value.unit is None:
            return value
        base = value.unit.base
        factor = value.unit.factor
        number = value.number
        new_unit = 1
        
        if not base:
            return value
            
        for n, unit in base:
            unit_in_generic, unit_in_si = self.find_generic_unit_for(unit)
            if not unit_in_si is None:
                factor = factor / (unit_in_si.factor ** n)
                new_unit *= (unit_in_generic.base[0][1] ** n)
            else:
                new_unit *= (unit ** n)
        return new_quantity(number * factor, new_unit)
コード例 #7
0
    def convert_return_value(self, return_value, storage,
                             attributes_to_return):
        if len(self.attribute_names) == 1:
            return_value = (return_value, )

        set_of_attributes_to_return = set(attributes_to_return)

        result = {}

        if self.index_output_attributes:
            index_output_attributes = self.index_output_attributes
        else:
            index_output_attributes = [False] * len(return_value)

        for value, attribute, isindex in zip(return_value,
                                             self.attribute_names,
                                             index_output_attributes):
            if attribute in set_of_attributes_to_return:
                if isindex:
                    result[attribute] = quantities.new_quantity(
                        storage._get_keys_for_indices_in_the_code(value),
                        units.object_key)
                else:
                    result[attribute] = value

        return result
コード例 #8
0
def read_quantity(string):
    """
    convert a string to a quantity or vectorquantity

    the string must be formatted as '[1, 2, 3] unit' for a vectorquantity,
    or '1 unit' for a quantity.
    """

    if "]" in string:
        values = list(map(float, string[1:].split('] ')[0].split(',')))
        unit = find_unit(string.split('] ')[1].split(' '))
        quantity = new_quantity(values, unit)
    else:
        value = float(string.split(' ')[0])
        unit = find_unit(string.split(' ')[1:])
        quantity = new_quantity(value, unit)
    return quantity
コード例 #9
0
ファイル: core.py プロジェクト: stevemcmillan/amuse
    def new_quantity(self, value):
        """Create a new Quantity object.

        :argument value: numeric value of the quantity, can be 
            a number or a sequence (list or ndarray)
        :returns: new ScalarQuantity or VectorQuantity object 
            with this unit
        """
        from amuse.units import quantities
        return quantities.new_quantity(value, self)
コード例 #10
0
    def new_quantity(self, value):
        """Create a new Quantity object.

        :argument value: numeric value of the quantity, can be 
            a number or a sequence (list or ndarray)
        :returns: new ScalarQuantity or VectorQuantity object 
            with this unit
        """
        from amuse.units import quantities
        return quantities.new_quantity(value, self)
コード例 #11
0
def read_quantity(string):
    """
    convert a string to a quantity or vectorquantity

    the string must be formatted as '[1, 2, 3] unit' for a vectorquantity,
    or '1 unit' for a quantity.
    """

    if "]" in string:
        # It's a list, so convert it to a VectorQuantity.
        # The unit part comes after the list.
        # The list itself must consist of floats only!
        values = list(map(float, string[1:].split('] ')[0].split(',')))
        unit = find_unit(string.split('] ')[1].split(' '))
        quantity = new_quantity(values, unit)
    else:
        value = float(string.split(' ')[0])
        unit = find_unit(string.split(' ')[1:])
        quantity = new_quantity(value, unit)
    return quantity
コード例 #12
0
ファイル: optparse.py プロジェクト: yon23/amuse-framework
def check_builtin_unit(option, opt, value):
    (cvt, what) = optparse._builtin_cvt[option.type]
    try:
        result = cvt(value)
        if option.unit is None:
            return result
        else:
            return quantities.new_quantity(result, option.unit)

    except ValueError:
        raise optparse.OptionValueError("option %s: invalid %s value: %r" %
                                        (opt, what, value))
コード例 #13
0
ファイル: optparse.py プロジェクト: Ingwar/amuse
def check_builtin_unit(option, opt, value):
    (cvt, what) = optparse._builtin_cvt[option.type]
    try:
        result = cvt(value)
        if option.unit is None:
            return result
        else:
            return quantities.new_quantity(result, option.unit)

    except ValueError:
        raise optparse.OptionValueError(
            "option %s: invalid %s value: %r" % (opt, what, value))
コード例 #14
0
ファイル: optparse.py プロジェクト: Ingwar/amuse
    def get_default_values(self):
        if not self.process_default_values:
                # Old, pre-Optik 1.5 behaviour.
            return Values(self.defaults)

        defaults = self.defaults.copy()
        for option in self._get_all_options():
            default = defaults.get(option.dest)
            if isinstance(default, basestring):
                opt_str = option.get_opt_string()
                defaults[option.dest] = option.check_value(opt_str, default)
            elif not option.unit is None and not quantities.is_quantity(default):
                defaults[option.dest] = quantities.new_quantity(default, option.unit)

        return optparse.Values(defaults)
コード例 #15
0
ファイル: optparse.py プロジェクト: yon23/amuse-framework
    def get_default_values(self):
        if not self.process_default_values:
            # Old, pre-Optik 1.5 behaviour.
            return Values(self.defaults)

        defaults = self.defaults.copy()
        for option in self._get_all_options():
            default = defaults.get(option.dest)
            if isinstance(default, basestring):
                opt_str = option.get_opt_string()
                defaults[option.dest] = option.check_value(opt_str, default)
            elif not option.unit is None and not quantities.is_quantity(
                    default):
                defaults[option.dest] = quantities.new_quantity(
                    default, option.unit)

        return optparse.Values(defaults)
コード例 #16
0
ファイル: scaling_converter.py プロジェクト: Ingwar/amuse
 def convert(self, quantity):
     unit = quantity.unit
     value = quantity.value_in(unit)
     
     base = unit.base
     if not base:
         return quantity
         
     new_unit = 1
     factor = unit.factor
     
     for n, unit in base:
         if unit in self.factors:
             factor_for_unit = self.factors[unit]
             factor = factor * (factor_for_unit ** n)
             new_unit *= (unit ** n)
         else:
             new_unit *= (unit ** n)
     return new_quantity(value * factor, new_unit)
コード例 #17
0
ファイル: core.py プロジェクト: stevemcmillan/amuse
 def as_quantity_in(self, unit):
     """Express this unit as a quantity in the given unit
     
     :argument unit: The unit to express this unit in
     :result: A Quantity object
     
     Examples
     
     >>> from amuse.units import units
     >>> ton = 1000 * units.kg
     >>> ton.as_quantity_in(units.kg)
     quantity<1000.0 kg>
     """
     from amuse.units import quantities
     if isinstance(unit, quantities.Quantity):
         raise exceptions.AmuseException("Cannot expres a unit in a quantity")
     else:
         factor = self.conversion_factor_from(unit)
         return quantities.new_quantity(factor, unit)
コード例 #18
0
 def as_quantity_in(self, unit):
     """Express this unit as a quantity in the given unit
     
     :argument unit: The unit to express this unit in
     :result: A Quantity object
     
     Examples
     
     >>> from amuse.units import units
     >>> ton = 1000 * units.kg
     >>> ton.as_quantity_in(units.kg)
     quantity<1000.0 kg>
     """
     from amuse.units import quantities
     if isinstance(unit, quantities.Quantity):
         raise exceptions.AmuseException("Cannot expres a unit in a quantity")
     else:
         factor = self.conversion_factor_from(unit)
         return quantities.new_quantity(factor, unit)
コード例 #19
0
ファイル: incode_storage.py プロジェクト: Ingwar/amuse
 def convert_return_value(self, return_value, storage, attributes_to_return):
     if len(self.attribute_names) == 1:
         return_value = (return_value,)
     
     set_of_attributes_to_return = set(attributes_to_return)
     
     result = {}
     
     if self.index_output_attributes:
         index_output_attributes = self.index_output_attributes
     else:
         index_output_attributes = [False] * len(return_value)
     
     for value, attribute, isindex in zip(return_value, self.attribute_names, index_output_attributes):
         if attribute in set_of_attributes_to_return:
             if isindex:
                 result[attribute] = quantities.new_quantity(storage._get_keys_for_indices_in_the_code(value), units.object_key)
             else:
                 result[attribute] = value
                 
     return result
コード例 #20
0
ファイル: test_fdps.py プロジェクト: rieder/amuse
 def test13(self):
    
     convert_nbody = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.m)
     
     instance = FDPS(convert_nbody)
     instance.commit_parameters()
     
     particles = datamodel.Particles(2)
     self.assertEquals(len(instance.particles), 0)
     
     particles.mass = [30.0, 30.0] | units.kg
     particles.radius =  [1.0, 1.0] | units.m
     particles.position = [[-10.0, 0.0, 0.0], [10.0, 0.0, 0.0]] | units.m
     particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s
     
     instance.particles.add_particles(particles)
     instance.commit_particles()
     
     copyof =  instance.particles.copy()
     
     com = instance.center_of_mass_position
     self.assertAlmostEqual(com[0], quantities.new_quantity(0.0, units.m), constants.precision)
     instance.stop()
コード例 #21
0
ファイル: plot_with_units.py プロジェクト: amusecode/amuse
if __name__ == "__main__":

    # latex_support()

    x = np.pi/20.0 * (range(-10, 10) | units.m)
    y1 = units.MSun.new_quantity(np.sin(x.number))
    y2 = units.MSun.new_quantity(x.number)
    native_plot.subplot(2, 2, 1)
    plot(x, y2, label='model')
    scatter(x, y1, label='data')
    xlabel('x')
    ylabel('mass [$M_\odot$]')  # overrides auto unit!
    native_plot.legend(loc=2)

    x = range(50) | units.Myr
    y1 = quantities.new_quantity(
        np.sin(np.arange(0, 1.5, 0.03)), 1e50*units.erg)
    y2 = -(1e43 | units.J) - y1
    native_plot.subplot(2, 2, 2)
    plot(x, y1, label='$E_\mathrm{kin}$')
    plot(x, y2, label='$E_\mathrm{pot}$')
    xlabel('t')
    ylabel('E')
    native_plot.legend()

    x = range(7) | units.day
    y1 = [0, 4, 2, 3, 2, 5, 1]
    y2 = [3, 0, 2, 2, 3, 0, 4]
    native_plot.subplot(2, 2, 3)
    plot(x, y1, 'ks', label='coffee')
    plot(x, y2, 'yo', label='tea')
    xlabel('time')
コード例 #22
0
def amuse_nth_root(quant, n):
    # Simply telling AMUSE quant**(1./3) breaks the units :-(
    return new_quantity((quant.number)**(1. / n),
                        (quant.unit**(1. / n)).to_simple_form())
コード例 #23
0
if __name__ == "__main__":

    # latex_support()

    x = np.pi / 20.0 * (list(range(-10, 10)) | units.m)
    y1 = units.MSun.new_quantity(np.sin(x.number))
    y2 = units.MSun.new_quantity(x.number)
    native_plot.subplot(2, 2, 1)
    plot(x, y2, label='model')
    scatter(x, y1, label='data')
    xlabel('x')
    ylabel('mass [$M_\odot$]')  # overrides auto unit!
    native_plot.legend(loc=2)

    x = list(range(50)) | units.Myr
    y1 = quantities.new_quantity(
        np.sin(np.arange(0, 1.5, 0.03)), 1e50 * units.erg)
    y2 = -(1e43 | units.J) - y1
    native_plot.subplot(2, 2, 2)
    plot(x, y1, label='$E_\mathrm{kin}$')
    plot(x, y2, label='$E_\mathrm{pot}$')
    xlabel('t')
    ylabel('E')
    native_plot.legend()

    x = list(range(7)) | units.day
    y1 = [0, 4, 2, 3, 2, 5, 1]
    y2 = [3, 0, 2, 2, 3, 0, 4]
    native_plot.subplot(2, 2, 3)
    plot(x, y1, 'ks', label='coffee')
    plot(x, y2, 'yo', label='tea')
    xlabel('time')