Exemplo n.º 1
0
    def __init__(self, h, a):

        # define new units
        #----------------------------------------------------
        self.h = pq.UnitQuantity('dimensionless hubble parameter',
                                 h,
                                 symbol='hh')

        self.a = pq.UnitQuantity('scale factor a = 1/(1+z)', a, symbol='aa')

        Units.__init__(self)
Exemplo n.º 2
0
 def __init__(self):
     self.cell = Organelle("cell")
     self.nucleus = Organelle('nucleus')
     self.cell.diameter = pq.Quantity(5, 'um')
     self.cell.volume = pq.Quantity(50, 'um**3')
     self.nucleus.diameter = pq.Quantity(2, 'um')
     self.nucleus.volume = pq.UncertainQuantity(2.9, 'um**3', 0.2)
     pq.nucleur_volume = pq.UnitQuantity('nuclear volume',
                                         self.nucleus.volume,
                                         symbol='NucVol')
     pq.cell_volume = pq.UnitQuantity('cellular volume',
                                      self.cell.volume,
                                      symbol='CellVol')
Exemplo n.º 3
0
    def declare_unit(obj, unit_key, conversion, name, base=False):
        """
        Create and return unit using specified package.
        """
        if obj.package == 'Quantities':
            unit_obj = pq.UnitQuantity(name,
                                       definition=conversion,
                                       symbol=unit_key)

            if base:
                unit = [(unit_obj, unit_key, conversion, name)]
                obj._set_base_units_pq(unit)
            else:
                unit = [(unit_obj, conversion)]
                obj.initialize_units(unit)

            return unit_obj

        if obj.package == 'Unum':
            if conversion is None:
                conversion = 0

            obj.del_unit(unit_key)
            unit_obj = unum.Unum.unit(unit_key, conversion, name)

            if base:
                unit = [(unit_obj, unit_key, conversion, name)]
                obj._set_base_units_unum(unit)
            else:
                unit = [(unit_obj, conversion)]
                obj.initialize_units(unit)

            return unit_obj
Exemplo n.º 4
0
    def from_destructured(self, unit_dict):
        unit = pq.UnitQuantity(
            unit_dict.get('name'),
            import_class(unit_dict.get('base').get('quantity')) *
            unit_dict.get('base').get('coefficient'), unit_dict.get('symbol'))

        return unit
Exemplo n.º 5
0
    def __init__(self):
        """ Define units """
        self.mF = pq.UnitQuantity('millifarad', pq.farad / 1e3, symbol='mF')
        self.uF = pq.UnitQuantity('microfarad', pq.farad / 1e6, symbol='uF')
        self.nF = pq.UnitQuantity('nanofarad', pq.farad / 1e9, symbol='nF')
        self.pF = pq.UnitQuantity('picofarad', pq.farad / 1e12, symbol='pF')

        self.mH = pq.UnitQuantity('millihenry', pq.henry / 1e3, symbol='mH')
        self.uH = pq.UnitQuantity('microhenry', pq.henry / 1e6, symbol='uH')
        self.nH = pq.UnitQuantity('nanohenry', pq.henry / 1e9, symbol='nH')
        self.pH = pq.UnitQuantity('picohenry', pq.henry / 1e12, symbol='pH')
Exemplo n.º 6
0
    def __init__(self, observation={}, name="Cell Density Test"):
        description = ("Tests the cell density within a single layer of model")
        self.units = quantities.UnitQuantity('1000/mm3',
                                             1e3 / quantities.mm**3,
                                             symbol='1000/mm3')
        required_capabilities = (cap.ProvidesDensityInfo, )

        observation = self.format_data(observation)
        self.figures = []
        sciunit.Test.__init__(self, observation, name)

        self.directory_output = './output/'
Exemplo n.º 7
0
def iCSD(lfp_data):
    #patch quantities with the SI unit Siemens if it does not exist
    for symbol, prefix, definition, u_symbol in zip(
        ['siemens', 'S', 'mS', 'uS', 'nS', 'pS'],
        ['', '', 'milli', 'micro', 'nano', 'pico'],
        [pq.A / pq.V, pq.A / pq.V, 'S', 'mS', 'uS', 'nS'],
        [None, None, None, None, u'uS', None]):
        if type(definition) is str:
            definition = lastdefinition / 1000
        if not hasattr(pq, symbol):
            setattr(
                pq, symbol,
                pq.UnitQuantity(prefix + 'siemens',
                                definition,
                                symbol=symbol,
                                u_symbol=u_symbol))
        lastdefinition = definition

    #prepare lfp data for use, by changing the units to SI and append quantities,
    #along with electrode geometry, conductivities and assumed source geometry

    lfp_data = lfp_data * 1E-6 * pq.V  # [uV] -> [V]
    #z_data = np.linspace(100E-6, 2300E-6, 23) * pq.m  # [m]
    z_data = np.linspace(100E-6, 1000E-6, 32) * pq.m  # [m]
    #diam = 500E-6 * pq.m                              # [m]
    diam = 250E-6 * pq.m  # [m] bigger vals make smaller sources/sinks
    h = 100E-6 * pq.m  # [m]  (makes no difference with spline iCSD method)
    sigma = 0.3 * pq.S / pq.m  # [S/m] or [1/(ohm*m)] (makes no difference with spline iCSD method)
    sigma_top = 0.3 * pq.S / pq.m  # [S/m] or [1/(ohm*m)]

    # Input dictionaries for each method
    spline_input = {
        'lfp': lfp_data,
        'coord_electrode': z_data,
        'diam': diam,
        'sigma': sigma,
        'sigma_top': sigma,
        'num_steps': 201,  # Spatial CSD upsampling to N steps
        'tol': 1E-12,
        'f_type': 'gaussian',
        'f_order': (20, 5),
    }

    # how to call!
    csd_obj = icsd.SplineiCSD(**spline_input)
    csd = csd_obj.get_csd()
    csd = csd_obj.filter_csd(csd)
    return csd
Exemplo n.º 8
0
def patch_quantities():
    """patch quantities with the SI unit Siemens if it does not exist"""
    for symbol, prefix, definition, u_symbol in zip(
        ['siemens', 'S', 'mS', 'uS', 'nS', 'pS'],
        ['', '', 'milli', 'micro', 'nano', 'pico'],
        [pq.A / pq.V, pq.A / pq.V, 'S', 'mS', 'uS', 'nS'],
        [None, None, None, None, u'µS', None]):
        if type(definition) is str:
            definition = lastdefinition / 1000
        if not hasattr(pq, symbol):
            setattr(
                pq, symbol,
                pq.UnitQuantity(prefix + 'siemens',
                                definition,
                                symbol=symbol,
                                u_symbol=u_symbol))
        lastdefinition = definition
    return
Exemplo n.º 9
0
class RandomTest(sciunit.Test):
    required_capabilities = (ProducesSpikes, )
    score_type = sciunit.scores.ZScore
    url = 'http://test-url.com'

    units = pq.UnitQuantity('megaohm', pq.ohm * 1e6, symbol='Mohm')  # Megaohms

    observation_schema = [("Mean, Standard Deviation, N", {
        'mean': {
            'units': True,
            'required': True
        },
        'std': {
            'units': True,
            'min': 0,
            'required': True
        },
        'n': {
            'type': 'integer',
            'min': 1
        }
    }),
                          ("Mean, Standard Error, N", {
                              'mean': {
                                  'units': True,
                                  'required': True
                              },
                              'sem': {
                                  'units': True,
                                  'min': 0,
                                  'required': True
                              },
                              'n': {
                                  'type': 'integer',
                                  'min': 1,
                                  'required': True
                              }
                          })]

    def generate_prediction(self, model):
        count = model.get_spike_count()
        return 1 * pq.MOhm
Exemplo n.º 10
0
import quantities as pq
import warnings

from neo.io.baseio import BaseIO
from neo.core import Segment, AnalogSignal, SpikeTrain

try:
    unicode
    PY2 = True
except NameError:
    PY2 = False

UNITS_MAP = {
    'spikes': pq.ms,
    'v': pq.mV,
    'gsyn': pq.UnitQuantity('microsiemens', 1e-6 * pq.S, 'uS',
                            'µS'),  # checked
}


class BasePyNNIO(BaseIO):
    """
    Base class for PyNN IO classes
    """
    is_readable = True
    is_writable = True
    has_header = True
    is_streameable = False  # TODO - correct spelling to "is_streamable"
    supported_objects = [Segment, AnalogSignal, SpikeTrain]
    readable_objects = supported_objects
    writeable_objects = supported_objects
    mode = 'file'
Exemplo n.º 11
0
"""
Small module to manage units and dimension analysis
"""
import quantities as pq


temperature = 300 * pq.K
kT = pq.UnitQuantity("k_B T", definition=300 * pq.K * 1 * pq.constants.k, symbol="kT")

length = pq.um
force = pq.UnitQuantity("nanonewton", definition=1e-9 * pq.N, symbol="nN")
energy = pq.UnitQuantity("femtojoules", definition=force * length, symbol="fJ")
time = pq.s

line_tension = energy / length
line_elasticity = energy / length ** 2
line_viscosity = force * time / length


area = length ** 2
area_tension = energy / area
area_elasticity = energy / area ** 2

vol = length ** 3
vol_tension = energy / vol
vol_elasticity = energy / vol ** 2
Exemplo n.º 12
0
.. autoclass:: EphyviewerConfigurator
   :members:
"""

import re

import numpy as np
import pandas as pd
import quantities as pq
import ephyviewer

from ..datasets.metadata import _abs_path
from ..gui.epochencoder import NeuroticWritableEpochSource

pq.mN = pq.UnitQuantity('millinewton', pq.N/1e3, symbol = 'mN');  # define millinewton


class EphyviewerConfigurator():
    """
    A class for launching ephyviewer for a dataset with configurable viewers.

    At initialization, invalid viewers are automatically disabled (e.g., the
    video viewer is disabled if ``video_file`` is not given in ``metadata``).
    Viewers can be hidden or shown before launch using the built-in methods.
    Valid viewer names are:

        * ``traces``
        * ``traces_rauc``
        * ``freqs``
        * ``spike_trains``
