コード例 #1
0
class Custom(properties.HasProperties):

    """

    """

    times = properties.Array(
        'Times at which characteristic decay function is evaluated', dtype=float)
    eta = properties.Array(
        'Characteristic decay function at evaluation times', dtype=float)

    @properties.observer('times')
    def _times_observer(self, change):
        if self.eta is not None:
            if len(change['value']) != len(self.eta):
                print('Length of time vector no longer matches length of eta vector')

    @properties.observer('eta')
    def _eta_observer(self, change):
        if self.times is not None:
            if len(change['value']) != len(self.times):
                print('Length of eta vector no longer matches length of time vector')

    def getCharDecay(self):
        """Returns characteristic decay function at specified times"""

        assert self.eta is not None, "Characteristic decay must be set"
        return self.eta
コード例 #2
0
class Custom(properties.HasProperties):
    """

    """

    times = properties.Array(
        "Times at which characteristic decay function is evaluated",
        dtype=float)
    eta = properties.Array("Characteristic decay function at evaluation times",
                           dtype=float)

    @properties.observer("times")
    def _times_observer(self, change):
        if self.eta is not None:
            if len(change["value"]) != len(self.eta):
                print(
                    "Length of time vector no longer matches length of eta vector"
                )

    @properties.observer("eta")
    def _eta_observer(self, change):
        if self.times is not None:
            if len(change["value"]) != len(self.times):
                print(
                    "Length of eta vector no longer matches length of time vector"
                )

    def getCharDecay(self):
        """Returns characteristic decay function at specified times"""

        if self.eta is None:
            raise AssertionError(
                "Characteristic decay (Property: eta) must be set.")

        return self.eta
コード例 #3
0
class SurveyParametersMixin(properties.HasProperties):
    """
    A mixin that has the properties of the survey. It doesn't do anything on
    its own
    """

    # survey parameters
    freqs = properties.Array(
        "source frequencies",
        required=False,
        dtype=float
    )

    timeSteps = TimeStepArray(
        "times-steps at which to solve",
        required=False,
        dtype=float
    )

    src_a = properties.Array(
        "down-hole z-location for the source",
        default=np.r_[0., 0., -975.]
    )

    src_b = properties.Array(
        "B electrode location",
        default=np.r_[1e3, 0., 0.]
    )
コード例 #4
0
class HalfSineWaveform(BaseWaveform):
    """
    A waveform that has a quarter-sine ramp-on and a quarter-cosine ramp-off.
    When the end of ramp-on and start of ramp off are on the same spot, it looks
    like a half sine wave.
    """

    ramp_on = properties.Array("times over which the transmitter ramps on",
                               shape=(2, ),
                               dtype=float)
    ramp_off = properties.Array("times over which we ramp off the waveform",
                                shape=(2, ),
                                dtype=float)

    def __init__(self, **kwargs):
        super(HalfSineWaveform, self).__init__(**kwargs)
        self.hasInitialFields = False

    def eval(self, time):
        if time < self.ramp_on[0]:
            return 0
        elif time >= self.ramp_on[0] and time <= self.ramp_on[1]:
            return np.sin((np.pi / 2) * ((time - self.ramp_on[0]) /
                                         (self.ramp_on[1] - self.ramp_on[0])))
        elif time > self.ramp_on[1] and time < self.ramp_off[0]:
            return 1
        elif time >= self.ramp_off[0] and time <= self.ramp_off[1]:
            return np.cos(
                (np.pi / 2) * ((time - self.ramp_off[0]) /
                               (self.ramp_off[1] - self.ramp_off[0])))
        else:
            return 0
