Exemplo n.º 1
0
class Rating(BaseModel):

    customer = properties.Instance(
        'Partial customer object.',
        instance_class=Customer,
        required=True,
    )
    ticket_id = properties.Integer(
        'Ticket ID',
        required=True,
    )
    thread_id = properties.Integer(
        'Thread ID',
        required=True,
    )
    mailbox = properties.Instance(
        'Reference to the mailbox that the conversation belongs to.',
        instance_class=MailboxRef,
        required=True,
    )
    rating = properties.StringChoice(
        'Satisfaction rating.',
        choices=['Great', 'Okay', 'Bad'],
        required=True,
    )
    comments = properties.String('Additional comments', )
    created_at = properties.DateTime(
        'UTC time when this rating was created.', )
    modified_at = properties.DateTime(
        'UTC time when this rating was modified.', )
class Producer(LinksModelWithImage):
    """Cannabis producers are the ones that create all of the cannabis flowers,
    extracts, edibles, and other products we know and love.

    More information about cannabis producers can be found in the `Cannabis
    Reports FAQ <https://www.cannabisreports.com/faq/cannabis-community/
    what-is-a-cannabis-producer>`_.
    """

    name = properties.String(
        'The name of the producer.',
    )
    reviews = properties.Instance(
        'The number of reviews for all of the strains available from this '
        'seed Producer.',
        instance_class=GeneralOverview,
    )
    extracts = properties.Instance(
        'Information on all of the extracts that this producer makes.',
        instance_class=GeneralOverview,
    )
    edibles = properties.Instance(
        'Information on all of the edibles that this producer makes.',
        instance_class=GeneralOverview,
    )
    products = properties.Instance(
        'Information on all of the products that this producer makes.',
        instance_class=GeneralOverview,
    )
Exemplo n.º 3
0
class LineSetGeometry(ProjectElementGeometry):
    """Contains spatial information of a line set"""
    vertices = properties.Instance(
        'Spatial coordinates of line vertices relative to line set origin',
        Vector3Array)
    segments = properties.Instance('Endpoint vertex indices of line segments',
                                   Int2Array)

    _valid_locations = ('vertices', 'segments')

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

    @property
    def num_nodes(self):
        """Number of nodes (vertices)"""
        return len(self.vertices.array)

    @property
    def num_cells(self):
        """Number of cells (segments)"""
        return len(self.segments.array)

    @properties.validator
    def _validate_mesh(self):
        """Ensures segment indices are valid"""
        if np.min(self.segments.array) < 0:
            raise ValueError('Segments may only have positive integers')
        if np.max(self.segments.array) >= len(self.vertices.array):
            raise ValueError('Segments expects more vertices than provided')
        return True
Exemplo n.º 4
0
class RasterMetaData(properties.HasProperties):
    """An object to contain all the information for a single swath.
    """
    #https://landsat.usgs.gov/how-do-landsat-8-band-combinations-differ-landsat-7-or-landsat-5-satellite-data

    # Metadata
    data_provider = properties.String('The data provider')
    satellite = properties.String('The satellite from which data was aquired')
    instrument = properties.String('The instrument on the satellite')
    acquisition_date = properties.String('The date of acquisition', required=False)
    scene_center_time = properties.String('Center time', required=False)
    level1_production_date = properties.String('Production date', required=False)
    solar_angles = properties.Instance('The solar angles', SolarAngle, required=False)
    earth_sun_distance = properties.Float('The earth-sun distance', required=False)
    product_id = properties.String('Data product ID', required=False)
    lpgs_metadata_file = properties.String('metadata file', required=False)
    wrs = properties.Instance('WRS', WRS, required=False)
    # TODO modis = properties.Instance('Modis', Modis, required=False)

    corner = properties.List('The corner points', prop=Corner)

    # Spatial Reference
    bounding_coordinates = properties.Instance('The bounding coordinates', BoundingCoordinates)
    projection_information = properties.Instance('The projection', Projection)
    orientation_angle = properties.Float('The orientation angle', min=-360.0, max=360.0)
