[x3d-public] example x3d.py python code using numpy library
John Carlson
yottzumm at gmail.com
Mon Feb 28 10:38:12 PST 2022
Thanks, Don.
I think this work will help with x3djsonld.py, but I don’t know when I
will pick it up again. I don’t have any big x3d.py projects besides that.
The good news is, I passed the cardiologist’s tests with flying colors
today, just a heart murmur/regurgitation, which is pretty much normal at my
age. My heart muscle shows no sign of muscle loss/death. The next step is
to schedule surgery this afternoon.
I will probably do an update of X3DJSONLD this afternoon. I’m about an
hour away from home. I will also start a non-schema JSON validation of
the archive using the latest X3DJSAIL. I am not aware of X3DJSAIL
updates. I don’t know if the JSON files need to be updated in my version
of the archives.
John
On Mon, Feb 28, 2022 at 11:28 AM Brutzman, Donald (Don) (CIV) <
brutzman at nps.edu> wrote:
> Based on the elegant list-comprehension expressions in the following two
> lines
>
>
>
> - coord = Coordinate( point = [ tuple(pt) for pt in point_coordinates]
> ),
>
>
>
> - color = Color( color = [tuple(c) for c in point_colors])
>
>
>
> These types of expressions could certainly be added to MFVec3f, MFColor,
> etc. which would continue flexibility of current duck typing across full
> diversity of X3D field types.
>
>
>
> Presumably the key precondition for applying them will be proper
> detection of type, e.g.
>
>
>
> - if isinstance(value, np.array) # and further checking that elements
> of arrays are tuples
>
>
>
> I will eventually be able to fumble around and get something hacked
> together, putting it into the fieldtype value setter. (Or keep them as a
> separate utility if numpy dependency needs to be avoided.)
>
>
>
> If you can help with type checking to avoid numpy GIGO problems, please
> toss me an example. Presumably if we can get numpy working then we can
> support other lists of tuples as well.
>
>
>
> FWIW, example target excerpted from package x3d.py follows. (The
> triple-hash ### blocks were form used prior to latest refactoring, they’ll
> get deleted once confirmed that all functionality is handled in new code.)
>
>
>
> ===========================
>
> class MFVec3f(_X3DArrayField):
>
> """
>
> Field type MFVec3f is an array of SFVec3f values. Individual singleton
> SFVec3f array values are optionally separated by commas in XML syntax.
>
> """
>
> # […snip…]
>
>
>
> @property # getter - - - - - - - - - -
>
> def value(self):
>
> """ Provide typed value of this field instance. """
>
> return self.__value
>
> @value.setter
>
> def value(self, value):
>
> """ The value setter only allows correctly typed values. """
>
> if isinstance(value,SFVec3f):
>
> value = value.value # dereference
>
> elif value is None:
>
> value = MFVec3f.DEFAULT_VALUE()
>
> # if _DEBUG: print('...DEBUG... set value to
> MFVec3f.DEFAULT_VALUE()=' + str(MFVec3f.DEFAULT_VALUE()))
>
> elif isinstance(value, list):
>
> for each in value: # check that elements are not tuples
>
> if isinstance(each, tuple):
>
> break
>
> else: # no tuples found, create 3-tuples
>
> value = [(x, y, z) for x, y, z in value]
>
> ### elif not isinstance(value, list) and isValidSFVec3f(value):
>
> ### print(' upcast to MF type', value)
>
> ### value = MFVec3f(SFVec3f(value))
>
> elif isinstance(value, list):
>
> if not value is None and not (isinstance(value,list) and
> len(value) == 0):
>
> _newValue = []
>
> for each in value:
>
> _newValue.append(SFVec3f(each).value)
>
> # if _DEBUG: print('...DEBUG... assign list, value=' +
> str(value), ', type=' + str(type(value)), ', _newValue=' +
> str(_newValue),flush=True)
>
> value = _newValue
>
> elif isinstance(value, str):
>
> value = [ float(value) ]
>
> self.__value = value
>
>
>
> # and
>
>
>
> def append(self, value=None):
>
> """ Add to existing value list, first ensuring that a correctly
> typed value is applied. """
>
> if not value is None:
>
>
>
> # if _DEBUG: print('...DEBUG... append to list, value=' +
> str(self.__value), ', type=' + str(type(self.__value)), ', value=' +
> str(value),flush=True)
>
> if isinstance(value,SFVec3f):
>
> self.__value.append(value.value) # dereference
>
> elif not isinstance(value,list) and not
> isinstance(value,MFVec3f):
>
> self.__value.append(SFVec3f(value).value) # checks validity
>
> elif (isinstance(value,list) and len(value) > 0) or
> isinstance(value,MFVec3f):
>
> for each in value:
>
> self.__value.append(SFVec3f(each).value) # checks
> validity
>
> elif isinstance(value,str):
>
> self.__value.append(SFVec3f(value).value) # checks validity
>
> ### if not value is None:
>
> ### if isValidSFVec3f(value):
>
> ### if isinstance(value, SFVec3f):
>
> ### value = SFVec3f(value).value # dereference value
> from base type
>
> ### self.__value.append(value)
>
> ### elif isValidMFVec3f(value):
>
> ### for each in value:
>
> ### while isinstance(each, list) and len(each) == 1:
>
> ### each = each[0] # dereference
>
> ### if isinstance(each, SFVec3f):
>
> ### each = each.value # dereference
>
> ### self.__value.append(each)
>
> ### else:
>
> ### assertValidMFVec3f(value) # report type failure
>
> def __bool__(self):
>
> if not isinstance(self.__value,list):
>
>
>
> print('*** x3d.py internal error, MFVec3f self.__value type='
> + str(type(self.__value)) + ' is not a list', flush=True)
>
> return len(self.__value) > 0
>
> # […snip…]
>
> ===========================
>
>
>
> all the best, Don
>
> --
>
> Don Brutzman Naval Postgraduate School, Code USW/Br
> brutzman at nps.edu
>
> Watkins 270, MOVES Institute, Monterey CA 93943-5000 USA
> +1.831.656.2149
>
> X3D graphics, virtual worlds, Navy robotics https://
> faculty.nps.edu/brutzman
>
>
>
> -----Original Message-----
> From: Brutzman, Donald (Don) (CIV) <brutzman at nps.edu>
> Sent: Sunday, February 27, 2022 7:42 AM
> To: vmarchetti at kshell.com
> Cc: X3D Public Mailing List (x3d-public at web3d.org) <x3d-public at web3d.org>;
> Hans Moritz Guenther <hgunther at mit.edu>; Brutzman, Donald (Don) (CIV) <
> brutzman at nps.edu>
> Subject: RE: example python code using numpy library
>
>
>
> [cc: Moritz]
>
>
>
> Looks like our enterprise mail server (configured by Microsoft in a cloud)
>
> scrubs all .py attachments.
>
>
>
> I was able to retrieve your example by going to the Web3D-archived version
>
> at
>
>
>
> *
> http://web3d.org/pipermail/x3d-public_web3d.org/2022-February/016818.html
>
>
>
> and then saving attachment.bin as NumpyExample.py
>
>
>
> Thank you Vince, looks interesting. Am also copying source here in case
>
> anyone has further retrieval difficulties.
>
>
>
> NumpyExample.py
>
> ======================================
>
> """
>
> Script to demonstrate setting the values of the coordinates, colors (by
>
> vertex), and index arrays defining
>
> an IndexedTriangleSet from data values in numpy arrays.
>
> Tested Feb 24 2022 with x3d version 4.0.51 installed with pip
>
> Vince Marchetti 24 Feb 2022
>
> license : https://creativecommons.org/licenses/by/4.0/
>
> """
>
> from x3d.x3d import *
>
> import numpy as np
>
> def colored_tetrahedron( radius ):
>
> """
>
> returns (3,) tuple of numpy arrays
>
> points_coordinate : a (N,3) array of vertex coordinates
>
> points_colors : (N,3) array of colors
>
> face_indices : (K,3) array of integer indices into points_* arrays
>
>
>
> where N = number of vertices in mesh (N=4 for this tetrahedron)
>
> K = number of triangle faces in mesh (K=5 for tetrahedron)
>
>
>
> defines a mesh for a tetrahedron inscribed in sphere of with radius
>
> specified by argument
>
> centered at origin
>
> """
>
> point_coordinates = np.array([
>
> ( 0.000, 1.000, 0.000),
>
> (-0.816, -0.344, 0.471),
>
> ( 0.816, -0.344, 0.471),
>
> ( 0.000, -0.344, -0.942),
>
> ]) * radius
>
>
>
> point_colors = np.array([
>
> (1.00,1.00,0.40),
>
> (0.70,0.40,1.00),
>
> (0.00,0.80,0.00),
>
> (1.00,0.80,0.90),
>
> ])
>
> face_indices = np.array([
>
> (0,1,2),
>
> (0,2,3),
>
> (0,3,1),
>
> (3,2,1)
>
> ])
>
>
>
> return point_coordinates,point_colors,face_indices
>
>
>
>
>
> point_coordinates,point_colors,face_indices = colored_tetrahedron( 2.0 )
>
> newModel=X3D(profile='Immersive',version='3.3',
>
> head=head(
>
> children=[
>
> meta(content='NumpyExample.x3d',name='title'),
>
> meta(content='example of using Numpy library to generate coordinate
>
> geometry and color',name='description'),
>
> meta(content='24 Feb 2022',name='created'),
>
> meta(content='Vince Marchetti',name='creator'),
>
> meta(content='https://www.web3d.org/x3d/content/examples/license.html
> ',name=
>
> 'license')
>
> ]),
>
> Scene=Scene(
>
>
>
> children=[
>
> WorldInfo(title='NumpyExample.x3d'),
>
> Viewpoint(DEF='ViewUpClose', description='Initial Viewpoint'),
>
> Shape(geometry=IndexedTriangleSet(
>
> # following code converts rank-2 numpy array of integers
>
> into a python list for setting value of index field
>
> index = list( face_indices.flatten() ),
>
>
>
> # following code converts rank-2 numpy array of float
> values
>
> into a Python list of Python tuples of floats
>
> # to set x3d values of type MFVec3f and MFColor
>
> coord = Coordinate( point = [ tuple(pt) for pt in
>
> point_coordinates] ),
>
> color = Color( color = [tuple(c) for c in point_colors])
>
> )
>
> )
>
> ])
>
> )
>
> newModelXML= newModel.XML()
>
> print(newModelXML)
>
> ======================================
>
>
>
> all the best, Don
>
> --
>
> Don Brutzman Naval Postgraduate School, Code USW/Br
> brutzman at nps.edu
>
> Watkins 270, MOVES Institute, Monterey CA 93943-5000 USA
> +1.831.656.2149
>
> X3D graphics, virtual worlds, Navy robotics
> https://faculty.nps.edu/brutzman
>
>
>
> -----Original Message-----
>
> From: vmarchetti at kshell.com <vmarchetti at kshell.com>
>
> Sent: Friday, February 25, 2022 3:50 AM
>
> To: X3D-Public <x3d-public at web3d.org>; Brutzman, Donald (Don) (CIV)
>
> <brutzman at nps.edu>
>
> Subject: example python code using numpy library
>
>
>
> Attached is a Python script that defines the coordinates, colors, and face
>
> indices for a tetrahedron as numpy rank-2 arrays, then converts those
> values
>
> in order to initialize the field values for an x3d IndexedTriangleSet node.
>
>
>
> This may serve as a demonstration example for using numpy together with
> the x3d package.
>
>
>
> This script runs with the pip installation of x3d and was tested at
> version 4.0.51
>
>
>
> Vince Marchetti
> _______________________________________________
> x3d-public mailing list
> x3d-public at web3d.org
> http://web3d.org/mailman/listinfo/x3d-public_web3d.org
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://web3d.org/pipermail/x3d-public_web3d.org/attachments/20220228/34dff0d2/attachment-0001.html>
More information about the x3d-public
mailing list