コード例 #5
0
ファイル: SrcTDEM.py プロジェクト: zhouxiaofei811/simpeg
class TrapezoidWaveform(BaseWaveform):
    """
    A waveform that has a linear ramp-on and a linear ramp-off.
    """

    ramp_on = properties.Array("""times over which the transmitter ramps on
        [time starting to ramp on, time fully on]
        """,
                               shape=(2, ),
                               dtype=float)

    ramp_off = properties.Array("""times over which we ramp off the waveform
        [time starting to ramp off, time off]
        """,
                                shape=(2, ),
                                dtype=float)

    def __init__(self, **kwargs):
        super(TrapezoidWaveform, self).__init__(**kwargs)
        self.hasInitialFields = False

    def eval(self, time):
        if time < self.ramp_on[0]:
            return 0
        elif time >= self.ramp_on[0] and time <= self.ramp_on[1]:
            return ((1. / (self.ramp_on[1] - self.ramp_on[0])) *
                    (time - self.ramp_on[0]))
        elif time > self.ramp_on[1] and time < self.ramp_off[0]:
            return 1
        elif time >= self.ramp_off[0] and time <= self.ramp_off[1]:
            return (1 - (1. / (self.ramp_off[1] - self.ramp_off[0])) *
                    (time - self.ramp_off[0]))
        else:
            return 0
コード例 #6
0
ファイル: sources.py プロジェクト: winnerer123/simpeg
class QuarterSineRampOnWaveform(BaseWaveform):
    """
    A waveform that has a quarter-sine ramp-on and a linear ramp-off
    """

    ramp_on = properties.Array("times over which the transmitter ramps on",
                               shape=(2, ),
                               dtype=float)

    ramp_off = properties.Array("times over which we ramp off the waveform",
                                shape=(2, ),
                                dtype=float)

    def __init__(self, **kwargs):
        super(QuarterSineRampOnWaveform, self).__init__(**kwargs)
        self.hasInitialFields = False

    def eval(self, time):
        if time < self.ramp_on[0]:
            return 0
        elif time >= self.ramp_on[0] and time <= self.ramp_on[1]:
            return np.sin(np.pi / 2 * (1.0 /
                                       (self.ramp_on[1] - self.ramp_on[0])) *
                          (time - self.ramp_on[0]))
        elif time > self.ramp_on[1] and time < self.ramp_off[0]:
            return 1
        elif time >= self.ramp_off[0] and time <= self.ramp_off[1]:
            return 1 - (1.0 / (self.ramp_off[1] - self.ramp_off[0])) * (
                time - self.ramp_off[0])
        else:
            return 0
コード例 #7
0
ファイル: model.py プロジェクト: WIEQLI/casingSimulations
class SurveyParametersMixin(properties.HasProperties):
    """
    A mixin that has the properties of the survey. It doesn't do anything on
    its own
    """

    # survey parameters
    freqs = properties.Array(
        "source frequencies",
        required=False,
        dtype=float
    )

    timeSteps = TimeStepArray(
        "times-steps at which to solve",
        required=False,
        dtype=float
    )

    src_a = properties.Array(
        "down-hole z-location for the source"
        # default=np.r_[0., 0., 0.]
    )

    src_b = properties.Array(
        "B electrode location"
        # default=np.r_[CASING_L, 0., 0.]
    )

    @property
    def info_survey(self):
        info = "\n ---- Survey ---- "

        # # src locations
        # info += "\n\n   src_a: {:s}".format(str(self.src_a))
        # info += "\n   src_b: {:s}".format(str(self.src_b))
        # info += "\n"

        # frequencies or times
        if self.freqs is not None:
            info += (
                "\n   {:1.0f} frequencies. "
                "min: {:1.1e} Hz, max: {:1.1e} Hz".format(
                    len(self.freqs), self.freqs.min(), self.freqs.max()
                )
            )

        if self.timeSteps is not None:
            info += (
                "\n   {:1.0f} time steps. min time step: {:1.1e} s, "
                "max time step: {:1.1e} s. Total time: {:1.1e} s".format(
                    len(self.timeSteps), self.timeSteps.min(),
                    self.timeSteps.max(), self.timeSteps.sum()
                )
            )
        return info