Exemplo n.º 13
0
def run(opt, star, planet, zodi):

    exosim_msg('Run instrument model ... ')
    st = time.time()
    instrument_emission     = Sed(star.sed.wl,
                                  np.zeros(star.sed.wl.size, dtype=np.float64)* \
                                  pq.W/pq.m**2/pq.um/pq.sr)
    instrument_transmission = Sed(star.sed.wl,
                                  np.ones(star.sed.wl.size, dtype=np.float64))

    for op in opt.common_optics.optical_surface:
        dtmp_tr = np.loadtxt(op.transmission.replace('__path__', opt.__path__),
                             delimiter=',')
        dtmp_em = np.loadtxt(op.emissivity.replace('__path__', opt.__path__),
                             delimiter=',')

        tr = Sed(dtmp_tr[:, 0] * pq.um, dtmp_tr[:, 1] * pq.dimensionless)
        tr.rebin(opt.common.common_wl)

        em = Sed(dtmp_em[:, 0] * pq.um, dtmp_em[:, 1] * pq.dimensionless)
        em.rebin(opt.common.common_wl)

        exolib.sed_propagation(star.sed, tr)
        exolib.sed_propagation(zodi.sed, tr)
        exolib.sed_propagation(instrument_emission,
                               tr,
                               emissivity=em,
                               temperature=op())

        instrument_transmission.sed = instrument_transmission.sed * tr.sed

    channel = {}
    for ch in opt.channel:
        #if ch.name != 'NIR Spec': continue
        channel[ch.name] = Channel(star.sed,
                                   planet.cr,
                                   zodi.sed,
                                   instrument_emission,
                                   instrument_transmission,
                                   options=ch)

        ch_optical_surface = ch.optical_surface if isinstance(ch.optical_surface, list) else \
          [ch.optical_surface]
        for op in ch.optical_surface:
            dtmp = np.loadtxt(op.transmission.replace('__path__',
                                                      opt.__path__),
                              delimiter=',')
            tr = Sed(dtmp[:,0]*pq.um, \
                    dtmp[:,1]*pq.dimensionless)
            tr.rebin(opt.common.common_wl)
            em = Sed(dtmp[:,0]*pq.um, \
                     dtmp[:,2]*pq.dimensionless)
            em.rebin(opt.common.common_wl)
            exolib.sed_propagation(channel[ch.name].star, tr)
            exolib.sed_propagation(channel[ch.name].zodi, tr)
            exolib.sed_propagation(channel[ch.name].emission, \
                    tr, emissivity=em,temperature=op())
            channel[ch.name].transmission.sed *= tr.sed

        # BUG workaround. There is a bug in the binning function. If transmission is zero,
        # it is rebiined to a finite, very small value. This needs to be fixed!
        # For now, I set to zero all transmission smaller than an arbitrary value
        #idx = np.where(channel[ch.name].transmission.sed < 1.0e-5)
        #channel[ch.name].star.sed[idx] = 0.0*channel[ch.name].star.sed.units
        #channel[ch.name].zodi.sed[idx] = 0.0*channel[ch.name].zodi.sed.units
        #channel[ch.name].emission.sed[idx] = 0.0*channel[ch.name].emission.sed.units
        #channel[ch.name].transmission.sed[idx] = 0.0*channel[ch.name].transmission.sed.units

        # Convert spectral signals
        dtmp = np.loadtxt(ch.qe().replace('__path__', opt.__path__),
                          delimiter=',')
        qe = Sed(dtmp[:,0]*pq.um, \
                     dtmp[:,1]*pq.dimensionless)

        Responsivity = qe.sed * qe.wl.rescale(
            pq.m) / (spc.c * spc.h * pq.m * pq.J) * pq.UnitQuantity(
                'electron', symbol='e-')

        Re = scipy.interpolate.interp1d(qe.wl, Responsivity)

        Aeff = 0.25 * np.pi * opt.common_optics.TelescopeEffectiveDiameter()**2
        Omega_pix = 2.0 * np.pi * (1.0 -
                                   np.cos(np.arctan(0.5 / ch.wfno()))) * pq.sr
        Apix = ch.detector_pixel.pixel_size()**2
        channel[ch.name].star.sed     *= Aeff             * \
          Re(channel[ch.name].star.wl)*pq.UnitQuantity('electron', 1*pq.counts, symbol='e-')/pq.J
        channel[ch.name].zodi.sed     *= Apix * Omega_pix * \
          Re(channel[ch.name].zodi.wl)*pq.UnitQuantity('electron', 1*pq.counts, symbol='e-')/pq.J
        channel[ch.name].emission.sed *= Apix * Omega_pix * \
          Re(channel[ch.name].emission.wl)*pq.UnitQuantity('electron', 1*pq.counts, symbol='e-')/pq.J

        ### create focal plane

        #1# allocate focal plane with pixel oversampling such that Nyquist sampling is done correctly
        fpn = ch.array_geometry()
        fp = np.zeros((fpn * ch.osf()).astype(np.int))

        #2# This is the current sampling interval in the focal plane.
        fp_delta = ch.detector_pixel.pixel_size() / ch.osf()

        #3# Load dispersion law
        if ch.type == 'spectrometer':
            if hasattr(ch, "dispersion"):
                dtmp = np.loadtxt(ch.dispersion.path.replace(
                    '__path__', opt.__path__),
                                  delimiter=',')
                ld = scipy.interpolate.interp1d(dtmp[..., 2] * pq.um +
                                                ch.dispersion().rescale(pq.um),
                                                dtmp[..., 0],
                                                bounds_error=False,
                                                kind='slinear',
                                                fill_value=0.0)
            elif hasattr(ch, "ld"):
                # wl = ld[0] + ld[1](x - ld[2]) = ld[1]*x + ld[0]-ldp[1]*ld[2]
                ld = np.poly1d(
                    (ch.ld()[1], ch.ld()[0] - ch.ld()[1] * ch.ld()[2]))
            else:
                exolib.exosim_error("Dispersion law not defined.")

            #4a# Estimate pixel and wavelength coordinates
            x_pix_osr = np.arange(fp.shape[1]) * fp_delta
            x_wav_osr = ld(x_pix_osr.rescale(
                pq.um).magnitude) * pq.um  # walength on each x pixel
            channel[ch.name].wl_solution = x_wav_osr

        elif ch.type == 'photometer':
            #4b# Estimate pixel and wavelength coordinates
            idx = np.where(channel[ch.name].transmission.sed >
                           channel[ch.name].transmission.sed.max() / np.e)
            x_wav_osr = np.linspace(
                channel[ch.name].transmission.wl[idx].min().item(),
                channel[ch.name].transmission.wl[idx].max().item(),
                8 * ch.osf()) * channel[ch.name].transmission.wl.units
            x_wav_center = (channel[ch.name].transmission.wl[idx]*channel[ch.name].transmission.sed[idx]).sum() / \
              channel[ch.name].transmission.sed[idx].sum()

            channel[ch.name].wl_solution = np.repeat(x_wav_center, fp.shape[1])

        else:
            exolib.exosim_error(
                "Channel should be either photometer or spectrometer.")

        d_x_wav_osr = np.zeros_like(x_wav_osr)
        idx = np.where(x_wav_osr > 0.0)
        d_x_wav_osr[idx] = np.gradient(x_wav_osr[idx])
        if np.any(d_x_wav_osr < 0): d_x_wav_osr *= -1.0

        #5# Generate PSFs, one in each detector pixel along spectral axis
        psf = exolib.Psf(x_wav_osr, ch.wfno(), \
                        fp_delta, shape='airy')

        #6# Save results in Channel class
        channel[ch.name].fp_delta = fp_delta
        channel[ch.name].psf = psf
        channel[ch.name].fp = fp
        channel[ch.name].osf = np.int(ch.osf())
        channel[ch.name].offs = np.int(ch.pix_offs())

        channel[ch.name].planet.sed *= channel[ch.name].star.sed
        channel[ch.name].star.rebin(x_wav_osr)
        channel[ch.name].planet.rebin(x_wav_osr)
        channel[ch.name].zodi.rebin(x_wav_osr)
        channel[ch.name].emission.rebin(x_wav_osr)
        channel[ch.name].transmission.rebin(x_wav_osr)
        channel[ch.name].star.sed *= d_x_wav_osr
        channel[ch.name].planet.sed *= d_x_wav_osr
        channel[ch.name].zodi.sed *= d_x_wav_osr
        channel[ch.name].emission.sed *= d_x_wav_osr

        #7# Populate focal plane with monochromatic PSFs
        if ch.type == 'spectrometer':
            j0 = np.round(np.arange(fp.shape[1]) - psf.shape[1] // 2).astype(
                np.int)

        elif ch.type == 'photometer':
            j0 = np.repeat(fp.shape[1] // 2, x_wav_osr.size)
        else:
            exolib.exosim_error(
                "Channel should be either photometer or spectrometer.")

        j1 = j0 + psf.shape[1]
        idx = np.where((j0 >= 0) & (j1 < fp.shape[1]))[0]
        i0 = fp.shape[0] // 2 - psf.shape[0] // 2 + channel[ch.name].offs
        i1 = i0 + psf.shape[0]
        for k in idx:            channel[ch.name].fp[i0:i1, j0[k]:j1[k]] += psf[...,k] * \
  channel[ch.name].star.sed[k]

        #9# Now deal with the planet
        planet_response = np.zeros(fp.shape[1])
        i0p = np.unravel_index(np.argmax(channel[ch.name].psf.sum(axis=2)),
                               channel[ch.name].psf[..., 0].shape)[0]
        for k in idx:
            planet_response[j0[k]:j1[k]] += psf[i0p, :, k] * channel[
                ch.name].planet.sed[k]

        #9# Allocate pixel response function
        kernel, kernel_delta = exolib.PixelResponseFunction(
            channel[ch.name].psf.shape[0:2],
            7 * ch.osf(),  # NEED TO CHANGE FACTOR OF 7 
            ch.detector_pixel.pixel_size(),
            lx=ch.detector_pixel.pixel_diffusion_length())

        channel[ch.name].fp = exolib.fast_convolution(
            channel[ch.name].fp, channel[ch.name].fp_delta, kernel,
            kernel_delta)

        ## TODO CHANGE THIS: need to convolve planet with pixel response function
        channel[ch.name].planet = Sed(
            channel[ch.name].wl_solution,
            planet_response / (1e-30 + fp[(i0 + i1) // 2, ...]))

        ## Fix units
        channel[
            ch.name].fp = channel[ch.name].fp * channel[ch.name].star.sed.units
        channel[ch.name].planet.sed = channel[
            ch.name].planet.sed * pq.dimensionless

        ## Deal with diffuse radiation
        if ch.type == 'spectrometer':
            channel[ch.name].zodi.sed = scipy.convolve(
                channel[ch.name].zodi.sed,
                np.ones(np.int(ch.slit_width() * channel[ch.name].opt.osf())),
                'same') * channel[ch.name].zodi.sed.units
            channel[ch.name].emission.sed = scipy.convolve(
                channel[ch.name].emission.sed,
                np.ones(np.int(ch.slit_width() * channel[ch.name].opt.osf())),
                'same') * channel[ch.name].emission.sed.units
        elif ch.type == 'photometer':
            channel[ch.name].zodi.sed = np.repeat(
                channel[ch.name].zodi.sed.sum(),
                channel[ch.name].wl_solution.size)
            channel[ch.name].zodi.wl = channel[ch.name].wl_solution
            channel[ch.name].emission.sed = np.repeat(
                channel[ch.name].emission.sed.sum(),
                channel[ch.name].wl_solution.size)
            channel[ch.name].emission.wl = channel[ch.name].wl_solution

        else:
            exolib.exosim_error(
                "Channel should be either photometer or spectrometer.")

    exosim_msg(' - execution time: {:.0f} msec.\n'.format(
        (time.time() - st) * 1000.0))
    return channel

    pass
Exemplo n.º 14
0
	:param precision:
	:param tex: Whether the string should be formatted for LaTeX.
	"""

    if tex:
        unit_str = as_latex(value)
    else:
        attr = "unicode" if quantities.markup.config.use_unicode else "string"
        unit_str = getattr(value.dimensionality, attr)
    return precision % float(value.magnitude), unit_str


# Additional units to complement quantities
#: Per 100 electronVolts.
per100eV = quantities.UnitQuantity(
    "per_100_eV",
    1 / (100 * quantities.eV * quantities.constants.Avogadro_constant),
    u_symbol="(100eV)**-1")

#: Decimetre
dm = decimetre = quantities.UnitQuantity("decimetre",
                                         quantities.m / 10.0,
                                         u_symbol="dm")

#: Square metre
m3 = quantities.metre**3

#: Square decimetre
dm3 = decimetre**3

#: Square cenimetre
cm3 = quantities.centimetre**3
Exemplo n.º 15
0
:copyright: Copyright 2006-2015 by the PyNN team, see AUTHORS.
:license: CeCILL, see LICENSE for details.
"""

import logging
import numpy
import quantities as pq
import neo
import brian
from pyNN import recording
from . import simulator

mV = brian.mV
ms = brian.ms
uS = brian.uS
pq.uS = pq.UnitQuantity('microsiemens', 1e-6*pq.S, 'uS')
pq.nS = pq.UnitQuantity('nanosiemens', 1e-9*pq.S, 'nS')

logger = logging.getLogger("PyNN")


class Recorder(recording.Recorder):
    """Encapsulates data and functions related to recording model variables."""
    _simulator = simulator

    def __init__(self, population=None, file=None):
        __doc__ = recording.Recorder.__doc__
        recording.Recorder.__init__(self, population, file)
        self._devices = {} # defer creation until first call of record()

    def _create_device(self, group, variable):
Exemplo n.º 16
0
        """
        return self.dot_product(other) / (self.get_magnitude() *
                                          other.get_magnitude())

    def is_collinear(self, other):
        value = abs(self.cos_theta(other))
        return values_are_equal(1, value)

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, other):
        return Vector(self.x * other, self.y * other)

    def __truediv__(self, other):
        return Vector(self.x / other, self.y / other)

    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)


Vector.ZERO = Vector(0, 0)

NUMBER_OF_SIGNIFICANT_DIGITS = 3
TOLERANCE = 10**-8  # Used when checking if floats are equal
FACTOR_OF_SAFETY_BUCKLING = 3
FACTOR_OF_SAFETY_YIELDING = 2
YIELD_STRESS = 350 * pq.MPa
YOUNG_MODULUS = 200000 * pq.MPa
kN = pq.UnitQuantity("kiloNewton", pq.N * 1000, "kN")
Exemplo n.º 17
0
from scipy.interpolate import interp1d
from elephant.current_source_density import icsd
import unittest

# patch quantities with the SI unit Siemens if it does not exist
for symbol, prefix, definition, u_symbol in zip(
    ['siemens', 'S', 'mS', 'uS', 'nS', 'pS'],
    ['', '', 'milli', 'micro', 'nano', 'pico'],
    [pq.A / pq.V, pq.A / pq.V, 'S', 'mS', 'uS', 'nS'],
        [None, None, None, None, u'µS', None]):
    if isinstance(definition, str):
        definition = lastdefinition / 1000
    if not hasattr(pq, symbol):
        setattr(pq, symbol, pq.UnitQuantity(
            prefix + 'siemens',
            definition,
            symbol=symbol,
            u_symbol=u_symbol))
    lastdefinition = definition


def potential_of_plane(z_j, z_i=0. * pq.m,
                       C_i=1 * pq.A / pq.m**2,
                       sigma=0.3 * pq.S / pq.m):
    '''
    Return potential of infinite horizontal plane with constant
    current source density at a vertical offset z_j.

    Arguments
    ---------
    z_j : float*pq.m
Exemplo n.º 18
0
"""
    sonde.quantities
    ~~~~~~~~~~~~~~~~

    This module contains a few custom quantities that are used
    primarily for unit conversion.
"""
from __future__ import absolute_import
import quantities as pq

#: Unit of concentration - milligrams per liter
mgl = pq.UnitQuantity('Concentration', pq.CompoundUnit("mg/L"), symbol='mg/L')

#: Unit of specific conductivity - milliSiemens per centimeter
mScm = pq.UnitQuantity('Specific Conductivity in MilliSiemens per Centimeter',
                       pq.CompoundUnit("1e-3*S/cm"),
                       symbol='mS/cm')

#: Unit of turbidity - nephelometric turbidity units
ntu = pq.UnitQuantity('Turbidity', pq.dimensionless, symbol='NTU')

#: Unit of salinity - practical salinity units
psu = pq.UnitQuantity('Salinity', pq.dimensionless, symbol='PSU')
ppt = psu

# nickname for dimensionless
dl = pq.dimensionless

#unit of speed
mps = pq.UnitQuantity('Speed', pq.m / pq.second, symbol='m/s')
Exemplo n.º 19
0
#!/Library/Frameworks/Python.framework/Versions/Current/bin/python

#  salines.py
#  
#
#  Created by Theodore Lindsay on 10/2/09.
#  Copyright (c) 2009 University of Oregon. All rights reserved.
#
"""calculate recipe for a volume of saline given the desired concentrations"""

import quantities as pq
#from psilentplib import Struct
pq.molar = pq.UnitQuantity('molar', pq.mol/pq.liter, symbol='M')

class Struct:
    """general structure class"""
    def __init__ (self, *argv, **argd):
        if len(argd):
            # Update by dictionary                                                                                            
            self.__dict__.update (argd)
        else:
            # Update by position                                                                                              
            attrs = filter (lambda x: x[0:2] != "__", dir(self))
            for n in range(len(argv)):
                setattr(self, attrs[n], argv[n])

class ion(object):
    def __init__(self,species,concentration):
        self.species = species 
        self.conc = concentration
        self.mob = mob(species)
Exemplo n.º 20
0
def getUnits():
    pq.AU = pq.UnitQuantity('arbitrary units', 1, symbol='AU')
    pq.uL = pq.UnitQuantity('microliter', 0.001 * pq.mL, symbol='uL')
    pq.nL = pq.UnitQuantity('nanoliter', 0.001 * pq.uL, symbol='nL')
    pq.pL = pq.UnitQuantity('picoliter', 0.001 * pq.nL, symbol='pL')
    pq.fL = pq.UnitQuantity('femtoliter', 0.001 * pq.pL, symbol='fL')
    pq.uM = pq.UnitQuantity('micromolar', 0.001 * pq.mM, symbol='uM')
    pq.nM = pq.UnitQuantity('nanomolar', 0.001 * pq.uM, symbol='nM')
    pq.Rgas = pq.UnitQuantity('gas constant',
                              1.987 * pq.cal / pq.Kelvin / pq.mol)
    pq.kb = pq.UnitQuantity('Boltzmann\'s constant', 1.38E-23 * pq.J / pq.K)
    pq.Cal = pq.UnitQuantity('Calorie', 1000 * pq.cal)
    pq.plank = pq.UnitQuantity('Plank\'s constant', 6.626E-34 * pq.J * pq.s)
    pq.molecule = pq.UnitQuantity('molecule',
                                  pq.mole / 6.0221409e+23,
                                  symbol='molecule')
    return pq
Exemplo n.º 21
0
            + ' please check the version number of Quantities.')
        print(
            'EGADS has imported an already installed version of Quantities. If issues occure,'
            + ' please check the version number of Quantities.')
except ImportError:
    logging.exception(
        'egads - __init__.py - EGADS couldn'
        't find quantities. Please check for a valid installation of Quantities'
        + ' or the presence of Quantities in third-party software directory.')
    raise ImportError(
        'EGADS couldn'
        't find quantities. Please check for a valid installation of Quantities'
        + ' or the presence of Quantities in third-party software directory.')

quantities.UnitQuantity('microgram',
                        quantities.gram / 1e6,
                        symbol='ug',
                        aliases=['micrograms'])
quantities.UnitQuantity('hectopascal',
                        quantities.Pa * 100,
                        symbol='hPa',
                        aliases=['hectopascals'])


def change_log_level(log_level='INFO'):
    logging.debug('egads - __init__.py - change_log_level - log_level ' +
                  log_level)
    logging.getLogger().setLevel(getattr(logging, log_level))


def set_log_options(log_level=None, log_path=None):
    logging.debug('egads - __init__.py - set_log_options - log_level ' +
Exemplo n.º 22
0
:copyright: Copyright 2006-2013 by the PyNN team, see AUTHORS.
:license: CeCILL, see LICENSE for details.
"""

import logging
import numpy
import quantities as pq
import neo
import brian
from pyNN import recording
from . import simulator

mV = brian.mV
ms = brian.ms
uS = brian.uS
pq.uS = pq.UnitQuantity('microsiemens', 1e-6 * pq.S, 'uS')

logger = logging.getLogger("PyNN")


class Recorder(recording.Recorder):
    """Encapsulates data and functions related to recording model variables."""
    _simulator = simulator

    def __init__(self, population=None, file=None):
        __doc__ = recording.Recorder.__doc__
        recording.Recorder.__init__(self, population, file)
        self._devices = {}  # defer creation until first call of record()

    def _create_device(self, group, variable):
        """Create a Brian recording device."""
Exemplo n.º 23
0
class NewportESP301Axis(object):
    """
    Encapsulates communication concerning a single axis
    of an ESP-301 controller. This class should not be
    instantiated by the user directly, but is
    returned by `NewportESP301.axis`.
    """
    # quantities micro inch
    micro_inch = pq.UnitQuantity('micro-inch', pq.inch / 1e6, symbol='uin')

    # Some more work might need to be done here to make
    # the encoder_step and motor_step functional
    # I really don't have a concrete idea how I'm
    # going to do this until I have a physical device

    _unit_dict = {
        0: pq.count,
        1: pq.count,
        2: pq.mm,
        3: pq.um,
        4: pq.inch,
        5: pq.mil,
        6: micro_inch,  # compound unit for micro-inch
        7: pq.deg,
        8: pq.grad,
        9: pq.rad,
        10: pq.mrad,
        11: pq.urad,
    }

    def __init__(self, controller, axis_id):
        if not isinstance(controller, NewportESP301):
            raise TypeError("Axis must be controlled by a Newport ESP-301 "
                            "motor controller.")

        self._controller = controller
        self._axis_id = axis_id + 1

        self._units = self.units

    # CONTEXT MANAGERS ##

    @contextmanager
    def _units_of(self, units):
        """
        Sets the units for the corresponding axis to a those given by an integer
        label (see `NewportESP301Units`), ensuring that the units are properly
        reset at the completion of the context manager.
        """
        old_units = self._get_units()
        self._set_units(units)
        yield
        self._set_units(old_units)

    # PRIVATE METHODS ##

    def _get_units(self):
        """
        Returns the integer label for the current units set for this axis.

        .. seealso::
            NewportESP301Units
        """
        return NewportESP301Units(
            int(self._newport_cmd("SN?", target=self.axis_id)))

    def _set_units(self, new_units):
        return self._newport_cmd("SN",
                                 target=self.axis_id,
                                 params=[int(new_units)])

    # PROPERTIES ##

    @property
    def axis_id(self):
        """
        Get axis number of Newport Controller

        :type: `int`
        """
        return self._axis_id

    @property
    def is_motion_done(self):
        """
        `True` if and only if all motion commands have
        completed. This method can be used to wait for
        a motion command to complete before sending the next
        command.

        :type: `bool`
        """
        return bool(int(self._newport_cmd("MD?", target=self.axis_id)))

    @property
    def acceleration(self):
        """
        Gets/sets the axis acceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :type: `~quantities.Quantity` or `float`
        """

        return assume_units(
            float(self._newport_cmd("AC?", target=self.axis_id)),
            self._units / (pq.s**2))

    @acceleration.setter
    def acceleration(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / (pq.s**2)).rescale(
                self._units / (pq.s**2)).magnitude)
        self._newport_cmd("AC", target=self.axis_id, params=[newval])

    @property
    def deceleration(self):
        """
        Gets/sets the axis deceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`
        :type: `~quantities.Quantity` or float
        """
        return assume_units(
            float(self._newport_cmd("AG?", target=self.axis_id)),
            self._units / (pq.s**2))

    @deceleration.setter
    def deceleration(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / (pq.s**2)).rescale(
                self._units / (pq.s**2)).magnitude)
        self._newport_cmd("AG", target=self.axis_id, params=[newval])

    @property
    def estop_deceleration(self):
        """
        Gets/sets the axis estop deceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`
        :type: `~quantities.Quantity` or float
        """
        return assume_units(
            float(self._newport_cmd("AE?", target=self.axis_id)),
            self._units / (pq.s**2))

    @estop_deceleration.setter
    def estop_deceleration(self, decel):
        decel = float(
            assume_units(decel, self._units / (pq.s**2)).rescale(
                self._units / (pq.s**2)).magnitude)
        self._newport_cmd("AE", target=self.axis_id, params=[decel])

    @property
    def jerk(self):
        """
        Gets/sets the jerk rate for the controller

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :type: `~quantities.Quantity` or `float`
        """

        return assume_units(
            float(self._newport_cmd("JK?", target=self.axis_id)),
            self._units / (pq.s**3))

    @jerk.setter
    def jerk(self, jerk):
        jerk = float(
            assume_units(jerk, self._units / (pq.s**3)).rescale(
                self._units / (pq.s**3)).magnitude)
        self._newport_cmd("JK", target=self.axis_id, params=[jerk])

    @property
    def velocity(self):
        """
        Gets/sets the axis velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("VA?", target=self.axis_id)),
            self._units / pq.s)

    @velocity.setter
    def velocity(self, velocity):
        velocity = float(
            assume_units(velocity, self._units / (pq.s)).rescale(
                self._units / pq.s).magnitude)
        self._newport_cmd("VA", target=self.axis_id, params=[velocity])

    @property
    def max_velocity(self):
        """
        Gets/sets the axis maximum velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("VU?", target=self.axis_id)),
            self._units / pq.s)

    @max_velocity.setter
    def max_velocity(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / pq.s).rescale(self._units /
                                                             pq.s).magnitude)
        self._newport_cmd("VU", target=self.axis_id, params=[newval])

    @property
    def max_base_velocity(self):
        """
        Gets/sets the maximum base velocity for stepper motors

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("VB?", target=self.axis_id)),
            self._units / pq.s)

    @max_base_velocity.setter
    def max_base_velocity(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / pq.s).rescale(self._units /
                                                             pq.s).magnitude)
        self._newport_cmd("VB", target=self.axis_id, params=[newval])

    @property
    def jog_high_velocity(self):
        """
        Gets/sets the axis jog high velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("JH?", target=self.axis_id)),
            self._units / pq.s)

    @jog_high_velocity.setter
    def jog_high_velocity(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / pq.s).rescale(self._units /
                                                             pq.s).magnitude)
        self._newport_cmd("JH", target=self.axis_id, params=[newval])

    @property
    def jog_low_velocity(self):
        """
        Gets/sets the axis jog low velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("JW?", target=self.axis_id)),
            self._units / pq.s)

    @jog_low_velocity.setter
    def jog_low_velocity(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / pq.s).rescale(self._units /
                                                             pq.s).magnitude)
        self._newport_cmd("JW", target=self.axis_id, params=[newval])

    @property
    def homing_velocity(self):
        """
        Gets/sets the axis homing velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("OH?", target=self.axis_id)),
            self._units / pq.s)

    @homing_velocity.setter
    def homing_velocity(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / pq.s).rescale(self._units /
                                                             pq.s).magnitude)
        self._newport_cmd("OH", target=self.axis_id, params=[newval])

    @property
    def max_acceleration(self):
        """
        Gets/sets the axis max acceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("AU?", target=self.axis_id)),
            self._units / (pq.s**2))

    @max_acceleration.setter
    def max_acceleration(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units / (pq.s**2)).rescale(
                self._units / (pq.s**2)).magnitude)
        self._newport_cmd("AU", target=self.axis_id, params=[newval])

    @property
    def max_deceleration(self):
        """
        Gets/sets the axis max decceleration.
        Max deaceleration is always the same as acceleration.

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`
        :type: `~quantities.Quantity` or `float`
        """
        return self.max_acceleration

    @max_deceleration.setter
    def max_deceleration(self, decel):
        decel = float(
            assume_units(decel, self._units / (pq.s**2)).rescale(
                self._units / (pq.s**2)).magnitude)
        self.max_acceleration = decel

    @property
    def position(self):
        """
        Gets real position on axis in units

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("TP?", target=self.axis_id)), self._units)

    @property
    def desired_position(self):
        """
        Gets desired position on axis in units

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("DP?", target=self.axis_id)), self._units)

    @property
    def desired_velocity(self):
        """
        Gets the axis desired velocity in unit/s

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit/s
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("DP?", target=self.axis_id)),
            self._units / pq.s)

    @property
    def home(self):
        """
        Gets/sets the axis home position.
        Default should be 0 as that sets current position as home

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("DH?", target=self.axis_id)), self._units)

    @home.setter
    def home(self, newval=0):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units).rescale(self._units).magnitude)
        self._newport_cmd("DH", target=self.axis_id, params=[newval])

    @property
    def units(self):
        """
        Get the units that all commands are in reference to.

        :type: `~quantities.Quantity` with units corresponding to
            units of axis connected  or int which corresponds to Newport
            unit number
        """
        self._units = self._get_pq_unit(self._get_units())
        return self._units

    @units.setter
    def units(self, newval):
        if newval is None:
            return
        if isinstance(newval, int):
            self._units = self._get_pq_unit(NewportESP301Units(int(newval)))
        elif isinstance(newval, pq.Quantity):
            self._units = newval
            newval = self._get_unit_num(newval)
        self._set_units(newval)

    @property
    def encoder_resolution(self):
        """
        Gets/sets the resolution of the encode. The minimum number of units
        per step. Encoder functionality must be enabled.

        :units: The number of units per encoder step
        :type: `~quantities.Quantity` or `float`
        """

        return assume_units(
            float(self._newport_cmd("SU?", target=self.axis_id)), self._units)

    @encoder_resolution.setter
    def encoder_resolution(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units).rescale(self._units).magnitude)
        self._newport_cmd("SU", target=self.axis_id, params=[newval])

    @property
    def full_step_resolution(self):
        """
        Gets/sets the axis resolution of the encode. The minimum number of
        units per step. Encoder functionality must be enabled.

        :units: The number of units per encoder step
        :type: `~quantities.Quantity` or `float`
        """

        return assume_units(
            float(self._newport_cmd("FR?", target=self.axis_id)), self._units)

    @full_step_resolution.setter
    def full_step_resolution(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units).rescale(self._units).magnitude)
        self._newport_cmd("FR", target=self.axis_id, params=[newval])

    @property
    def left_limit(self):
        """
        Gets/sets the axis left travel limit

        :units: The limit in units
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("SL?", target=self.axis_id)), self._units)

    @left_limit.setter
    def left_limit(self, limit):
        limit = float(
            assume_units(limit, self._units).rescale(self._units).magnitude)
        self._newport_cmd("SL", target=self.axis_id, params=[limit])

    @property
    def right_limit(self):
        """
        Gets/sets the axis right travel limit

        :units: units
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("SR?", target=self.axis_id)), self._units)

    @right_limit.setter
    def right_limit(self, limit):
        limit = float(
            assume_units(limit, self._units).rescale(self._units).magnitude)
        self._newport_cmd("SR", target=self.axis_id, params=[limit])

    @property
    def error_threshold(self):
        """
        Gets/sets the axis error threshold

        :units: units
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("FE?", target=self.axis_id)), self._units)

    @error_threshold.setter
    def error_threshold(self, newval):
        if newval is None:
            return
        newval = float(
            assume_units(newval, self._units).rescale(self._units).magnitude)
        self._newport_cmd("FE", target=self.axis_id, params=[newval])

    @property
    def current(self):
        """
        Gets/sets the axis current (amps)

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\text{A}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("QI?", target=self.axis_id)), pq.A)

    @current.setter
    def current(self, newval):
        if newval is None:
            return
        current = float(assume_units(newval, pq.A).rescale(pq.A).magnitude)
        self._newport_cmd("QI", target=self.axis_id, params=[current])

    @property
    def voltage(self):
        """
        Gets/sets the axis voltage

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\text{V}`
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(
            float(self._newport_cmd("QV?", target=self.axis_id)), pq.V)

    @voltage.setter
    def voltage(self, newval):
        if newval is None:
            return
        voltage = float(assume_units(newval, pq.V).rescale(pq.V).magnitude)
        self._newport_cmd("QV", target=self.axis_id, params=[voltage])

    @property
    def motor_type(self):
        """
        Gets/sets the axis motor type
        * 0 = undefined
        * 1 = DC Servo
        * 2 = Stepper motor
        * 3 = commutated stepper motor
        * 4 = commutated brushless servo motor

        :type: `int`
        :rtype: `NewportESP301MotorType`
        """
        return NewportESP301MotorType(
            int(self._newport_cmd("QM?", target=self._axis_id)))

    @motor_type.setter
    def motor_type(self, newval):
        if newval is None:
            return
        self._newport_cmd("QM", target=self._axis_id, params=[int(newval)])

    @property
    def feedback_configuration(self):
        """
        Gets/sets the axis Feedback configuration

        :type: `int`
        """
        return int(self._newport_cmd("ZB?", target=self._axis_id)[:-2], 16)

    @feedback_configuration.setter
    def feedback_configuration(self, newval):
        if newval is None:
            return
        self._newport_cmd("ZB", target=self._axis_id, params=[int(newval)])

    @property
    def position_display_resolution(self):
        """
        Gets/sets the position display resolution

        :type: `int`
        """
        return int(self._newport_cmd("FP?", target=self._axis_id))

    @position_display_resolution.setter
    def position_display_resolution(self, newval):
        if newval is None:
            return
        self._newport_cmd("FP", target=self._axis_id, params=[int(newval)])

    @property
    def trajectory(self):
        """
        Gets/sets the axis trajectory

        :type: `int`
        """
        return int(self._newport_cmd("TJ?", target=self._axis_id))

    @trajectory.setter
    def trajectory(self, newval):
        if newval is None:
            return
        self._newport_cmd("TJ", target=self._axis_id, params=[int(newval)])

    @property
    def microstep_factor(self):
        """
        Gets/sets the axis microstep_factor

        :type: `int`
        """
        return int(self._newport_cmd("QS?", target=self._axis_id))

    @microstep_factor.setter
    def microstep_factor(self, newval):
        if newval is None:
            return
        newval = int(newval)
        if newval < 1 or newval > 250:
            raise ValueError("Microstep factor must be between 1 and 250")
        else:
            self._newport_cmd("QS", target=self._axis_id, params=[newval])

    @property
    def hardware_limit_configuration(self):
        """
        Gets/sets the axis hardware_limit_configuration

        :type: `int`
        """
        return int(self._newport_cmd("ZH?", target=self._axis_id)[:-2])

    @hardware_limit_configuration.setter
    def hardware_limit_configuration(self, newval):
        if newval is None:
            return
        self._newport_cmd("ZH", target=self._axis_id, params=[int(newval)])

    @property
    def acceleration_feed_forward(self):
        """
        Gets/sets the axis acceleration_feed_forward setting

        :type: `int`
        """
        return float(self._newport_cmd("AF?", target=self._axis_id))

    @acceleration_feed_forward.setter
    def acceleration_feed_forward(self, newval):
        if newval is None:
            return
        self._newport_cmd("AF", target=self._axis_id, params=[float(newval)])

    @property
    def proportional_gain(self):
        """
        Gets/sets the axis proportional_gain

        :type: `float`
        """
        return float(self._newport_cmd("KP?", target=self._axis_id)[:-1])

    @proportional_gain.setter
    def proportional_gain(self, newval):
        if newval is None:
            return
        self._newport_cmd("KP", target=self._axis_id, params=[float(newval)])

    @property
    def derivative_gain(self):
        """
        Gets/sets the axis derivative_gain

        :type: `float`
        """
        return float(self._newport_cmd("KD?", target=self._axis_id))

    @derivative_gain.setter
    def derivative_gain(self, newval):
        if newval is None:
            return
        self._newport_cmd("KD", target=self._axis_id, params=[float(newval)])

    @property
    def integral_gain(self):
        """
        Gets/sets the axis integral_gain

        :type: `float`
        """
        return float(self._newport_cmd("KI?", target=self._axis_id))

    @integral_gain.setter
    def integral_gain(self, newval):
        if newval is None:
            return
        self._newport_cmd("KI", target=self._axis_id, params=[float(newval)])

    @property
    def integral_saturation_gain(self):
        """
        Gets/sets the axis integral_saturation_gain

        :type: `float`
        """
        return float(self._newport_cmd("KS?", target=self._axis_id))

    @integral_saturation_gain.setter
    def integral_saturation_gain(self, newval):
        if newval is None:
            return
        self._newport_cmd("KS", target=self._axis_id, params=[float(newval)])

    @property
    def encoder_position(self):
        """
        Gets the encoder position

        :type:
        """
        with self._units_of(NewportESP301Units.encoder_step):
            return self.position

    # MOVEMENT METHODS #

    def search_for_home(
            self,
            search_mode=NewportESP301HomeSearchMode.zero_position_count.value):
        """
        Searches this axis only
        for home using the method specified by ``search_mode``.

        :param NewportESP301HomeSearchMode search_mode: Method to detect when
            Home has been found.
        """
        self._controller.search_for_home(axis=self.axis_id,
                                         search_mode=search_mode)

    def move(self, position, absolute=True, wait=False, block=False):
        """
        :param position: Position to set move to along this axis.
        :type position: `float` or :class:`~quantities.Quantity`
        :param bool absolute: If `True`, the position ``pos`` is
            interpreted as relative to the zero-point of the encoder.
            If `False`, ``pos`` is interpreted as relative to the current
            position of this axis.
        :param bool wait: If True, will tell axis to not execute other
            commands until movement is finished
        :param bool block: If True, will block code until movement is finished
        """
        position = float(
            assume_units(position, self._units).rescale(self._units).magnitude)
        if absolute:
            self._newport_cmd("PA", params=[position], target=self.axis_id)
        else:
            self._newport_cmd("PR", params=[position], target=self.axis_id)

        if wait:
            self.wait_for_position(position)
            if block:
                sleep(0.003)
                mot = self.is_motion_done
                while not mot:
                    mot = self.is_motion_done

    def move_to_hardware_limit(self):
        """
        move to hardware travel limit
        """
        self._newport_cmd("MT", target=self.axis_id)

    def move_indefinitely(self):
        """
        Move until told to stop
        """
        self._newport_cmd("MV", target=self.axis_id)

    def abort_motion(self):
        """
        Abort motion
        """
        self._newport_cmd("AB", target=self.axis_id)

    def wait_for_stop(self):
        """
        Waits for axis motion to stop before next command is executed
        """
        self._newport_cmd("WS", target=self.axis_id)

    def stop_motion(self):
        """
        Stop all motion on axis. With programmed deceleration rate
        """
        try:
            self._newport_cmd("ST", target=self.axis_id)
        except NewportError as e:
            raise NewportError(e)

    def wait_for_position(self, position):
        """
        Wait for axis to reach position before executing next command

        :param position: Position to wait for on axis

        :type position: float or :class:`~quantities.Quantity`
        """
        position = float(
            assume_units(position, self._units).rescale(self._units).magnitude)
        self._newport_cmd("WP", target=self.axis_id, params=[position])

    def wait_for_motion(self, poll_interval=0.01, max_wait=None):
        """
        Blocks until all movement along this axis is complete, as reported
        by `~NewportESP301Axis.is_motion_done`.

        :param float poll_interval: How long (in seconds) to sleep between
            checking if the motion is complete.
        :param float max_wait: Maximum amount of time to wait before
            raising a `IOError`. If `None`, this method will wait
            indefinitely.
        """
        # FIXME: make sure that the controller is not in
        #        programming mode, or else this might not work.
        #        In programming mode, the "WS" command should be
        #        sent instead, and the two parameters to this method should
        #        be ignored.
        poll_interval = float(
            assume_units(poll_interval, pq.s).rescale(pq.s).magnitude)
        max_wait = float(assume_units(max_wait, pq.s).rescale(pq.s).magnitude)
        tic = time()
        while True:
            if self.is_motion_done:
                return
            else:
                if max_wait is None or (time() - tic) < max_wait:
                    sleep(poll_interval)
                else:
                    raise IOError("Timed out waiting for motion to finish.")

    def enable(self):
        """
        Turns motor axis on.
        """
        self._newport_cmd("MO", target=self._axis_id)

    def disable(self):
        """
        Turns motor axis off.
        """
        self._newport_cmd("MF", target=self._axis_id)

    def setup_axis(self, **kwargs):
        """
        Setup a non-newport DC servo motor stage. Necessary parameters are.

        * 'motor_type' = type of motor see 'QM' in Newport documentation
        * 'current' = motor maximum current (A)
        * 'voltage' = motor voltage (V)
        * 'units' = set units (see NewportESP301Units)(U)
        * 'encoder_resolution' = value of encoder step in terms of (U)
        * 'max_velocity' = maximum velocity (U/s)
        * 'max_base_velocity' =  maximum working velocity (U/s)
        * 'homing_velocity' = homing speed (U/s)
        * 'jog_high_velocity' = jog high speed (U/s)
        * 'jog_low_velocity' = jog low speed (U/s)
        * 'max_acceleration' = maximum acceleration (U/s^2)
        * 'acceleration' = acceleration (U/s^2)
        * 'deceleration' = set deceleration (U/s^2)
        * 'error_threshold' = set error threshold (U)
        * 'proportional_gain' = PID proportional gain (optional)
        * 'derivative_gain' = PID derivative gain (optional)
        * 'interal_gain' = PID internal gain (optional)
        * 'integral_saturation_gain' = PID integral saturation (optional)
        * 'trajectory' = trajectory mode (optional)
        * 'position_display_resolution' (U per step)
        * 'feedback_configuration'
        * 'full_step_resolution'  = (U per step)
        * 'home' = (U)
        * 'acceleration_feed_forward' = bewtween 0 to 2e9
        * 'reduce_motor_torque' =  (time(ms),percentage)
        """

        self.motor_type = kwargs.get('motor_type')
        self.feedback_configuration = kwargs.get('feedback_configuration')
        self.full_step_resolution = kwargs.get('full_step_resolution')
        self.position_display_resolution = kwargs.get('position_display_'
                                                      'resolution')
        self.current = kwargs.get('current')
        self.voltage = kwargs.get('voltage')
        self.units = int(kwargs.get('units'))
        self.encoder_resolution = kwargs.get('encoder_resolution')
        self.max_acceleration = kwargs.get('max_acceleration')
        self.max_velocity = kwargs.get('max_velocity')
        self.max_base_velocity = kwargs.get('max_base_velocity')
        self.homing_velocity = kwargs.get('homing_velocity')
        self.jog_high_velocity = kwargs.get('jog_high_velocity')
        self.jog_low_velocity = kwargs.get('jog_low_velocity')
        self.acceleration = kwargs.get('acceleration')
        self.velocity = kwargs.get('velocity')
        self.deceleration = kwargs.get('deceleration')
        self.estop_deceleration = kwargs.get('estop_deceleration')
        self.jerk = kwargs.get('jerk')
        self.error_threshold = kwargs.get('error_threshold')
        self.proportional_gain = kwargs.get('proportional_gain')
        self.derivative_gain = kwargs.get('derivative_gain')
        self.integral_gain = kwargs.get('integral_gain')
        self.integral_saturation_gain = kwargs.get('integral_saturation_gain')
        self.home = kwargs.get('home')
        self.microstep_factor = kwargs.get('microstep_factor')
        self.acceleration_feed_forward = kwargs.get(
            'acceleration_feed_forward')
        self.trajectory = kwargs.get('trajectory')
        self.hardware_limit_configuration = kwargs.get('hardware_limit_'
                                                       'configuration')
        if 'reduce_motor_torque_time' in kwargs and 'reduce_motor_torque_percentage' in kwargs:
            motor_time = kwargs['reduce_motor_torque_time']
            motor_time = int(
                assume_units(motor_time, pq.ms).rescale(pq.ms).magnitude)
            if motor_time < 0 or motor_time > 60000:
                raise ValueError("Time must be between 0 and 60000 ms")
            percentage = kwargs['reduce_motor_torque_percentage']
            percentage = int(
                assume_units(percentage,
                             pq.percent).rescale(pq.percent).magnitude)
            if percentage < 0 or percentage > 100:
                raise ValueError("Time must be between 0 and 60000 ms")
            self._newport_cmd("QR",
                              target=self._axis_id,
                              params=[motor_time, percentage])

        # update motor configuration
        self._newport_cmd("UF", target=self._axis_id)
        self._newport_cmd("QD", target=self._axis_id)
        # save configuration
        self._newport_cmd("SM")
        return self.read_setup()

    def read_setup(self):
        """
        Returns dictionary containing:
            'units'
            'motor_type'
            'feedback_configuration'
            'full_step_resolution'
            'position_display_resolution'
            'current'
            'max_velocity'
            'encoder_resolution'
            'acceleration'
            'deceleration'
            'velocity'
            'max_acceleration'
            'homing_velocity'
            'jog_high_velocity'
            'jog_low_velocity'
            'estop_deceleration'
            'jerk'
            'proportional_gain'
            'derivative_gain'
            'integral_gain'
            'integral_saturation_gain'
            'home'
            'microstep_factor'
            'acceleration_feed_forward'
            'trajectory'
            'hardware_limit_configuration'

        :rtype: dict of `quantities.Quantity`, float and int
        """

        config = dict()
        config['units'] = self.units
        config['motor_type'] = self.motor_type
        config['feedback_configuration'] = self.feedback_configuration
        config['full_step_resolution'] = self.full_step_resolution
        config[
            'position_display_resolution'] = self.position_display_resolution
        config['current'] = self.current
        config['max_velocity'] = self.max_velocity
        config['encoder_resolution'] = self.encoder_resolution
        config['acceleration'] = self.acceleration
        config['deceleration'] = self.deceleration
        config['velocity'] = self.velocity
        config['max_acceleration'] = self.max_acceleration
        config['homing_velocity'] = self.homing_velocity
        config['jog_high_velocity'] = self.jog_high_velocity
        config['jog_low_velocity'] = self.jog_low_velocity
        config['estop_deceleration'] = self.estop_deceleration
        config['jerk'] = self.jerk
        # config['error_threshold'] = self.error_threshold
        config['proportional_gain'] = self.proportional_gain
        config['derivative_gain'] = self.derivative_gain
        config['integral_gain'] = self.integral_gain
        config['integral_saturation_gain'] = self.integral_saturation_gain
        config['home'] = self.home
        config['microstep_factor'] = self.microstep_factor
        config['acceleration_feed_forward'] = self.acceleration_feed_forward
        config['trajectory'] = self.trajectory
        config[
            'hardware_limit_configuration'] = self.hardware_limit_configuration
        return config

    def get_status(self):
        """
        Returns Dictionary containing values:
            'units'
            'position'
            'desired_position'
            'desired_velocity'
            'is_motion_done'

        :rtype: dict
        """
        status = dict()
        status['units'] = self.units
        status['position'] = self.position
        status['desired_position'] = self.desired_position
        status['desired_velocity'] = self.desired_velocity
        status['is_motion_done'] = self.is_motion_done

        return status

    @staticmethod
    def _get_pq_unit(num):
        """
        Gets the units for the specified axis.

        :units: The units for the attached axis
        :type num: int
        """
        return NewportESP301Axis._unit_dict[num]

    def _get_unit_num(self, quantity):
        """
        Gets the integer label used by the Newport ESP 301 corresponding to a
        given `~quantities.Quantity`.

        :param quantities.Quantity quantity: Units to return a label for.

        :return int:
        """
        for num, quant in self._unit_dict.items():
            if quant == quantity:
                return num

        raise KeyError(
            "{0} is not a valid unit for Newport Axis".format(quantity))

    # pylint: disable=protected-access
    def _newport_cmd(self, cmd, **kwargs):
        """
        Passes the newport command from the axis class to the parent controller

        :param cmd:
        :param kwargs:
        :return:
        """
        return self._controller._newport_cmd(cmd, **kwargs)