Exemplo n.º 5
0
class Strain(LineageModel):
    """Cannabis strains are the various cultivars available for the cannabis
    family. Thousands of years of human domestication and breeding of cannabis
    strains have resulted in a huge variety of attributes that we know and
    love today.

    `Wikipedia Definition <http://en.wikipedia.org/wiki/Cultivar>`_

    Over time, strain names have been used by various companies in their
    attempts to recreate the results of other breeders. Cannabis Reports
    identifies strains not only by their name, but by their seed company as
    well, to ensure they are all properly represented.
    """

    name = properties.String(
        'Name of the cannabis strain.',
    )
    seed_company = properties.Instance(
        'Information about the seed company that created or provides the '
        'strain.',
        instance_class=SeedCompany,
    )
    genetics = properties.Instance(
        'Object that holds information about the genetics for the strain.',
        instance_class=StrainGenetics,
    )
    children = properties.Instance(
        'Object that holds information about the children for the strain.',
        instance_class=GeneralOverview,
    )
    reviews = properties.Instance(
        'Object that holds information about the reviews for the strain.',
        instance_class=GeneralOverview,
    )
Exemplo n.º 6
0
class SurfaceGeometry(ProjectElementGeometry):
    """Contains spatial information about a triangulated surface"""
    vertices = properties.Instance(
        'Spatial coordinates of vertices relative to surface origin',
        Vector3Array)
    triangles = properties.Instance('Vertex indices of surface triangles',
                                    Int3Array)

    _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):
        """get number of nodes"""
        return len(self.vertices)

    @property
    def num_cells(self):
        """get number of cells"""
        return len(self.triangles)

    @properties.validator
    def _validate_mesh(self):
        if np.min(self.triangles.array) < 0:
            raise ValueError('Triangles may only have positive integers')
        if np.max(self.triangles.array) >= len(self.vertices.array):
            raise ValueError('Triangles expects more vertices than provided')
        return True
Exemplo n.º 7
0
class Volume(CompositeResource):
    """Contains all the information about a 3D volume"""
    mesh = properties.Instance(
        doc='Mesh',
        instance_class=Mesh3DGrid,
        default=Mesh3DGrid,
    )
    data = properties.List(
        doc='Data',
        prop=_VolumeBinder,
        coerce=True,
        required=False,
        default=list,
    )
    opts = properties.Instance(
        doc='Options',
        instance_class=_VolumeOptions,
        default=_VolumeOptions,
    )

    def _nbytes(self):
        return self.mesh._nbytes() + sum(d.data._nbytes() for d in self.data)

    @properties.validator
    def _validate_data(self):
        """Check if resource is built correctly"""
        for ii, dat in enumerate(self.data):
            assert dat.location == 'CC'  # in ('N', 'CC')
            valid_length = (self.mesh.nC
                            if dat.location == 'CC' else self.mesh.nN)
            if len(dat.data.array) != valid_length:
                raise ValueError(
                    'volume.data[{index}] length {datalen} does not match '
                    '{loc} length {meshlen}'.format(index=ii,
                                                    datalen=len(
                                                        dat.data.array),
                                                    loc=dat.location,
                                                    meshlen=valid_length))
        return True

    def _to_omf(self):
        import omf
        element = omf.VolumeElement(
            name=self.title or '',
            description=self.description or '',
            geometry=self.mesh._to_omf(),
            color=self.opts.color or 'random',
            data=[],
        )
        for data in self.data:
            if data.location == 'CC':
                location = 'cells'
            else:
                location = 'vertices'
            omf_data = data.data._to_omf()
            omf_data.location = location
            element.data.append(omf_data)
        return element
Exemplo n.º 8
0
class DateTimeData(ProjectElementData):
    """Data array with DateTime entries"""
    array = properties.Instance(
        'datetimes at locations on a mesh (see location parameter)',
        DateTimeArray
    )
    colormap = properties.Instance(
        'colormap associated with the data',
        DateTimeColormap,
        required=False
    )
Exemplo n.º 9
0
class ScalarData(ProjectElementData):
    """Data array with scalar values"""
    array = properties.Instance(
        'scalar values at locations on a mesh (see location parameter)',
        ScalarArray
    )
    colormap = properties.Instance(
        'colormap associated with the data',
        ScalarColormap,
        required=False
    )