コード例 #8
0
ファイル: model.py プロジェクト: WIEQLI/casingSimulations
class TargetMixin(BaseCasing):

    target_radius = properties.Array(
        "radial extent of the target (m) [min, max]",
        shape=(2,),
        default=np.r_[0., 25.]
    )

    target_z = properties.Array(
        "vertical extent of the target (m) [min, max]",
        shape=(2,),
        default=np.r_[-925., -900.]
    )

    target_theta = properties.Array(
        "azimuthal extent of the target (m) [min, max]",
        shape=(2,),
        default=np.r_[0., 2*np.pi]
    )

    sigma_target = properties.Float(
        "conductivity of the target (S/m)",
        min=0.,
        default=SIGMA_BACK
    )

    def indx_target(self, mesh):
        return (
            (mesh.gridCC[:, 0] >= self.target_radius[0]) &
            (mesh.gridCC[:, 0] <= self.target_radius[1])
        )

    def indy_target(self, mesh):
        return (
            (mesh.gridCC[:, 1] >= self.target_theta[0]) &
            (mesh.gridCC[:, 1] <= self.target_theta[1])
        )

    def indz_target(self, mesh):
        return (
            (mesh.gridCC[:, 2] >= self.target_z[0]) &
            (mesh.gridCC[:, 2] <= self.target_z[1])
        )

    def ind_target(self, mesh):
        return (
            self.indx_target(mesh) & self.indy_target(mesh) &
            self.indz_target(mesh)
        )

    def add_sigma_target(self, mesh, sigma):
        ind_target = self.ind_target(mesh)
        sigma[ind_target] = self.sigma_target
        return sigma
コード例 #9
0
class VolumeGridGeometry(ProjectElementGeometry):
    """Contains spatial information of a 3D grid volume."""
    tensor_u = properties.Array('Tensor cell widths, u-direction',
                                shape=('*', ),
                                dtype=float)
    tensor_v = properties.Array('Tensor cell widths, v-direction',
                                shape=('*', ),
                                dtype=float)
    tensor_w = properties.Array('Tensor cell widths, w-direction',
                                shape=('*', ),
                                dtype=float)
    axis_u = properties.Vector3('Vector orientation of u-direction',
                                default='X',
                                length=1)
    axis_v = properties.Vector3('Vector orientation of v-direction',
                                default='Y',
                                length=1)
    axis_w = properties.Vector3('Vector orientation of w-direction',
                                default='Z',
                                length=1)

    _valid_locations = ('vertices', 'cells')

    def location_length(self, location):
        """Return correct data length based on location"""
        if location == 'cells':
            return self.num_cells
        return self.num_nodes

    @property
    def num_nodes(self):
        """Number of nodes (vertices)"""
        return ((len(self.tensor_u) + 1) * (len(self.tensor_v) + 1) *
                (len(self.tensor_w) + 1))

    @property
    def num_cells(self):
        """Number of cells"""
        return len(self.tensor_u) * len(self.tensor_v) * len(self.tensor_w)

    @properties.validator
    def _validate_mesh(self):
        """Check if mesh content is built correctly"""
        if not (np.abs(self.axis_u.dot(self.axis_v) < 1e-6) and  #pylint: disable=no-member
                np.abs(self.axis_v.dot(self.axis_w) < 1e-6) and  #pylint: disable=no-member
                np.abs(self.axis_w.dot(self.axis_u) < 1e-6)):  #pylint: disable=no-member
            raise ValueError('axis_u, axis_v, and axis_w must be orthogonal')
        return True
コード例 #10
0
 class ManyProperties(properties.HasProperties):
     mystr = properties.String(
         'my string',
         serializer=reverse,
         deserializer=reverse,
     )
     myarr = properties.Array(
         'my array',
         serializer=to_string,
         deserializer=from_string,
     )
     myinst = properties.Instance(
         'my HP1',
         instance_class=HP1,
         serializer=serialize_a_only,
         deserializer=deserialize_from_a,
     )
     mylist = properties.List(
         'my list of HP1',
         prop=HP1,
         serializer=sum_of_a,
         deserializer=from_sum,
     )
     myunion = properties.Union(
         'string or HP1',
         props=(HP1, properties.String('')),
         serializer=just_the_classname,
         deserializer=reverse,
     )
コード例 #11
0
class SingleLayer(Halfspace):
    """
    A model consisting of air, subsurface and a single subsurface layer
    """
    sigma_layer = properties.Float(
        "conductivity of the layer (S/m)",
        default=1e-2
    )

    layer_z = properties.Array(
        "z-limits of the layer",
        shape=(2,),
        default=np.r_[-1000., -900.]
    )

    def ind_layer(self, mesh):
        return (
            (mesh.gridCC[:, 2] < self.layer_z[1]) &
            (mesh.gridCC[:, 2] > self.layer_z[0])
        )

    def sigma(self, mesh):
        sigma = super(self, sigma)(mesh)
        sigma[self.ind_layer(mesh)] = self.sigma_layer
        return sigma