Exemplo n.º 24
0
# 3. CHILLED WATER
# 3. 1. Measured Chilled water
df['measured_chilled_water_AH2'] = df['measured_chw']

#m_chwp = np.zeros((N,2)) 
#m_chwp_cost = np.empty((N,2))
#chwt = np.array(power_cost['measured_chw']['Readings'])
#
#m_chwp[:,0] = chwt[:,0]
#m_chwp[:,1] = chwt[:,1] * 3.517 / chw_eff
#m_chwp_cost[:,0] = chwt[:,0]
#m_chwp_cost[:,1] = np.array([m_chwp[i,1] * elec_price[i,1] \
#                             for i in range(N)])

# 3. 2. Calculate chilled water cost
cfm = pq.UnitQuantity('cfm', pq.foot**3/pq.minute, symbol='cfm')
df['chilled_water_AH2'] = np.nan
df['hot_water_AH2'] = np.nan 
df['total_zone_load_AH2'] = np.nan
df['total_VAV_box_airflow'] = np.nan 
#for rh_name in rh_coils:
#  df_zone['coil_closed_temp_change_' + rh_name] = np.nan
#  df_zone['hot_water_' +rh_name] = np.nan
#  df_zone['instantaneous_zone_load_' + rh_name] = np.nan

for i in range(9, df.shape[0]):
  chw_AH2 =  0.0 * pq.W
  all_sats = []*pq.F
  for coil_name in chw_coils:
    mat = np.array(df[str(coil_name) + '_MAT'][i-9:i+1]) * pq.F
    sat = np.array(df[str(coil_name) + '_SAT'][i-9:i+1]) * pq.F