Exemplo n.º 10
0
class Band(properties.HasProperties):
    """Contains raster metadata and data for a single band."""

    # metadata attributes
    name = properties.String('Name of the band')
    data_type = properties.String('Band data type')
    nlines = properties.Integer('number of lines')
    nsamps = properties.Integer('number of samples')
    product = properties.String('Data product')
    # Not required
    app_version = properties.String('app version', required=False)
    production_date = properties.String('production date', required=False)
    resample_method = properties.String('resample method', required=False)
    category = properties.String('Band category', required=False)
    source = properties.String('Band source', required=False)
    qa_description = properties.String('QA description', required=False)
    # TODO: class_values
    percent_coverage = properties.Float('percent coverage', required=False)

    # metadata: All required
    short_name = properties.String('Short name')
    long_name = properties.String('Long display name')
    file_name = properties.String('Original file name')
    pixel_size = properties.Instance('The pixel size', PixelSize)

    # data information
    fill_value = properties.Integer('fill value', default=-9999)
    saturate_value = properties.Integer('Saturate value', required=False)
    add_offset = properties.Float('Add offset', required=False)
    data_units = properties.String('Data units', required=False)
    scale_factor = properties.Float('Scaling factor', required=False)
    valid_range = properties.Instance('The valid data range',
                                      ValidRange,
                                      required=False)
    radiance = properties.Instance('The radiance', Lum, required=False)
    reflectance = properties.Instance('The reflectance', Lum, required=False)
    thermal_const = properties.Instance('The thermal const',
                                        ThermalConst,
                                        required=False)

    bitmap_description = properties.Dictionary(
        'band bitmap description (not always present)',
        required=False,
        key_prop=properties.String('Key value'),
        value_prop=properties.String('Bitmap value description'))

    # TODO: data validation causes a MAJOR slowdown. WAAAAYYY faster to not set
    #       the data as a `properties` attribute.
    # data = properties.Array(
    #     'The band data as a 2D NumPy data',
    #     shape=('*','*'),
    #     )
    data = None
Exemplo n.º 11
0
class TestModel(BaseModel):
    a_key = properties.String('A key')
    sub_instance = properties.Instance(
        'Sub Instance',
        instance_class=BaseModel,
    )
    list = properties.List(
        'List',
        prop=properties.Instance('List Instance', instance_class=BaseModel),
    )
    list_string = properties.List(
        'List of Strings',
        prop=properties.String('String'),
    )
    not_a_field = True
Exemplo n.º 12
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,
     )
Exemplo n.º 13
0
class ScalarColormap(ContentModel):
    """Length-128 color gradient with min/max values, used with ScalarData"""
    gradient = properties.Instance(
        'length-128 ColorArray defining the gradient',
        ColorArray
    )
    limits = properties.List(
        'Data range associated with the gradient',
        prop=properties.Float(''),
        min_length=2,
        max_length=2,
        default=properties.undefined,
    )

    @properties.validator('gradient')
    def _check_gradient_length(self, change):                                  #pylint: disable=no-self-use
        """Ensure gradient is length-128"""
        if len(change['value']) != 128:
            raise ValueError('Colormap gradient must be length 128')

    @properties.validator('limits')
    def _check_limits_on_change(self, change):                                 #pylint: disable=no-self-use
        """Ensure limits are valid"""
        if change['value'][0] > change['value'][1]:
            raise ValueError('Colormap limits[0] must be <= limits[1]')

    @properties.validator
    def _check_limits_on_validate(self):
        """Ensure limits are valid"""
        self._check_limits_on_change({'value': self.limits})
Exemplo n.º 14
0
class VolumeElement(ProjectElement):
    """Contains mesh, data, and options of a volume"""
    geometry = properties.Instance('Structure of the volume element',
                                   instance_class=VolumeGridGeometry)
    subtype = properties.StringChoice('Category of Volume',
                                      choices=('volume', ),
                                      default='volume')
Exemplo n.º 15
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,
     )
Exemplo n.º 16
0
def test_is_list_of_pointers():
    assert utils.is_list_of_pointers(
        properties.List('', PointerSubclass('', properties.HasProperties)))
    assert not utils.is_list_of_pointers(
        PointerSubclass('', properties.HasProperties))
    assert not utils.is_list_of_pointers(
        properties.List('', properties.Instance('', properties.HasProperties)))