コード例 #12
0
class Point(BaseRx):
    """Point receiver"""

    times = properties.Array("Observation times", dtype=float)

    fieldType = properties.StringChoice("Field type",
                                        choices=["h", "b", "dhdt", "dbdt"])

    orientation = properties.StringChoice("Component of response",
                                          choices=["x", "y", "z"])

    def __init__(self, locations=None, **kwargs):

        if locations.shape[1] != 3:
            raise ValueError(
                "Rx locations (xi,yi,zi) must be np.array(N,3) where N is the number of stations"
            )

        super(Point, self).__init__(locations, **kwargs)

    @property
    def n_times(self):
        """Number of measurements times."""
        if self.times is not None:
            return len(self.times)

    nTimes = deprecate_property(
        n_times,
        "nTimes",
        new_name="n_times",
        removal_version="0.16.0",
        error=True,
    )

    @property
    def n_locations(self):
        """Number of locations."""
        return self.locations.shape[0]

    nLocs = deprecate_property(
        n_locations,
        "nLocs",
        new_name="n_locations",
        removal_version="0.16.0",
        error=True,
    )

    @property
    def nD(self):
        """Number of data in the receiver."""
        if self.times is not None:
            return self.locations.shape[0] * len(self.times)

    fieldComp = deprecate_property(
        orientation,
        "fieldComp",
        new_name="orientation",
        removal_version="0.16.0",
        error=True,
    )
コード例 #13
0
ファイル: RxVRM.py プロジェクト: zhouxiaofei811/simpeg
class Point(BaseRxVRM):
    """Point receiver"""

    times = properties.Array('Observation times', dtype=float)
    fieldType = properties.StringChoice('Field type',
                                        choices=["h", "b", "dhdt", "dbdt"])
    fieldComp = properties.StringChoice('Component of response',
                                        choices=["x", "y", "z"])

    # def __init__(self, locs, times, fieldType, fieldComp, **kwargs):
    def __init__(self, locs, **kwargs):

        if locs.shape[1] != 3:
            raise ValueError(
                'Rx locations (xi,yi,zi) must be np.array(N,3) where N is the number of stations'
            )

        super(Point, self).__init__(locs, **kwargs)

    @property
    def nTimes(self):
        """Number of measurements times."""
        if self.times is not None:
            return len(self.times)

    @property
    def nLocs(self):
        """Number of locations."""
        return self.locs.shape[0]

    @property
    def nD(self):
        """Number of data in the receiver."""
        if self.times is not None:
            return self.locs.shape[0] * len(self.times)
コード例 #14
0
 class ManyProperties(properties.HasProperties):
     mystr = properties.String(
         'my string',
         required=False,
     )
     myarr = properties.Array(
         'my array',
         required=False,
     )
     myinst = properties.Instance(
         'my HP1',
         instance_class=HP1,
         required=False,
     )
     mylist = properties.List(
         'my list of HP1',
         prop=HP1,
         required=False,
         default=properties.utils.undefined
     )
     myunion = properties.Union(
         'string or HP1',
         props=(HP1, properties.String('')),
         required=False,
     )
コード例 #15
0
ファイル: RxVRM.py プロジェクト: jlartey-aims/Resistivity
class Point(BaseRxVRM):
    """Point receiver"""

    times = properties.Array('Observation times', dtype=float)
    fieldType = properties.StringChoice('Field type',
                                        choices=["h", "b", "dhdt", "dbdt"])
    fieldComp = properties.StringChoice('Component of response',
                                        choices=["x", "y", "z"])

    # def __init__(self, locs, times, fieldType, fieldComp, **kwargs):
    def __init__(self, locs, **kwargs):
        assert locs.shape[1] == 3, 'locs must in 3-D (x,y,z).'
        super(Point, self).__init__(locs, **kwargs)

    @property
    def nTimes(self):
        """Number of measurements times."""
        if self.times is not None:
            return len(self.times)

    @property
    def nLocs(self):
        """Number of locations."""
        return self.locs.shape[0]

    @property
    def nD(self):
        """Number of data in the receiver."""
        if self.times is not None:
            return self.locs.shape[0] * len(self.times)