Exemplo n.º 25
0
###############################
""" Physical quantities. 


    Holds things related to physical quantities, eg atomic units using the
    *quantities* package.
"""
__docformat__ = "restructuredtext en"
__all__ = [
    'a0', 'bohr_radius', 'h', 'planck', 'h_bar', 'reduced_planck',
    'electronic_mass', 'Ry', 'rydberg', 'Kb', 'boltzmann'
]

import quantities as pq

h = pq.UnitQuantity("planck", 4.1356673310e-15 * pq.eV * pq.s)
""" Planck's constant. """
planck = h
""" Planck's constant. """
h_bar = pq.UnitQuantity("h_bar", h / 2e0 / pq.pi, symbol='h_bar')
""" Reduced Planck's constant. """
reduced_plank = h_bar
""" Reduced Planck's constant. """

Ry = pq.UnitQuantity('Rydberg', 0.5 * pq.hartree, symbol='Ry')
""" Rydberg energy units. """
rydberg = Ry
""" Rydberg energy units. """

a0 = pq.UnitQuantity('bohr_radius', 0.529177249 * pq.angstrom, symbol='a0')
""" Bohr radius, unit of length of atomic units. """
Exemplo n.º 26
0
# constants
YEAR = 2013 * pq.year
_DIRNAME = os.path.dirname(__file__)
_DATA = os.path.join(_DIRNAME, '..', 'data')
_FORMULAS = os.path.join(_DIRNAME, '..', 'formulas')
_CALCS = os.path.join(_DIRNAME, '..', 'calcs')
_MODELS = os.path.join(_DIRNAME, '..', 'models')
_OUTPUTS = os.path.join(_DIRNAME, '..', 'outputs')
_SIMULATIONS = os.path.join(_DIRNAME, '..', 'simulations')