class MenuItemSummary(MenuItem):
    """Menu item summary for when it is known what the menu item is."""

    location = properties.Instance(
        'Object containing information about the location this item is at.',
        instance_class=Dispensary,
    )
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
class SeedCompany(LineageModel):
    """Cannabis seed companies create the variety of strains available for
    growing and breeding.
    """

    name = properties.String('The name of this seed company.', )
    strains = properties.Instance(
        'Object containing information on the strains available from this '
        'seed company.',
        instance_class=GeneralOverview,
    )
    reviews = properties.Instance(
        'The number of reviews for all of the strains available from this '
        'seed company.',
        instance_class=GeneralOverview,
    )
Exemplo n.º 20
0
class Customer(SearchCustomer):
    """This represents a customer, which is a type of person."""

    background = properties.String(
        'This is the Notes field from the user interface.',
    )
    address = properties.Instance(
        'The address for this customer.',
        instance_class=Address,
    )
    social_profiles = properties.List(
        'Social profiles that represent this customer.',
        prop=SocialProfile,
    )
    emails = properties.List(
        'Email addresses for this customer.',
        prop=Email,
    )
    phones = properties.List(
        'Phone numbers for this customer.',
        prop=Phone,
    )
    chats = properties.List(
        'Chat addresses for this customer.',
        prop=Chat,
    )
    websites = properties.List(
        'Websites for this customer.',
        prop=Website,
    )
Exemplo n.º 21
0
class LineSetElement(ProjectElement):
    """Contains mesh, data, and options of a line set"""
    geometry = properties.Instance('Structure of the line element',
                                   instance_class=LineSetGeometry)
    subtype = properties.StringChoice('Category of LineSet',
                                      choices=('line', 'borehole'),
                                      default='line')
Exemplo n.º 22
0
class _BaseElementOptions(_BaseOptions):
    """Base class for various element options"""
    visible = properties.Boolean(
        'Visibility of resource on/off',
        default=True,
    )
    opacity = properties.Instance(
        'Default opacity options on the element',
        OptionsOpacity,
        default=OptionsOpacity,
    )
    color = properties.Instance(
        'Default color options on the element',
        OptionsColor,
        default=OptionsColor,
    )
Exemplo n.º 23
0
class LineSetElement(ProjectElement):
    """Contains mesh, data, and options of a line set"""
    geometry = properties.Instance(
        'Structure of the line element',
        instance_class=LineSetGeometry
    )
    subtype = properties.StringChoice(
        'Category of LineSet',
        choices=('line', 'borehole'),
        default='line'
    )

    def toVTK(self):
        """Convert the line set to a ``vtkPloyData`` data object."""
        import vtk
        from vtk.util import numpy_support as nps

        output = vtk.vtkPolyData()
        cells = vtk.vtkCellArray()
        pts = vtk.vtkPoints()

        # Make a data array for grouping the line segments
        indexArr = vtk.vtkIntArray()
        indexArr.SetNumberOfValues(self.geometry.num_cells)
        indexArr.SetName('Line Index')

        # Generate VTK Points from the vertices
        pts.SetNumberOfPoints(self.geometry.num_nodes)
        pts.SetData(nps.numpy_to_vtk(self.geometry.vertices))

        last = self.geometry.segments[0][0]
        segi = 0
        for i in range(len(self.geometry.segments)):
            # Create a VTK Line cell for each segment
            seg = self.geometry.segments[i]
            aLine = vtk.vtkLine()
            aLine.GetPointIds().SetId(0, seg[0])
            aLine.GetPointIds().SetId(1, seg[1])
            cells.InsertNextCell(aLine)
            # Group segments by connectivity:
            if seg[0] != last:
                segi += 1
            last = seg[1]
            indexArr.SetValue(i, segi)

        # Generate the output
        output.SetPoints(pts)
        output.SetLines(cells)
        output.GetCellData().AddArray(indexArr)

        # Now add data to lines:
        for data in self.data:
            arr = data.array.array
            c = nps.numpy_to_vtk(num_array=arr)
            c.SetName(data.name)
            output.GetCellData().AddArray(c)

        # TODO: if subtype is borehole make a tube

        return output
Exemplo n.º 24
0
class WebHookEvent(BaseModel):

    event_type = event_type
    record = properties.Instance(
        'The parsed data record that was received in the request.',
        instance_class=BaseModel,
        required=True,
    )