コード例 #16
0
ファイル: sources.py プロジェクト: mrdrewj/simpeg
class LineCurrent(BaseFDEMSrc):
    """
    Line current source. Given the wire path provided by the (n,3) loc
    array the cells intersected by the wire path are identified and integrated
    src terms are computed

    :param list rxList: receiver list
    :param float freq: src frequency
    :param (n,3) array locations: points defining src path
    """

    location = properties.Array("location of the source", shape=("*", 3))
    current = properties.Float("current in the line", default=1.0)

    def Mejs(self, simulation):
        if getattr(self, "_Mejs", None) is None:
            mesh = simulation.mesh
            locs = self.location
            self._Mejs = self.current * segmented_line_current_source_term(
                mesh, locs)
        return self._Mejs

    def getRHSdc(self, simulation):
        Grad = simulation.mesh.nodalGrad
        return Grad.T * self.Mejs(simulation)

    def s_m(self, simulation):
        return Zero()

    def s_e(self, simulation):
        if simulation._formulation != "EB":
            raise NotImplementedError(
                "LineCurrents are only implemented for EB formulations")
        return self.Mejs(simulation)
コード例 #17
0
ファイル: survey.py プロジェクト: mrdrewj/simpeg
class SurveyVRM(BaseSurvey):
    """"""

    source_list = properties.List(
        "A list of sources for the survey",
        properties.Instance("A SimPEG source", BaseSrcVRM),
        default=[],
    )

    t_active = properties.Array(
        "Boolean array where True denotes active data in the inversion",
        dtype=bool)

    def __init__(self, source_list=None, **kwargs):

        t_active = kwargs.pop("t_active", None)

        super(SurveyVRM, self).__init__(source_list=source_list, **kwargs)

        self._nD_all = self.vnD.sum()
        self._nD = self._nD_all

        if t_active is None:
            self.t_active = np.ones(self._nD_all, dtype=bool)
        else:
            self.t_active = t_active

    @properties.validator("t_active")
    def _t_active_validator(self, change):
        if self._nD_all != len(change["value"]):
            raise ValueError(
                "Length of t_active boolean array must equal number of data. Number of data is %i"
                % self._nD_all)

    @property
    def nD(self):
        if self._nD is None:
            self._nD = np.sum(self.t_active)
        return self._nD

    def set_active_interval(self, tmin, tmax):
        """Set active times using an interval"""

        srcList = self.source_list
        nSrc = len(srcList)
        tActBool = np.array([])

        for pp in range(0, nSrc):

            rxList = srcList[pp].receiver_list
            nRx = len(rxList)

            for qq in range(0, nRx):

                times = rxList[qq].times
                nLoc = np.shape(rxList[qq].locations)[0]
                tActBool = np.r_[tActBool, np.kron(np.ones(nLoc), times)]

        self.t_active = (tActBool >= tmin) & (tActBool <= tmax)
        self._nD = np.sum(self.t_active)
コード例 #18
0
class GlobalAEMSurvey(Survey.BaseSurvey, properties.HasProperties):

    # This assumes a multiple sounding locations
    rx_locations = properties.Array("Receiver locations ",
                                    dtype=float,
                                    shape=('*', 3))
    src_locations = properties.Array("Source locations ",
                                     dtype=float,
                                     shape=('*', 3))
    topo = properties.Array("Topography", dtype=float, shape=('*', 3))

    half_switch = properties.Bool("Switch for half-space", default=False)

    _pred = None

    @Utils.requires('prob')
    def dpred(self, m, f=None):
        """
            Return predicted data.
            Predicted data, (`_pred`) are computed when
            self.prob.fields is called.
        """
        if f is None:
            f = self.prob.fields(m)

        return self._pred

    @property
    def n_sounding(self):
        """
            # of Receiver locations
        """
        return self.rx_locations.shape[0]

    def read_xyz_data(self, fname):
        """
        Read csv file format
        This is a place holder at this point
        """
        pass

    @property
    def nD(self):
        # Need to generalize this for the dual moment data
        if getattr(self, '_nD', None) is None:
            self._nD = self.nD_vec.sum()
        return self._nD