# add extra units to registry
UREG = pq.unit_registry  # registry of units
LUMEN = pq.UnitLuminousIntensity('lumen', pq.cd * pq.sr, 'lm',
                                 aliases=['lumens'])
LUX = pq.UnitLuminousIntensity('lux', LUMEN / pq.m ** 2, 'lx')
MB = pq.UnitQuantity('millibar', pq.milli * pq.bar, 'mB',
                     aliases=['mBar', 'mb', 'mbar', 'millibars'])
FA = pq.UnitQuantity('femtoampere', pq.femto * pq.ampere, 'fA',
                     aliases=['femtoamp', 'femtoAmp', 'femtoamps', 'femtoAmps',
                              'femtoamperes', 'femtoAmpere', 'femtoAmperes',
                              'fAmp', 'fAmps'])


def _listify(x):
    """
    If x is not a list, make it a list.
    """
    return list(x) if isinstance(x, (list, tuple)) else [x]


class Registry(dict):
    """
Exemplo n.º 27
0
    def calculate_score(self, simulation_result, score_instance):
        model_class = general_hlp.import_class(
            score_instance.model_instance.model_class.import_path)

        model_url = score_instance.model_instance.url
        model_name = os.path.basename(model_url)
        model_path = os.path.join(settings.DOWNLOADED_MODEL_DIR, model_name)

        model_hlp.download_and_save_model(model_path, model_url)

        model_instance = model_class(model_path,
                                     name=score_instance.model_instance.name,
                                     backend=ScidashCacheBackend.name)

        model_instance.set_memory_cache(simulation_result)

        test_class = general_hlp.import_class(
            score_instance.test_instance.test_class.import_path)

        observation = copy.deepcopy(score_instance.test_instance.observation)
        params = copy.deepcopy(score_instance.test_instance.params)

        try:
            destructured = json.loads(
                score_instance.test_instance.test_class.units)
        except json.JSONDecodeError:
            units = general_hlp.import_class(
                score_instance.test_instance.test_class.units)
        else:
            if destructured.get('name', False):
                base_unit = general_hlp.import_class(
                    destructured.get('base').get('quantity'))
                units = pq.UnitQuantity(
                    destructured.get('name'),
                    base_unit * destructured.get('base').get('coefficient'),
                    destructured.get('symbol'))
            else:
                units = destructured

        for key in observation:
            if not isinstance(units, dict):
                observation[key] = int(
                    observation[key]) * units if key != 'n' else int(
                        observation[key])
            else:
                observation[key] = int(
                    observation[key]) * units[key] if key != 'n' else int(
                        observation[key])

        params_units = score_instance.test_instance.test_class.params_units

        for key in params_units:
            params_units[key] = general_hlp.import_class(params_units[key])

        processed_params = {}

        for key in params:
            if params[key] is not None:
                processed_params[key] = float(params[key]) * params_units[key]

        test_instance = test_class(observation=observation, **processed_params)

        score = test_instance.judge(model_instance).json(add_props=True,
                                                         string=False)

        self.update_score(score_instance, score)

        return score
Exemplo n.º 28
0
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------

import quantities as pq

# Conductances:
mS = pq.UnitQuantity('milli-Siemen', pq.milli * pq.siemens, symbol='mS')
uS = pq.UnitQuantity('micro-Siemen', pq.micro * pq.siemens, symbol='uS')
nS = pq.UnitQuantity('nano-Siemen', pq.nano * pq.siemens, symbol='nS')
pS = pq.UnitQuantity('pico-Siemen', pq.pico * pq.siemens, symbol='pS')

# Capacitances:
mF = pq.UnitQuantity('millifarad', pq.milli * pq.farad, symbol='mF')
uF = pq.UnitQuantity('microfarad', pq.micro * pq.farad, symbol='uF')
nF = pq.UnitQuantity('nanofarad', pq.nano * pq.farad, symbol='nF')
pF = pq.UnitQuantity('picofarad', pq.pico * pq.farad, symbol='pF')

# Areas:
um2 = pq.UnitQuantity('micrometer-squared', pq.um ** 2, symbol='um2')
cm2 = pq.UnitQuantity('centimeter-squared', pq.cm ** 2, symbol='cm2')
mm2 = pq.UnitQuantity('micrometer-squared', pq.mm ** 2, symbol='mm2')
m2 = pq.UnitQuantity('meter-squared', pq.m ** 2, symbol='m2')
Exemplo n.º 29
0
import cython
import numpy as np
import quantities as pq

import rmgpy.constants as constants
from rmgpy.exceptions import QuantityError
from rmgpy.rmgobject import RMGObject, expand_to_dict

################################################################################

# Explicitly set the default units to SI
pq.set_default_units('si')

# These units are not defined by the quantities package, but occur frequently
# in data handled by RMG, so we define them manually
pq.UnitQuantity('kilocalories', pq.cal * 1e3, symbol='kcal')
pq.UnitQuantity('kilojoules', pq.J * 1e3, symbol='kJ')
pq.UnitQuantity('kilomoles', pq.mol * 1e3, symbol='kmol')
pq.UnitQuantity('molecule', pq.mol / 6.02214179e23, symbol='molecule')
pq.UnitQuantity('molecules', pq.mol / 6.02214179e23, symbol='molecules')
pq.UnitQuantity('debye', 1.0 / (constants.c * 1e21) * pq.C * pq.m, symbol='De')

################################################################################

# Units that should not be used in RMG-Py:
NOT_IMPLEMENTED_UNITS = ['degC', 'C', 'degF', 'F', 'degR', 'R']

################################################################################


class Units(RMGObject):
Exemplo n.º 30
0
class NewportESP301Axis(object):
    """
    Encapsulates communication concerning a single axis
    of an ESP-301 controller. This class should not be
    instantiated by the user directly, but is
    returned by `NewportESP301.axis`.
    """
    # quantities micro inch
    micro_inch = pq.UnitQuantity('micro-inch',pq.inch/1e6, symbol = 'uin')
    
    # Some more work might need to be done here to make
    # the encoder_step and motor_step functional
    # I really don't have a concrete idea how I'm 
    # going to do this until I have a physical device

    _unit_dict = {
                0    :  pq.count,
                1    :  pq.count,
                2    :  pq.mm,
                3    :  pq.um,
                4    :  pq.inch,
                5    :  pq.mil,
                6    :  micro_inch, #compound unit for micro-inch
                7    :  pq.deg,
                8    :  pq.grad,
                9    :  pq.rad,
                10   :  pq.mrad,
                11   :  pq.urad,
                } 


    def __init__(self, controller, axis_id):
        if not isinstance(controller, NewportESP301):
            raise TypeError("Axis must be controlled by a Newport ESP-301 motor controller.")

        # TODO: check axis_id
        
        self._controller = controller
        self._axis_id = axis_id

        self._units = self.units
        
    ## CONTEXT MANAGERS ##
    
    @contextmanager
    def _units_of(self, units):
        """
        Sets the units for the corresponding axis to a those given by an integer
        label (see `NewportESP301Units`), ensuring that the units are properly
        reset at the completion of the context manager.
        """
        old_units = self._get_units()
        self._set_units(units)
        yield
        self._set_units(old_units)
        
    ## PRIVATE METHODS ##
    
    def _get_units(self):
        """
        Returns the integer label for the current units set for this axis.
        
        .. seealso::
            NewportESP301Units
        """
        return NewportESP301Units(
            self._controller._newport_cmd("SN?", target=self.axis_id)
        )
        
    def _set_units(self, new_units):
        return self._controller._newport_cmd(
            "SN", target=self.axis_id,
            params=[int(new_units)]
        )
        
    ## PROPERTIES ##
    
    @property
    def axis_id(self):
        """
        Get axis number of Newport Controller

        :type: `int`
        """
        return self._axis_id
    
    @property
    def is_motion_done(self):
        """
        `True` if and only if all motion commands have
        completed. This method can be used to wait for
        a motion command to complete before sending the next
        command.

        :type: `bool`
        """
        return bool(int(self._controller._newport_cmd("MD?", target=self.axis_id)))
        
    @property
    def acceleration(self):
        """
        Get acceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :param accel: Sets acceleration
        :type accel: `~quantities.Quantity` or `float`
        
        """
        
        return assume_units(float(self._controller._newport_cmd("AC?", target=self.axis_id)),
                self._units/(pq.s**2))    
    @acceleration.setter
    def acceleration(self,accel):
        accel = float(assume_units(accel,self._units/(pq.s**2)).rescale(
                self._units/(pq.s**2)).magnitude)
        return self._controller._newport_cmd("AC",target=self.axis_id,params=[accel])
   
    @property
    def deceleration(self):
        """
        Gets deceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`
        :param decel: Sets deceleration 
        :type decel: `~quantities.Quantity` or float
        """
        return assume_units(float(self._controller._newport_cmd("AG?", target=self.axis_id)),
                self._units/(pq.s**2))
    @deceleration.setter
    def deceleration(self,decel):
        decel = float(assume_units(decel,self._units/(pq.s**2)).rescale(
                self._units/(pq.s**2)).magnitude)
        return self._controller._newport_cmd("AG",target=self.axis_id,params=[decel])
    
    @property
    def estop_deceleration(self):
        """
        Gets estop_deceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`
        :param decel: Sets deceleration 
        :type decel: `~quantities.Quantity` or float
        """
        return assume_units(float(self._controller._newport_cmd("AE?", target=self.axis_id)),
                self._units/(pq.s**2))
    @estop_deceleration.setter
    def estop_deceleration(self,decel):
        decel = float(assume_units(decel,self._units/(pq.s**2)).rescale(
                self._units/(pq.s**2)).magnitude)
        return self._controller._newport_cmd("AE",target=self.axis_id,params=[decel])
   
    @property
    def jerk(self):
        """
        Gets and sets the jerk rate for the controller

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :param accel: Sets acceleration
        :type accel: `~quantities.Quantity` or `float`
        
        """
        
        return assume_units(float(self._controller._newport_cmd("JK?", target=self.axis_id)),
                self._units/(pq.s**3))    
    @jerk.setter
    def jerk(self,jerk):
        jerk = float(assume_units(jerk,self._units/(pq.s**3)).rescale(
                self._units/(pq.s**3)).magnitude)
        return self._controller._newport_cmd("JK",target=self.axis_id,params=[jerk])

    @property
    def velocity(self):
        """
        Gets velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :param velocity: Sets velocity
        :type velocity: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("VA?", target=self.axis_id)),
                self._units/(pq.s))
    @velocity.setter
    def velocity(self,velocity):
        velocity = float(assume_units(velocity,self._units/(pq.s)).rescale(
                self._units/(pq.s)).magnitude)
        return self._controller._newport_cmd("VA",target=self.axis_id,params=[velocity])

    @property
    def max_velocity(self):
        """
        Get the maximum velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :param velocity: Sets the maximum velocity
        :type velocity: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("VU?", target=self.axis_id)),
                self._units/pq.s)
    @max_velocity.setter
    def max_velocity(self,velocity):
        velocity = float(assume_units(velocity,self._units/(pq.s)).rescale(
                self._units/(pq.s)).magnitude)
        return self._controller._newport_cmd("VU", target=self.axis_id,params=[velocity])
    
    @property
    def max_base_velocity(self):
        """
        Get the maximum base velocity for stepper motors

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :param velocity: Sets the maximum velocity
        :type velocity: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("VB?", target=self.axis_id)),
                self._units/pq.s)
    @max_base_velocity.setter
    def max_base_velocity(self,velocity):
        velocity = float(assume_units(velocity,self._units/(pq.s)).rescale(
                self._units/(pq.s)).magnitude)
        return self._controller._newport_cmd("VB", target=self.axis_id,params=[velocity])
    
    @property
    def jog_high_velocity(self):
        """
        Gets and sets jog high velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :param jog_high_velocity: Sets velocity
        :type jog_high_velocity: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("JH?", target=self.axis_id)),
                self._units/(pq.s))
    @jog_high_velocity.setter
    def jog_high_velocity(self,jog_high_velocity):
        jog_high_velocity = float(assume_units(jog_high_velocity,self._units/(pq.s)).rescale(
                self._units/(pq.s)).magnitude)
        return self._controller._newport_cmd("JH",target=self.axis_id,params=[jog_high_velocity])

    @property
    def jog_low_velocity(self):
        """
        Gets and sets jog low velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :param jog_low_velocity: Sets velocity
        :type jog_low_velocity: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("JW?", target=self.axis_id)),
                self._units/(pq.s))
    @jog_low_velocity.setter
    def jog_low_velocity(self,jog_low_velocity):
        jog_low_velocity = float(assume_units(jog_low_velocity,self._units/(pq.s)).rescale(
                self._units/(pq.s)).magnitude)
        return self._controller._newport_cmd("JW",target=self.axis_id,params=[jog_low_velocity])

    @property
    def homing_velocity(self):
        """
        Gets and sets the homing velocity

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s}`
        :param homing_velocity: Sets velocity
        :type homing_velocity: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("OH?", target=self.axis_id)),
                self._units/(pq.s))
    @homing_velocity.setter
    def homing_velocity(self,homing_velocity):
        homing_velocity = float(assume_units(homing_velocity,self._units/(pq.s)).rescale(
                self._units/(pq.s)).magnitude)
        return self._controller._newport_cmd("OH",target=self.axis_id,params=[homing_velocity])

    @property
    def max_acceleration(self):
        """
        Get max acceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`

        :param accel: Sets the maximum acceleration
        :type accel: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("AU?", target=self.axis_id)),
                self._units/(pq.s**2))
    @max_acceleration.setter
    def max_acceleration(self,accel):
        accel = float(assume_units(accel,self._units/(pq.s**2)).rescale(
                self._units/(pq.s**2)).magnitude)
        return self._controller._newport_cmd("AU",target=self.axis_id,params=[accel])

    # Max deacceleration is always the same as accelleration 
    @property
    def max_deceleration(self):
        """
        Get max deceleration

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport :math:`\\frac{unit}{s^2}`
        :param decel: Sets maximum deceleration
        :type: `~quantities.Quantity` or `float`
        """
        return self.max_acceleration
    @max_deceleration.setter
    def max_deacceleration(self,decel):        
        decel = float(assume_units(decel,self._units/(pq.s**2)).rescale(
                self._units/(pq.s**2)).magnitude)
        return self.max_acceleration(decel)
    
    @property
    def position(self):
        """
        Gets real position on axis in units

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("TP?", target=self.axis_id)),
                self._units)
    @property
    def desired_position(self):
        """
        Gets desired position on axis in units

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("DP?", target=self.axis_id)),
                self._units)
    @property
    def desired_velocity(self):
        """
        Gets desired velocity on axis in unit/s

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit/s
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("DP?", target=self.axis_id)),
                self._units/pq.s)
    
    @property
    def home(self):
        """
        Get home position

        :units: As specified (if a `~quantities.Quantity`) or assumed to be
            of current newport unit
        :param home: Sets home position of axis
        :type home: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("DH?", target=self.axis_id)),
                self._units)
    #default should be 0 as that sets current position as home
    @home.setter
    def home(self, home=0):
        home = float(assume_units(home,self._units).rescale(
                self._units).magnitude)
        return self._controller._newport_cmd("DH", target=self.axis_id, params=[home])
    
    @property
    def units(self):
        """
        Get the units that all commands are in reference to. 

        :param unit: Set the reference unit for axis

        :type unit: `~quantities.Quantity` with units corresponding to 
            units of axis connected  or int which corresponds to Newport 
            unit number 
        :rtype: `~quantities.Quantity`

        """
        self._units = self.get_pq_unit(self._get_units())
        return self._units
        
    @units.setter
    def units(self,unit):
        if isinstance(unit, int):
            self._units = self.get_pq_unit(NewportESP301Units(int(unit)))
        elif isinstance(unit,pq.Quantity):
            self._units = unit
            unit = self.get_unit_num(unit)

        return self._set_units(unit)

    @property
    def encoder_resolution(self):
        """
        Get the resolution of the encode. The minimum number of units per step. 
        Encoder functionality must be enabled

        :units: The number of units per encoder step
        :param resolution: Sets the encoder resolution of axis
        :type resolution: `~quantities.Quantity` or `float`
        """

        return assume_units(float(self._controller._newport_cmd("SU?",target=self.axis_id)),
                self._units)
    @encoder_resolution.setter
    def encoder_resolution(self, resolution):
        
        resolution = float(assume_units(resolution,self._units).rescale(
                self._units).magnitude)
        return self._controller._newport_cmd("SU",target=self.axis_id,params=[resolution])

    @property
    def full_step_resolution(self):
        """
        Get the resolution of the encode. The minimum number of units per step. 
        Encoder functionality must be enabled

        :units: The number of units per encoder step
        :param full_step_resolution: Sets the encoder resolution of axis
        :type full_step_resolution: `~quantities.Quantity` or `float`
        """

        return assume_units(float(self._controller._newport_cmd("FR?",target=self.axis_id)),
                self._units)
    @full_step_resolution.setter
    def full_step_resolution(self, full_step_resolution):
        
        full_step_resolution = float(assume_units(full_step_resolution,self._units).rescale(
                self._units).magnitude)
        return self._controller._newport_cmd("FR",target=self.axis_id,params=[full_step_resolution])
    
    @property
    def left_limit(self):
        """
        Get the left travel limit

        :units: The limit in units
        :param limit: Set the travel limit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("SL?",target=self.axis_id)),
                self._units)
    @left_limit.setter
    def left_limit(self, limit):
        limit = float(assume_units(limit,self._units).rescale(
                self._units).magnitude)
        return self._controller._newport_cmd("SL",target=self.axis_id,params=[limit])    

    @property
    def right_limit(self):
        """
        Get the right travel limit

        :units: units
        :param limit: Set the travel limit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("SR?",target=self.axis_id)),
                self._units)
    @right_limit.setter
    def right_limit(self, limit):
        limit = float(assume_units(limit,self._units).rescale(
            self._units).magnitude)
        return self._controller._newport_cmd("SR",target=self.axis_id,params=[limit])
    
    @property
    def error_threshold(self):
        """
        Get and set the error threshold 

        :units: units
        :param error_threshold: Set the travel limit
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("FE?",target=self.axis_id)),
                self._units)
    @error_threshold.setter
    def error_threshold(self, error_threshold):
        error_threshold = float(assume_units(error_threshold,self._units).rescale(
            self._units).magnitude)
        return self._controller._newport_cmd("FE",target=self.axis_id,params=[error_threshold])

    @property
    def current(self):
        """
        Get and set the current

        :units: A
        :param current: Set the current
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("QI?",target=self.axis_id)),
                pq.A)
    @current.setter
    def current(self, current):
        current = float(assume_units(current,pq.A).rescale(
            pq.A).magnitude)
        return self._controller._newport_cmd("QI",target=self.axis_id,params=[current])

    @property
    def voltage(self):
        """
        Get and set the current

        :units: A
        :param voltage: Set the voltage
        :type: `~quantities.Quantity` or `float`
        """
        return assume_units(float(self._controller._newport_cmd("QV?",target=self.axis_id)),
                self.V)
    @voltage.setter
    def voltage(self, voltage):
        voltage = float(assume_units(voltage,pq.V).rescale(
            pq.V).magnitude)
        return self._controller._newport_cmd("QV",target=self.axis_id,params=[voltage])
   
    @property    
    def motor_type(self):
        """
        Get and set the motor type 
        * 0 = undefined
        * 1 = DC Servo 
        * 2 = Stepper motor
        * 3 = commutated stepper motor
        * 4 = commutated brushless servo motor

        :param int motor_type: Type of motor
        """
        return NewportESP301MotorType( int(self._controller._newport_cmd("QM?",target=self._axis_id)) )
    @motor_type.setter
    def motor_type(self, motor_type):
        self._controller._newport_cmd("QM",target=self._axis_id,params=[int(motor_type)])

    @property    
    def feedback_configuration(self):
        """
        Get and set Feedback configuration        

        :param int feedback_configuration: 
        """
        return int(self._controller._newport_cmd("ZB?",target=self._axis_id)[:-2],16)
    @feedback_configuration.setter
    def feedback_configuration(self, feedback_configuration):
        self._controller._newport_cmd("ZB",target=self._axis_id,params=[int(feedback_configuration)])

    @property    
    def position_display_resolution(self):
        """
        Get and set the position display resolution

        :param int position_display_resolution: 
        """
        return int(self._controller._newport_cmd("FP?",target=self._axis_id))
    @position_display_resolution.setter
    def position_display_resolution(self, position_display_resolution):
        self._controller._newport_cmd("FP",target=self._axis_id,params=[int(position_display_resolution)])    
    
    @property    
    def trajectory(self):
        """
        Get and set the trajectory

        :param int trajectory: 
        """
        return int(self._controller._newport_cmd("TJ?",target=self._axis_id))
    @trajectory.setter
    def trajectory(self, trajectory):
        self._controller._newport_cmd("TJ",target=self._axis_id,params=[int(trajectory)])

    @property    
    def microstep_factor(self):
        """
        Get and set the microstep_factor

        :param int microstep_factor: 
        """
        return int(self._controller._newport_cmd("QS?",target=self._axis_id))
    @microstep_factor.setter
    def microstep_factor(self, microstep_factor):

        factor = int(microstep_factor)
        if factor >= 1 and factor <= 250 :
            self._controller._newport_cmd("QS",target=self._axis_id,params=[factor])
        else:
            raise ValueError("Microstep factor must be between 1 and 250")

    @property    
    def hardware_limit_configuration(self):
        """
        Get and set the hardware_limit_configuration

        :param int hardware_limit_configuration: 
        """
        return int(self._controller._newport_cmd("ZH?",target=self._axis_id)[:-2])
    @hardware_limit_configuration.setter
    def hardware_limit_configuration(self, hardware_limit_configuration):
        self._controller._newport_cmd("ZH",target=self._axis_id,params=[int(hardware_limit_configuration)])

    @property    
    def acceleration_feed_forward(self):
        """
        Get and set the acceleration_feed_forward

        :param int acceleration_feed_forward: 
        """
        return float(self._controller._newport_cmd("AF?",target=self._axis_id))
    @acceleration_feed_forward.setter
    def acceleration_feed_forward(self, acceleration_feed_forward):
        self._controller._newport_cmd("AF",target=self._axis_id,params=[float(acceleration_feed_forward)])

    @property    
    def proportional_gain(self):
        """
        Get and set the proportional_gain

        :param float proportional_gain: 
        """
        return float(self._controller._newport_cmd("KP?",target=self._axis_id)[:-1])
    @proportional_gain.setter
    def proportional_gain(self, proportional_gain):
        self._controller._newport_cmd("KP",target=self._axis_id,params=[float(proportional_gain)])

    @property    
    def derivative_gain(self):
        """
        Get and set the derivative_gain

        :param float derivative_gain: 
        """
        return float(self._controller._newport_cmd("KD?",target=self._axis_id))
    @derivative_gain.setter
    def derivative_gain(self, derivative_gain):
        self._controller._newport_cmd("KD",target=self._axis_id,params=[float(derivative_gain)])

    @property    
    def integral_gain(self):
        """
        Get and set the integral_gain

        :param float integral_gain: 
        """
        return float(self._controller._newport_cmd("KI?",target=self._axis_id))
    @integral_gain.setter
    def integral_gain(self, integral_gain):
        self._controller._newport_cmd("KI",target=self._axis_id,params=[float(integral_gain)])

    @property    
    def integral_saturation_gain(self):
        """
        Get and set the integral_saturation_gain

        :param float integral_saturation_gain: 
        """
        return float(self._controller._newport_cmd("KS?",target=self._axis_id))
    @integral_saturation_gain.setter
    def integral_saturation_gain(self,integral_saturation_gain):
        self._controller._newport_cmd("KS",target=self._axis_id,params=[float(integral_saturation_gain)])

    @property
    def encoder_position(self):
        with self._units_of(NewportESP301Units.encoder_step):
            return self.position
        

    ## MOVEMENT METHODS ##
    def search_for_home(self,
            search_mode=NewportESP301HomeSearchMode.zero_position_count.value
        ):
        """
        Searches this axis only
        for home using the method specified by ``search_mode``.

        :param NewportESP301HomeSearchMode search_mode: Method to detect when
            Home has been found.
        """
        self._controller._home(axis=self.axis_id, search_mode=search_mode)

    def move(self, position, absolute=True,wait=False,block=False):
        """
        :param position: Position to set move to along this axis.
        :type position: `float` or :class:`~quantities.Quantity`
        :param bool absolute: If `True`, the position ``pos`` is
            interpreted as relative to the zero-point of the encoder.
            If `False`, ``pos`` is interpreted
            as relative to the current position of this axis.
        :param bool wait: If True, will tell axis to not execute other
            commands until movement is finished
        :param bool block: If True, will block code until movement is finished
        """
        position = float(assume_units(position,self._units).rescale(
            self._units).magnitude)
        # TODO: handle unit conversions here.
        if absolute:
            self._controller._newport_cmd("PA", params=[position], target=self.axis_id)
        else:
            self._controller._newport_cmd("PR", params=[position], target=self.axis_id)
        
        if wait:
            self.wait_for_position(position)
            if block:
                sleep(0.003)
                mot = self.is_motion_done
                while not mot:                    
                    mot = self.is_motion_done


    def move_to_hardware_limit(self):
        """
        move to hardware travel limit
        """
        self._controller._newport_cmd("MT", target=self.axis_id)

    def move_indefinitely(self):
        """
        Move until told to stop
        """
        self._controller._newport_cmd("MV", target=self.axis_id)

    def abort_motion(self):
        """
        Abort motion
        """
        self._controller._newport_cmd("AB", target=self.axis_id)
        
    def wait_for_stop(self):
        """ 
        Waits for axis motion to stop before next command is executed
        """
        self._controller._newport_cmd("WS",target=self.axis_id)

    def stop_motion(self):
        """
        Stop all motion on axis. With programmed deceleration rate
        """
        try:
            self._controller._newport_cmd("ST",target=self.axis_id)
        except NewportError, e:
            print e