Exemplo n.º 25
0
def test_is_pointer():
    assert utils.is_pointer(PointerSubclass('', properties.HasProperties))
    assert utils.is_pointer(
        properties.Union('',
                         props=[
                             PointerSubclass('', properties.HasProperties),
                             properties.extras.Pointer(
                                 '', properties.HasProperties),
                         ]))
    assert not utils.is_pointer(
        properties.Instance('', properties.HasProperties))
    assert not utils.is_pointer(
        properties.Union('',
                         props=[
                             PointerSubclass('', properties.HasProperties),
                             properties.Instance('', properties.HasProperties),
                         ]))
Exemplo n.º 26
0
class OptionsSurface(_BaseElementOptions):
    """Surface visualizatino options"""
    color = properties.Instance(
        'Default color options on the element',
        OptionsSurfaceColor,
        default=OptionsSurfaceColor,
    )
    wireframe = properties.Instance(
        'Default wireframe options on the element',
        OptionsWireframe,
        default=OptionsWireframe,
    )
    textures = properties.List(
        'Default textures on the element',
        OptionsTexture,
        default=list,
    )
Exemplo n.º 27
0
class AbstractItem(LinksModelWithImage):
    """Represents the base attributes for a saleable cannabis item."""

    name = properties.String(
        'Name of the item.',
    )
    barcode = properties.String(
        'Link to the barcode for this item.',
    )
    producer = properties.Instance(
        'Information about the producer that created the item.',
        instance_class=Producer,
    )
    type = properties.String(
        'Type of item.',
    )
    strain = properties.Instance(
        'Strain that this item comes from.',
        instance_class=Strain,
    )
    lab_test = properties.String(
        'Link to the PDF containing lab test information for this item.',
    )
    thc = properties.String(
        'Amount of `THC <https://www.cannabisreports.com/faq/'
        'cannabis-community/what-is-thc-tetrahydrocannabinol>`_ in this '
        'item.',
    )
    cbd = properties.String(
        'Amount of `CBD <https://www.cannabisreports.com/faq/'
        'cannabis-community/what-is-cbd-cannabidiol>`_ in this item.',
    )
    cannabis = properties.String(
        'Milligrams of cannabis in this item.',
    )
    hash_oil = properties.String(
        'Milligrams of hash oil in this item.',
    )
    reviews = properties.Instance(
        'Object containing information on the reviews for the item.',
        instance_class=GeneralOverview,
    )
Exemplo n.º 28
0
class BaseDataNSEMPlots(properties.HasProperties):
    """
    A class container of matplotlib panels for plotting
    NSEM data.

    """

    fig = properties.Instance("Figure plotting", plt.Figure, required=False)
    axes = properties.List(
        "List of plot axes",
        properties.Instance("Axes to plot the on", plt.Axes),
        required=False,
    )

    def setup(self):
        """
        Setup up the plot window.

        Should populate the
            self.fig and self.axes properties
        """
        raise NotImplementedError(
            "Is required in subclasses of {}".format(self.__class__)
        )

    def draw(self):
        raise NotImplementedError(
            "Is required in subclasses of {}".format(self.__class__)
        )

    def clear_axes(self):
        """
        Function to clear all of the axes
        """
        for ax in self.axes:
            while len(ax.lines) > 0:
                for line in ax.lines:
                    ax.lines.remove(line)

            while len(ax.collections) > 0:
                for item in ax.collections:
                    item.remove()
Exemplo n.º 29
0
class OptionsTubes(OptionsLines):
    """LineSet visualization options for lines with finite thickness

    This adds radius to standard
    :class:`lfview.resources.spatial.options.OptionsLines`
    and may be used with drillholes, for example.
    """
    radius = properties.Instance(
        'Default radius options on the element',
        OptionsSize,
        default=OptionsSize,
    )
Exemplo n.º 30
0
class _SurfaceBinder(HasSteno3DProps):
    """Contains the data on a 2D surface with location information"""
    location = properties.StringChoice(doc='Location of the data on mesh',
                                       choices={
                                           'CC': ('FACE', 'CELLCENTER'),
                                           'N': ('NODE', 'VERTEX', 'CORNER')
                                       })
    data = properties.Instance(
        doc='Data',
        instance_class=DataArray,
        default=DataArray,
    )