コード例 #19
0
class SurfaceGridGeometry(ProjectElementGeometry):
    """Contains spatial information of a 2D grid"""
    tensor_u = properties.Array('Grid cell widths, u-direction',
                                shape=('*', ),
                                dtype=float)
    tensor_v = properties.Array('Grid cell widths, v-direction',
                                shape=('*', ),
                                dtype=float)
    axis_u = properties.Vector3('Vector orientation of u-direction',
                                default='X',
                                length=1)
    axis_v = properties.Vector3('Vector orientation of v-direction',
                                default='Y',
                                length=1)
    offset_w = properties.Instance('Node offset', ScalarArray, required=False)

    _valid_locations = ('vertices', 'faces')

    def location_length(self, location):
        """Return correct data length based on location"""
        if location == 'faces':
            return self.num_cells
        return self.num_nodes

    @property
    def num_nodes(self):
        """Number of nodes (vertices)"""
        return (len(self.tensor_u) + 1) * (len(self.tensor_v) + 1)

    @property
    def num_cells(self):
        """Number of cells (faces)"""
        return len(self.tensor_u) * len(self.tensor_v)

    @properties.validator
    def _validate_mesh(self):
        """Check if mesh content is built correctly"""
        if not np.abs(self.axis_u.dot(self.axis_v)) < 1e-6:  #pylint: disable=no-member
            raise ValueError('axis_u and axis_v must be orthogonal')
        if self.offset_w is properties.undefined or self.offset_w is None:
            return True
        if len(self.offset_w.array) != self.num_nodes:
            raise ValueError(
                'Length of offset_w, {zlen}, must equal number of nodes, '
                '{nnode}'.format(zlen=len(self.offset_w),
                                 nnode=self.num_nodes))
        return True
コード例 #20
0
ファイル: sparse.py プロジェクト: lshuai8002/simpeg-1
class BaseSparse(BaseRegularization):
    """
    Base class for building up the components of the Sparse Regularization
    """
    def __init__(self, mesh, **kwargs):
        self._stashedR = None
        super(BaseSparse, self).__init__(mesh=mesh, **kwargs)

    model = properties.Array("current model", dtype=float)

    epsilon = properties.Float("Threshold value for the model norm",
                               default=1e-3,
                               required=True)

    norm = properties.Array("norm used", dtype=float)

    space = properties.String("By default inherit the objctive",
                              default='linear')

    gradientType = properties.String("type of gradient", default='components')

    scale = properties.Array(
        "General nob for scaling",
        dtype=float,
    )

    # Give the option to scale or not
    scaledIRLS = properties.Bool("Scale the gradients of the IRLS norms",
                                 default=True)

    @properties.validator('scale')
    def _validate_scale(self, change):
        if change['value'] is not None:
            # todo: residual size? we need to know the expected end shape
            if self._nC_residual != '*':
                assert len(change['value']) == self._nC_residual, (
                    'scale must be length {} not {}'.format(
                        self._nC_residual, len(change['value'])))

    @property
    def stashedR(self):
        return self._stashedR

    @stashedR.setter
    def stashedR(self, value):
        self._stashedR = value
コード例 #21
0
ファイル: GlobalEM1D.py プロジェクト: ligang0309/simpegEM1D
class GlobalEM1DSurvey(Survey.BaseSurvey, properties.HasProperties):

    # This assumes a multiple sounding locations
    rx_locations = properties.Array("Receiver locations ",
                                    dtype=float,
                                    shape=('*', 3))
    src_locations = properties.Array("Source locations ",
                                     dtype=float,
                                     shape=('*', 3))
    topo = properties.Array("Topography", dtype=float, shape=('*', 3))

    _pred = None

    @Utils.requires('prob')
    def dpred(self, m, f=None):
        """
            Return predicted data.
            Predicted data, (`_pred`) are computed when
            self.prob.fields is called.
        """
        if f is None:
            f = self.prob.fields(m)

        return self._pred

    @property
    def n_sounding(self):
        """
            # of Receiver locations
        """
        return self.rx_locations.shape[0]

    @property
    def n_layer(self):
        """
            # of Receiver locations
        """
        return self.prob.n_layer

    def read_xyz_data(self, fname):
        """
        Read csv file format
        This is a place holder at this point
        """
        pass
コード例 #22
0
class Int3Array(ScalarArray):
    """Shared n x 3 array of integers"""
    array = properties.Array(
        'Shared n x 3 Int Array',
        dtype=int,
        shape=('*', 3),
        serializer=array_serializer,
        deserializer=array_deserializer(('*', 3))
    )
コード例 #23
0
        class HasNoCoerceArray(properties.HasProperties):

            arr = properties.Array('', coerce=False)
            vec2 = properties.Vector2('', coerce=False)

            @properties.Array('', coerce=False)
            def dynamic_arr(self):
                if getattr(self, '_dynamic_arr', None) is None:
                    self._dynamic_arr = np.ones(5)
                return self._dynamic_arr
コード例 #24
0
ファイル: spec.py プロジェクト: banesullivan/nuftio
class MaterialComponent(properties.HasProperties):
    """Defines the extent of a material component in the grid"""

    i = properties.Array(
        'Range of element indices in the X-direction',
        shape=(2, ),
        dtype=int,
    )

    j = properties.Array(
        'Range of element indices in the Y-direction',
        shape=(2, ),
        dtype=int,
    )

    k = properties.Array(
        'Range of element indices in the Z-direction',
        shape=(2, ),
        dtype=int,
    )
コード例 #25
0
class GridInfo(properties.HasProperties):
    ncol = properties.Integer('number of columns', min=2)
    nrow = properties.Integer('number of rows', min=2)
    xll = properties.Float('x-value of lower-left corner')
    yll = properties.Float('y-value of lower-left corner')
    xsize = properties.Float('x-axis spacing')
    ysize = properties.Float('y-axis spacing')
    zmin = properties.Float('minimum data value', required=False)
    zmax = properties.Float('maximum data value', required=False)
    data = properties.Array('grid of data values', shape=('*', '*'))

    @properties.validator
    def _validate_datasize(self):
        if self.data.shape != (self.ncol, self.nrow):
            raise ValueError('Data shape must be ncol x nrow')

    def to_steno3d(self, project=None, as_topo=True):
        """Create a project from GridInfo

        Optional input:
            project: Preexisting Steno3D project to add .grd file components
                     to. If not provided, a new project will be created.
            verbose: Print messages and warnings during file parsing.
                     (default: True)
            as_topo: If True, add data from grid file as topography.
                     Otherwise only add the data as color on a flat surface.
                     (default: True)

        Output:
            Steno3D Project with GridInfo components
        """

        self.validate()

        if project is None:
            project = steno3d.Project(description='From surfer grid file')
        elif not isinstance(project, steno3d.Project):
            raise steno3d.parsers.ParseError('project must be Steno3D Project')

        surf = steno3d.Surface(
            project=project,
            mesh=steno3d.Mesh2DGrid(O=[self.xll, self.yll, 0],
                                    h1=np.ones(self.ncol - 1) * self.xsize,
                                    h2=np.ones(self.nrow - 1) * self.ysize),
            data=[
                dict(location='N',
                     data=steno3d.DataArray(array=self.data.flatten()))
            ])

        if as_topo:
            surf.mesh.Z = self.data.flatten()

        return project
コード例 #26
0
 class ArrayOpts(properties.HasProperties):
     myarray = properties.Array('my array')
     myarray222 = properties.Array('my 3x3x3 array', shape=(2, 2, 2))
     myarrayfloat = properties.Array('my float array', dtype=float)
     myarrayint = properties.Array('my int array', dtype=int)
     myarraybool = properties.Array('my bool array', dtype=bool)
     myarraycomplex = properties.Array('my complex array',
                                       dtype=complex)
コード例 #27
0
ファイル: KnownSystems.py プロジェクト: simpeg/simpegEM1D
class KnownSystems(properties.HasProperties):
    """Simple Class for KnownSystems."""

    BaseFrequency = properties.Float("WaveFormCurrent", )

    WaveFormCurrent = properties.Array("WaveFormCurrent",
                                       dtype=float,
                                       shape=('*', ))

    WaveFormTime = properties.Array("WaveFormTime", dtype=float, shape=('*', ))

    t_peak = properties.Float("Peak waveform time", )

    t0 = properties.Float("Zero waveform time", )

    tref = properties.Float("Reference time for current off", )

    ModellingLoopRadius = properties.Float("ModellingLoopRadius", )

    WindowTimeStart = properties.Array("WindowTimeStart",
                                       dtype=float,
                                       shape=('*', ))

    WindowTimeEnd = properties.Array("WindowTimeEnd",
                                     dtype=float,
                                     shape=('*', ))

    def __init__(self, name):
        self.name = name

    def save(self, fname=None):
        data = self.serialize()
        if fname is None:
            fname = self.name
        with open(fname + '.json', 'w') as outfile:
            json.dump(data, outfile, ensure_ascii=False)
コード例 #28
0
ファイル: RxVRM.py プロジェクト: zhouxiaofei811/simpeg
class SquareLoop(BaseRxVRM):
    """Square loop receiver

    Measurements with this type of receiver are the field, integrated over the
    area of the loop, then multiplied by the number of coils, then normalized
    by the dipole moment. As a result, the units for fields predicted with this
    type of receiver are the same as 'h', 'b', 'dhdt' and 'dbdt', respectively.

    """

    times = properties.Array('Observation times', dtype=float)
    width = properties.Float('Square loop width', min=1e-6)
    nTurns = properties.Integer('Number of loop turns', min=1, default=1)
    quadOrder = properties.Integer(
        'Order for numerical quadrature integration over loop',
        min=1,
        max=7,
        default=3)
    fieldType = properties.StringChoice('Field type',
                                        choices=["h", "b", "dhdt", "dbdt"])
    fieldComp = properties.StringChoice('Component of response',
                                        choices=["x", "y", "z"])

    def __init__(self, locs, **kwargs):

        if locs.shape[1] != 3:
            raise ValueError(
                'Rx locations (xi,yi,zi) must be np.array(N,3) where N is the number of stations'
            )

        super(SquareLoop, self).__init__(locs, **kwargs)

    @property
    def nTimes(self):
        """Number of measurements times."""
        if self.times is not None:
            return len(self.times)

    @property
    def nLocs(self):
        """Number of locations."""
        return self.locs.shape[0]

    @property
    def nD(self):
        """Number of data in the receiver."""
        if self.times is not None:
            return self.locs.shape[0] * len(self.times)
コード例 #29
0
ファイル: models.py プロジェクト: csmwteam/wtools
class Models(properties.HasProperties):
    """A container for static models"""

    _models = properties.Dictionary(
        'The data dictionary.',
        key_prop=properties.String('The model names'),
        value_prop=properties.Array('The data values',
                                    dtype=(float, int, bool),
                                    shape=None))

    @property
    def shape(self):
        return list(self._models.values())[0].shape

    @properties.validator
    def _validate_models(self):
        shp = self.shape
        for k, d in self._models.items():
            if d.shape != shp:
                raise RuntimeError(
                    'Validation Failed: dimesnion mismatch between models.')
        return True

    def __getitem__(self, key):
        """Get a model by its string name and time index"""
        return self._models[key]

    def __setitem__(self, key, value):
        if self._models is None:
            self._models = {}
        self._models[key] = value

    def keys(self):
        return self._models.keys()

    def values(self):
        return self._models.values()

    def items(self):
        return self._models.items()

    def save(self, filename):
        with open(filename, 'w') as f:
            json.dump(self.serialize(), f)
        return filename
コード例 #30
0
class ScalarArray(UidModel):
    """Class with unique ID and data array"""
    array = properties.Array(
        'Shared Scalar Array',
        serializer=array_serializer,
        deserializer=array_deserializer(('*',))
    )

    def __init__(self, array=None, **kwargs):
        super(ScalarArray, self).__init__(**kwargs)
        if array is not None:
            self.array = array

    def __len__(self):
        return self.array.__len__()

    def __getitem__(self, i):
        return self.array.__getitem__(i)