plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
ISET/iset3d-v3-master
piMateriallib.m
.m
iset3d-v3-master/utilities/material/piMateriallib.m
7,692
utf_8
c749aad8472e7fff50e23c46ebe245a1
function [materiallib_updated] = piMateriallib % A library of material properties (deprecated) % % Syntax: % materiallib = piMaterialib; % % Brief description: % All of the material definitions that we use in ISET3d are % represented in the materiallib. This function creates the material % lib with the specific parameters for each type of material. % % Inputs: % N/A % % Outputs: % materiallib: A structure with the different material definitions % % Description: % % The PBRT material properties include the specular and diffuse and % transparency material properties. The parameters to achieve these % effects are stored in this library for about a dozen different % material types. The definitions of the slots are defined on the % PBRT web-site (https://www.pbrt.org/fileformat-v3.html#materials) % % For the imported Cinema 4D scenes we know the material types of % each part, and ISET3d specifies in the recipe for each object an % object-specific name and a material type. The reflectance and % other material properties are stored in this material library. % % For example, if we want a particular part to look like, say % carpaint, we assign the materiallib.carpaint properties to that % object. % % Zhenyi Liu Scien Stanford, 2018 % % See also % piMaterial* % Examples: %{ %} %% carpaintmix % % A mixture of a specular (mirror like) material and a substrate % material that looks like a car. materiallib.carpaintmix.paint_mirror.stringtype = 'mirror'; materiallib.carpaintmix.paint_mirror.rgbkr = [.1 .1 .1]; materiallib.carpaintmix.paint_base.stringtype='substrate'; materiallib.carpaintmix.paint_base.colorkd = piColorPick('random'); materiallib.carpaintmix.paint_base.colorks =[.1 .1 .1]; materiallib.carpaintmix.paint_base.floaturoughness=0.01; materiallib.carpaintmix.paint_base.floatvroughness=0.01; materiallib.carpaintmix.carpaint.stringtype = 'mix'; materiallib.carpaintmix.carpaint.amount = 0.5; materiallib.carpaintmix.carpaint.stringnamedmaterial1 = 'paint_mirror'; materiallib.carpaintmix.carpaint.stringnamedmaterial2 = 'paint_base'; % materiallib.carpaintmix.paint_mirror=piMaterialCreate('paint_mirror', ... % 'type', 'mirror', ... % 'kr value', [0.1 0.1 0.1]); % materiallib.carpaintmix.paint_base = piMaterialCreate %% carpaint % % Typical car paint without much specularity. Some people define it % this way rather than as carpaintmix. % materiallib.carpaint.stringtype='substrate'; materiallib.carpaint.rgbkd = piColorPick('random'); materiallib.carpaint.rgbks =[.15 .15 .15]; materiallib.carpaint.floaturoughness =0.0005; materiallib.carpaint.floatvroughness=0.00051; %% chrome_spd % % This the chrome metal appearance. % materiallib.chrome_spd.stringtype='metal'; materiallib.chrome_spd.floatroughness=0.01; materiallib.chrome_spd.spectrumk='spds/metals/Ag.k.spd'; materiallib.chrome_spd.spectrumeta='spds/metals/Ag.eta.spd'; %% blackrubber % Good for tires materiallib.blackrubber.floatroughness = 0.5; materiallib.blackrubber.stringtype = 'uber'; materiallib.blackrubber.rgbkd = [ .01 .01 .01 ]; materiallib.blackrubber.rgbks = [ 0.2 .2 .2 ]; %% mirror materiallib.mirror.stringtype='mirror'; materiallib.mirror.spectrumkr = [400 1 800 1]; %% matte % Standard matte surface. Only diffuse. materiallib.matte.stringtype = 'matte'; %% plastic % Standard plastic appearance % materiallib.plastic.stringtype = 'plastic'; materiallib.plastic.rgbkd = [0.25 0.25 0.25]; materiallib.plastic.rgbks = [0.25 0.25 0.25]; materiallib.plastic.floatroughness = 0.1; %% glass % Standard glass appearance materiallib.glass.stringtype = 'glass'; % materiallib.glass.rgbkr = [0.00415 0.00415 0.00415]; materiallib.glass.spectrumkr = [400 1 800 1]; materiallib.glass.spectrumkt = [400 1 800 1]; materiallib.glass.eta = 1.5; %% Retroreflective materiallib.retroreflective.stringtype = 'retroreflective'; %% Uber materiallib.uber.stringtype = 'uber'; %% translucent materiallib.translucent.stringtype = 'translucent'; materiallib.translucent.colorreflect = [0.5 0.5 0.5]; materiallib.translucent.colortransmit = [0.5 0.5 0.5]; %% Human skin % Human skin is assigned this material. materiallib.skin.stringtype = 'kdsubsurface'; % The mean free path--the average distance light travels in the medium before scattering. % mfp = inverse sigma_t value of Jensen's skin1 parameters (in meters) materiallib.skin.colormfp = [1.2953e-03 9.5238e-04 6.7114e-04]; materiallib.skin.floaturoughness = 0.05; materiallib.skin.floateta = 1.333; materiallib.skin.floatvroughness = 0.05; materiallib.skin.boolremaproughness = 'false'; %% fourier materiallib.fourier.stringtype = 'fourier'; materiallib.fourier.bsdffile = 'bsdfs/roughglass_alpha_0.2.bsdf'; %% TotalReflect materiallib.totalreflect = piMaterialCreate('totalReflect',... 'type', 'matte', 'spectrum kd', [400 1 800 1]); %% materiallib_updated = piMaterialEmptySlot(materiallib); end function materiallib = piMaterialEmptySlot(materiallib) % Empty the unused material slot for certain type of material, for example, % mirror is only defined by reflectivity, since the default material % includes values for unused parameters, in this case, we should empty the % slots except Kr(reflectivity) to avoid errors when rendering. thisMaterial = fieldnames(materiallib); for ii = 1: length(thisMaterial) if isfield(materiallib.(thisMaterial{ii}), 'string') switch materiallib.(thisMaterial{ii}).stringtype case 'glass' materiallib.(thisMaterial{ii}).floatroughness = []; materiallib.(thisMaterial{ii}).rgbkr = []; materiallib.(thisMaterial{ii}).rgbks = []; materiallib.(thisMaterial{ii}).rgbkd = []; materiallib.(thisMaterial{ii}).rgbkt = []; case 'metal' materiallib.(thisMaterial{ii}).floatroughness = []; materiallib.(thisMaterial{ii}).rgbkr = []; materiallib.(thisMaterial{ii}).rgbks = []; materiallib.(thisMaterial{ii}).rgbkd = []; materiallib.(thisMaterial{ii}).rgbkt = []; case 'mirror' materiallib.(thisMaterial{ii}).floatroughness = []; materiallib.(thisMaterial{ii}).rgbkr = []; materiallib.(thisMaterial{ii}).rgbks = []; materiallib.(thisMaterial{ii}).rgbkd = []; materiallib.(thisMaterial{ii}).rgbkt = []; case 'skin' materiallib.(thisMaterial{ii}).floatroughness = []; materiallib.(thisMaterial{ii}).rgbkr = []; materiallib.(thisMaterial{ii}).texturekr = []; materiallib.(thisMaterial{ii}).texturebumpmap = []; materiallib.(thisMaterial{ii}).rgbkt = []; materiallib.(thisMaterial{ii}).stringnamedmaterial1 = []; materiallib.(thisMaterial{ii}).stringnamedmaterial2 = []; case 'fourier' materiallib.(thisMaterial{ii}).floatroughness = []; materiallib.(thisMaterial{ii}).rgbkr = []; materiallib.(thisMaterial{ii}).rgbks = []; materiallib.(thisMaterial{ii}).rgbkd = []; materiallib.(thisMaterial{ii}).rgbkt = []; case 'translucent' materiallib.(thisMaterial{ii}).floatroughness = []; materiallib.(thisMaterial{ii}).rgbkr = []; materiallib.(thisMaterial{ii}).rgbkt = []; case 'mix' materiallib.(thisMaterial{ii}).floatroughness = []; materiallib.(thisMaterial{ii}).rgbkr = []; materiallib.(thisMaterial{ii}).rgbks = []; materiallib.(thisMaterial{ii}).rgbkd = []; materiallib.(thisMaterial{ii}).rgbkt = []; end else continue end end end
github
ISET/iset3d-v3-master
piMaterialWrite.m
.m
iset3d-v3-master/utilities/material/piMaterialWrite.m
5,057
utf_8
d53176e3a5d12b14495036c7158f4dbf
function piMaterialWrite(thisR) %% % Synopsis: % piMaterialWrite(thisR) % % Brief description: % Write material and texture information in material pbrt file. % % Inputs: % thisR - recipe. % % Outputs: % None % % Description: % Write the material file from PBRT V3, as input from Cinema 4D % % The main scene file (scene.pbrt) includes a scene_materials.pbrt % file. This routine writes out the materials file from the % information in the recipe. % % ZL, SCIEN STANFORD, 2018 % ZLY, SCIEN STANFORD, 2020 %% p = inputParser; p.addRequired('thisR',@(x)isequal(class(x),'recipe')); p.parse(thisR); %% Create txtLines for texture struct array % Texture txt lines creation are moved into piTextureText function. if isfield(thisR.textures,'list') && ~isempty(thisR.textures.list) textureTxt = cell(1, thisR.textures.list.Count); textureKeys = keys(thisR.textures.list); for ii = 1:numel(textureKeys) textureTxt{ii} = piTextureText(thisR.textures.list(textureKeys{ii}), thisR); end else textureTxt = {}; end %% Parse the output file, working directory, stuff like that. % Commented by ZLY. Does this section do any work? %{ % Converts any jpg file names in the PBRT files into png file names ntxtLines=length(thisR.materials.txtLines); for jj = 1:ntxtLines str = thisR.materials.txtLines(jj); if piContains(str,'.jpg"') thisR.materials.txtLines(jj) = strrep(str,'jpg','png'); end if piContains(str,'.jpg "') thisR.materials.txtLines(jj) = strrep(str,'jpg ','png'); end % photoshop exports texture format with ".JPG "(with extra space) ext. if piContains(str,'.JPG "') thisR.materials.txtLines(jj) = strrep(str,'JPG ','png'); end if piContains(str,'.JPG"') thisR.materials.txtLines(jj) = strrep(str,'JPG','png'); end if piContains(str,'bmp') thisR.materials.txtLines(jj) = strrep(str,'bmp','png'); end if piContains(str,'tif') thisR.materials.txtLines(jj) = strrep(str,'tif','png'); end end %} %% Create txtLines for the material struct array if isfield(thisR.materials, 'list') && ~isempty(thisR.materials.list) materialTxt = cell(1, thisR.materials.list.Count); materialKeys= keys(thisR.materials.list); for ii=1:length(materialTxt) % Converts the material struct to text materialTxt{ii} = piMaterialText(thisR.materials.list(materialKeys{ii})); end else materialTxt{1} = ''; end %% Write to scene_material.pbrt texture-material file output = thisR.get('materials output file'); fileID = fopen(output,'w'); fprintf(fileID,'# Exported by piMaterialWrite on %i/%i/%i %i:%i:%0.2f \n',clock); if ~isempty(textureTxt) % Add textures for row=1:length(textureTxt) fprintf(fileID,'%s\n',textureTxt{row}); end end % Add the materials nPaintLines = {}; gg = 1; for dd = 1:length(materialTxt) if piContains(materialTxt{dd},'paint_base') &&... ~piContains(materialTxt{dd},'mix')||... piContains(materialTxt{dd},'paint_mirror') &&... ~piContains(materialTxt{dd},'mix') nPaintLines{gg} = dd; gg = gg+1; end end % Find material names contains 'paint_base' or 'paint_mirror' if ~isempty(nPaintLines) for hh = 1:length(nPaintLines) fprintf(fileID,'%s\n',materialTxt{nPaintLines{hh}}); materialTxt{nPaintLines{hh}} = []; end materialTxt = materialTxt(~cellfun('isempty',materialTxt)); % nmaterialTxt = length(materialTxt)-length(nPaintLines); for row=1:length(materialTxt) fprintf(fileID,'%s\n',materialTxt{row}); end else for row=1:length(materialTxt) fprintf(fileID,'%s\n',materialTxt{row}); end end %% Write media to xxx_materials.pbrt if ~isempty(thisR.media) for m=1:length(thisR.media.list) fprintf(fileID, piMediumText(thisR.media.list(m), thisR.get('working directory'))); end end fclose(fileID); [~,n,e] = fileparts(output); %fprintf('Material file %s written successfully.\n', [n,e]); end %% function that converts the struct to text function val = piMediumText(medium, workDir) % For each type of material, we have a method to write a line in the % material file. % val_name = sprintf('MakeNamedMedium "%s" ',medium.name); val = val_name; val_string = sprintf(' "string type" "%s" ',medium.type); val = strcat(val, val_string); resDir = fullfile(fullfile(workDir,'spds')); if ~exist(resDir,'dir') mkdir(resDir); end if ~isempty(medium.absFile) fid = fopen(fullfile(resDir,sprintf('%s_abs.spd',medium.name)),'w'); fprintf(fid,'%s',medium.absFile); fclose(fid); val_floatindex = sprintf(' "string absFile" "spds/%s_abs.spd"',medium.name); val = strcat(val, val_floatindex); end if ~isempty(medium.vsfFile) fid = fopen(fullfile(resDir,sprintf('%s_vsf.spd',medium.name)),'w'); fprintf(fid,'%s',medium.vsfFile); fclose(fid); val_floatindex = sprintf(' "string vsfFile" "spds/%s_vsf.spd"',medium.name); val = strcat(val, val_floatindex); end end
github
ISET/iset3d-v3-master
piColorPick.m
.m
iset3d-v3-master/utilities/scenes/piColorPick.m
2,044
utf_8
5fd33c3d0118bff80b7865f861992e73
function rgb = piColorPick(color,varargin) % Choose a pre-defined color or randomly pick one of the list % % Syntax % rgb = piColorPick(color,varargin) % % Description % For the moment, there is randomization of the returned color. We % get something in the range. We are going to create a key/value % pair that sets the randomization range or that turns off % randomization of the returned color. % % Inputs % color: 'red','blue','white','black','silver','yellow','random' % % Key/value pairs % N/A yet % % Outputs % rgb - red green blue triplet % % Zhenyi % % See also % piMaterialAssign % %% Parse % colorlist = {'white','black','red','blue','silver','yellow'}; %% if piContains(color,'random') % Choose a random color, I guess. index = rand; if index <= 0.35, color = 'white';end if index > 0.35 && index <= 0.75, color = 'black';end if index > 0.75 && index <= 0.8, color = 'red';end if index > 0.8 && index <= 0.85, color = 'blue';end if index > 0.85 && index <= 0.9, color = 'green';end if index > 0.95 && index <= 0.90, color = 'yellow';end if index > 0.90 && index <= 1.00, color = 'silver';end rgb = colorswitch(color); else rgb = colorswitch(color); end end function rgb = colorswitch(color) switch color case 'white' r = 254+rand(1); g = 253+rand(1); b = 250+rand(1); case 'black' r = 1+rand(1); g = 1+rand(1); b = 1+rand(1); case 'red' r = 134+rand(1); g = 1+rand(1); b = 17+rand(1); case 'blue' r = 22+rand(1); g = 54+rand(1); b = 114+rand(1); case 'green' r = 84+rand(1); g = 128+rand(1); b = 66+rand(1); case 'yellow' r = 223+rand(1); g = 192+rand(1); b = 99+rand(1); case 'silver' r = 192+rand(1); g = r; b = g; case 'gray' r = 169+rand(1); g = 169+rand(1); b = 169+rand(1); end rgb = [r/255 g/255 b/255]; end
github
ISET/iset3d-v3-master
piMediaWrite.m
.m
iset3d-v3-master/utilities/medium/piMediaWrite.m
1,325
utf_8
6e886532e54680146c276a1a96fc97f3
function piMediaWrite(thisR) % Write the material file from PBRT V3, as input from Cinema 4D % % The main scene file (scene.pbrt) includes a scene_materials.pbrt % file. This routine writes out the materials file from the % information in the recipe. % % HB, SCIEN STANFORD, 2020 %% p = inputParser; p.addRequired('thisR',@(x)isequal(class(x),'recipe')); p.parse(thisR); %% Empty any line that contains MakeNamedMaterial % The remaining lines have a texture definition. for mm=1:numel(thisR.media.list) thisR.media.txtLine{mm} = piMediumText(thisR.media.list(mm)); end %% Write to scene_material.pbrt texture-material file output = thisR.media.outputFile_media; fileID = fopen(output,'w'); fprintf(fileID,'# Exported by piMediaWrite on %i/%i/%i %i:%i:%0.2f \n',clock); for row=1:length(thisR.media.txtLine) fprintf(fileID,'%s\n',thisR.media.txtLine{row}); end fclose(fileID); [~,n,e] = fileparts(output); fprintf('Material file %s written successfully.\n', [n,e]); end %% function that converts the struct to text function val = piMediumText(medium) % For each type of material, we have a method to write a line in the % material file. % val_name = sprintf('MakeNamedMedium "%s" ',medium.name); val = val_name; val_string = sprintf(' "string type" "%s" ',medium.type); val = strcat(val, val_string); end
github
ISET/iset3d-v3-master
piRecipeUpdateAssets.m
.m
iset3d-v3-master/utilities/recipe/piRecipeUpdateAssets.m
2,055
utf_8
95865cfabbc234f9ecf31c401ef395bf
function thisR = piRecipeUpdateAssets(thisRV1) % Rearrange the assets in V1 format into V2 format % % Description: % Rearrange the assets with the new structure to make the old recipe % compatible. % %% p = inputParser; p.addRequired('thisRV1', @(x)isequal(class(x), 'recipe')); p.parse(thisRV1); %% Make sure the modern fields exist in all assets in the old format recipe fieldList = {"name", "index", "mediumInterface", "material",... "light", "areaLight", "shape", "output", "motion", "scale"}; for ii = 1:numel(thisR.assets) thisR.assets(ii).groupobjs = []; thisR.assets(ii).scale = [1, 1, 1]; if isempty(thisR.assets(ii).rotate) thisR.assets(ii).rotate = [0 0 0; 0 0 1; 0 1 0; 1 0 0]; end for jj = 1:numel(thisR.assets(ii).children) for kk = 1:numel(fieldList) if strcmp(fieldList{kk}, "scale") thisR.assets(ii).children(jj).(fieldList{kk}) = [1, 1, 1]; end if ~isfield(thisR.assets(ii).children(jj), fieldList{kk}) thisR.assets(ii).children(jj).(fieldList{kk}) = []; end end end end %% The old assets are flat structure. % We created a root node and put all the old assets into the groupobj. So % when new assets are created from the old ones, they will always be flat. % You'll have to rearrange if you want them to be hierarcichal. newAssets = createGroupObject(); newAssets.name = 'root'; newAssets.groupobjs = thisR.assets; % All the assets in the first and only level thisR.assets = newAssets; end function obj = createGroupObject() % Initialize a structure representing a group object. obj.name = []; obj.size.l = 0; obj.size.w = 0; obj.size.h = 0; obj.size.pmin = [0 0]; obj.size.pmax = [0 0]; obj.scale = [1 1 1]; obj.position = [0 0 0]; obj.rotate = [0 0 0; 0 0 1; 0 1 0; 1 0 0]; obj.children = []; obj.groupobjs = []; end
github
ISET/iset3d-v3-master
piRecipeUpdate.m
.m
iset3d-v3-master/utilities/recipe/piRecipeUpdate.m
3,992
utf_8
abbc915b5192c9992b47586b06723f99
function thisRV2 = piRecipeUpdate(thisRV2) % Convert a render recipe from V1 structure to V2 structure. % % Synopsis % thisRV2 = piRecipeUpdate(thisRV2) % % The change(s) are: % % 1. Change material format % 2. Extract texture from material slot and make it a separate slot. % 3. Rearrange assets to new tree structure % % Syntax: % % Description: % % Inputs: % thisR - recipe % % Outputs: % thisR - modified recipe % % % Zheng Lyu, 2020 %% Parse input p = inputParser; p.addRequired('thisRV2', @(x)isequal(class(x),'recipe')); p.parse(thisRV2); %% Lights thisRV2 = piRecipeUpdateLights(thisRV2); %% Materials an thisRV2 = piRecipeUpdateMaterials(thisRV2); %% Assets thisRV2 = piRecipeUpdateAssets(thisRV2); end function thisRV2 = piRecipeUpdateLights(thisRV2) thisRV2.lights = piLightGetFromText(thisRV2.world, 'print info', false); end function thisRV2 = piRecipeUpdateAssets(thisRV2) % Update the asset format % Each asset will become a node, these are the nodes at first level. nAssets = numel(thisRV2.assets); % Initialize the tree. assetsTree = tree('root'); for ii=1:nAssets thisAsset = thisRV2.assets(ii); % The V1 assets are a cell array and each entry can have multiple % children. But children do not have children. We attach the first level % to the root, and the children to the entry in the first level. % For every asset we figure out its node type thisNode = parseV1Assets(thisAsset); [assetsTree, id] = assetsTree.addnode(1, thisNode); % Check the children if isfield(thisAsset, 'children') && ~isempty(thisAsset.children) for jj=1:numel(thisAsset.children) childNode = parseV1Assets(thisAsset.children(jj)); % Add object index: index_objectname_O childNode.name = sprintf('%03d_%s',jj,childNode.name); assetsTree = assetsTree.addnode(id, childNode); end end end % Make the name unique thisRV2.assets = assetsTree.uniqueNames; end function node = parseV1Assets(thisAsset) % Rules: % If children is empty and material does not exist, it is a marker % and material exists, it is an object % % If children is not empty it is a branch. Version 1 has no slot for % lights. % if isfield(thisAsset, 'material') && ~isfield(thisAsset, 'children') % An object node = piAssetCreate('type', 'object'); node.name = strcat(thisAsset.name, '_O'); node.material = piParseGeometryMaterial(thisAsset.material); node.index = thisAsset.index; % Not clear node.shape.filename = thisAsset.output; elseif isfield(thisAsset, 'children') && isempty(thisAsset.children) % A marker node = piAssetCreate('type', 'marker'); node.size = thisAsset.size; node.size.pmin = node.size.pmin(:)'; node.size.pmax = node.size.pmax(:)'; node.name = strcat(thisAsset.name, '_M'); node.translation = thisAsset.position(:)'; node.rotation = thisAsset.rotate; if isfield(thisAsset, 'motion') node.motion = thisAsset.motion; end else % A branch node node = piAssetCreate('type', 'branch'); node.size = thisAsset.size; node.size.pmin = node.size.pmin(:)'; node.size.pmax = node.size.pmax(:)'; node.name = strcat(thisAsset.name, '_B'); node.translation = thisAsset.position(:)'; node.rotation = thisAsset.rotate; if isfield(thisAsset, 'motion') node.motion = thisAsset.motion; end end end function thisRV2 = piRecipeUpdateMaterials(thisRV2) % Update the materials AND textures %% In version 1 everything was in the materials text txtLines = thisRV2.materials.txtLines; % We parse the text into the format needed for the materials and textures, % separately, in Version 2 [thisRV2.materials.list, thisRV2.textures.list] = parseMaterialTexture(txtLines); end
github
ISET/iset3d-v3-master
piRecipeDefault.m
.m
iset3d-v3-master/utilities/recipe/piRecipeDefault.m
12,426
utf_8
2a817c33f6d7e99fbc671177cf2804d1
function thisR = piRecipeDefault(varargin) % Returns a recipe to an ISET3d standard scene % % Syntax % thisR = piRecipeDefault(varargin) % % Description: % piRecipeDefault reads in PBRT scene text files in the data/V3 % repository. It is also capable of using ieWebGet to retrieve pbrt % scenes, from the web and install them locally. % % Inputs % N/A - Default returns the MCC scene % % Optional key/val pairs % scene name - Specify a PBRT scene name from the data/V3 directory. % Here are some names: % MacBethChecker (default) % SimpleScene % checkerboard % slantedBar % chessSet % chessSetScaled % teapot % numbers at depth % % write - Call piWrite (default is false). Immediately writes into % iset3d/local, without any editing. % % Outputs % thisR - the ISET3d recipe with information from the PBRT scene file. % % % See also % @recipe, recipe.list % Examples: %{ thisR = recipe; thisR.list; %} %{ thisR = piRecipeDefault; piWrite(thisR); piWrite(thisR); scene = piRender(thisR,'render type','illuminant'); sceneWindow(scene); %} %{ thisR = piRecipeDefault('scene name','SimpleScene'); piWrite(thisR); scene = piRender(thisR); sceneWindow(scene); %} %{ thisR = piRecipeDefault; piWrite(thisR); scene = piRender(thisR,'render type','all'); sceneWindow(scene); %} %{ thisR = piRecipeDefault('scene name','checkerboard'); piWrite(thisR); scene = piRender(thisR); scene = piRender(thisR,'render type','illuminant'); sceneWindow(scene); %} %{ % #ETTBSkip - Zheng should look at and make fix the issue with the light. thisR = piRecipeDefault('scene name','slantedBar'); piWrite(thisR); scene = piRender(thisR,'render type','radiance'); scene = sceneSet(scene,'mean luminance',100); sceneWindow(scene); %} %{ thisR = piRecipeDefault('scene name','chessSet'); piWrite(thisR); scene = piRender(thisR, 'render type', 'both'); sceneWindow(scene); %} %{ thisR = piRecipeDefault('scene name','teapot'); piWrite(thisR); scene = piRender(thisR); sceneWindow(scene); %} %{ thisR = piRecipeDefault('scene name','MacBeth Checker CusLight'); piWrite(thisR); [scene, results] = piRender(thisR); sceneWindow(scene); %} %% Figure out the scene and whether you want to write it out varargin = ieParamFormat(varargin); p = inputParser; p.addParameter('scenename','MacBethChecker',@ischar); p.addParameter('write',false,@islogical); p.addParameter('loadrecipe',true,@islogical); % Load recipe if it exists % p.addParameter('verbose', 2, @isnumeric); p.parse(varargin{:}); sceneDir = p.Results.scenename; write = p.Results.write; loadrecipe = p.Results.loadrecipe; %% To read the file,the upper/lower case must be right % We check based on all lower case, but get the capitalization right by % assignment in the case switch ieParamFormat(sceneDir) case 'macbethchecker' sceneDir = 'MacBethChecker'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'macbethcheckerbox' sceneDir = 'MacBethCheckerBox'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'macbethcheckercus' sceneDir = 'MacBethCheckerCus'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case {'macbethcheckercb', 'mcccb'} sceneDir = 'mccCB'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'whiteboard' sceneDir = 'WhiteBoard'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'simplescene' sceneDir = 'SimpleScene'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'chessset' sceneDir = 'ChessSet'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'chesssetpieces' sceneDir = 'ChessSetPieces'; sceneFile = ['ChessSet','.pbrt']; exporter = 'C4D'; case 'chessset_2' sceneDir = 'ChessSet_2'; sceneFile = ['chessSet2','.pbrt']; exporter = 'Copy'; case 'chesssetscaled' sceneDir = 'ChessSetScaled'; sceneFile = [sceneDir,'.pbrt']; exporter = 'Copy'; case 'checkerboard' sceneDir = 'checkerboard'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'coloredcube' sceneDir = 'coloredCube'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'teapot' sceneDir = 'teapot'; sceneFile = 'teapot-area-light.pbrt'; exporter = 'Copy'; case 'slantedbar' % In sceneEye cases we were using piCreateSlantedBarScene. But % going forward we will use the Cinema 4D model so we can use the % other tools for controlling position, texture, and so forth. sceneDir = 'slantedBar'; sceneFile = 'slantedBar.pbrt'; exporter = 'C4D'; case 'slantedbarc4d' sceneDir = 'slantedBarC4D'; sceneFile = 'slantedBarC4D.pbrt'; exporter = 'C4D'; case 'slantedbarasset' sceneDir = 'slantedbarAsset'; sceneFile = 'slantedbarAsset.pbrt'; exporter = 'C4D'; case 'flatsurface' sceneDir = 'flatSurface'; sceneFile = 'flatSurface.pbrt'; exporter = 'C4D'; case 'stepfunction' sceneDir = 'stepfunction'; sceneFile = 'stepfunction.pbrt'; exporter = 'C4D'; case 'sphere' sceneDir = 'sphere'; sceneFile = 'sphere.pbrt'; exporter = 'C4D'; case 'flatsurfacewhitetexture' sceneDir = 'flatSurfaceWhiteTexture'; sceneFile = 'flatSurfaceWhiteTexture.pbrt'; exporter = 'C4D'; case 'flatsurfacerandomtexture' sceneDir = 'flatSurfaceRandomTexture'; sceneFile = 'flatSurfaceRandomTexture.pbrt'; exporter = 'C4D'; case 'flatsurfacemcctexture' sceneDir = 'flatSurfaceMCCTexture'; sceneFile = 'flatSurfaceMCCTexture.pbrt'; exporter = 'C4D'; case 'simplescenelight' sceneDir = 'SimpleSceneLight'; sceneFile = 'SimpleScene.pbrt'; exporter = 'C4D'; case 'macbethcheckercuslight' sceneDir = 'MacBethCheckerCusLight'; sceneFile = ['MacBethCheckerCus','.pbrt']; exporter = 'C4D'; case 'bunny' sceneDir = 'bunny'; sceneFile = ['bunny','.pbrt']; exporter = 'C4D'; case 'coordinate' sceneDir = 'coordinate'; sceneFile = ['coordinate','.pbrt']; exporter = 'C4D'; case {'cornellbox', 'cornell_box'} sceneDir = 'cornell_box'; sceneFile = ['cornell_box','.pbrt']; exporter = 'C4D'; case {'cornellboxbunnychart'} if loadrecipe && exist('Cornell_Box_Multiple_Cameras_Bunny_charts-recipe.mat','file') load('Cornell_Box_Multiple_Cameras_Bunny_charts-recipe.mat','thisR'); return; end sceneDir = 'Cornell_BoxBunnyChart'; sceneFile = ['Cornell_Box_Multiple_Cameras_Bunny_charts','.pbrt']; exporter = 'C4D'; case {'cornellboxreference'} % Main Cornell Box sceneDir = 'CornellBoxReference'; sceneFile = ['CornellBoxReference','.pbrt']; exporter = 'C4D'; case {'cornellboxlamp'} sceneDir = 'CornellBoxLamp'; sceneFile = ['CornellBoxLamp','.pbrt']; exporter = 'C4D'; case 'snellenatdepth' sceneDir = 'snellenAtDepth'; sceneFile = ['snellen','.pbrt']; exporter = 'Copy'; case 'numbersatdepth' sceneDir = 'NumbersAtDepth'; sceneFile = ['numbersAtDepth','.pbrt']; % mmUnits = true; exporter = 'Copy'; case 'lettersatdepth' sceneDir = 'lettersAtDepth'; sceneFile = [sceneDir,'.pbrt']; exporter = 'C4D'; case 'bathroom' sceneDir = 'bathroom'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'classroom' sceneDir = 'classroom'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'kitchen' sceneDir = 'kitchen'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'veach-ajar' sceneDir = 'veach-ajar'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'villalights' sceneDir = 'villaLights'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'plantsdusk' sceneDir = 'plantsDusk'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'livingroom' sceneDir = 'living-room'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'yeahright' sceneDir = 'yeahright'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'sanmiguel' warning('sanmiguel: Not rendering correctly yet.') sceneDir = 'sanmiguel'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'teapotfull' sceneDir = 'teapot-full'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case {'whiteroom', 'white-room'} sceneDir = 'white-room'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'bedroom' sceneDir = 'bedroom'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'colorfulscene' % djc -- This scene loads but on my machine pbrt gets an error: % "Unexpected token: "string mapname"" sceneDir = 'ColorfulScene'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case 'livingroom3' % Not running sceneDir = 'living-room-3'; sceneFile = 'scene.pbrt'; exporter = 'Copy'; case {'livingroom3mini', 'living-room-3-mini'} % Not running sceneDir = 'living-room-3-mini'; sceneFile = [sceneDir,'.pbrt']; exporter = 'Copy'; case {'blenderscene'} sceneDir = 'BlenderScene'; sceneFile = [sceneDir,'.pbrt']; exporter = 'Blender'; % Blender otherwise error('Can not identify the scene, %s\n',sceneDir); end %% See if we can find the file % Local if isequal(sceneDir,'BlenderScene') FilePath = fullfile(piRootPath,'data','blender','BlenderScene'); else FilePath = fullfile(piRootPath,'data','V3',sceneDir); end fname = fullfile(FilePath,sceneFile); if ~exist(fname,'file') fname = piSceneWebTest(sceneDir,sceneFile); end %% If we are here, we found the file. So create the recipe. % Parse the file contents into the ISET3d recipe and identify the type of % parser. C4D has special status. In other cases, such as the scenes from % the PBRT and Benedikt sites, we just copy the files into ISET3d/local. switch exporter case {'C4D','Copy'} thisR = piRead(fname, 'exporter', exporter); case 'Blender' thisR = piRead_Blender(fname,'exporter',exporter); otherwise error('Unknown export type %s\n',exporter); end thisR.set('exporter',exporter); % By default, do the rendering and mounting from ISET3d/local. That % directory is not part of the git upload area. % outFile = fullfile(piRootPath,'local',sceneName,[sceneName,'.pbrt']; [~,n,e] = fileparts(fname); outFile = fullfile(piRootPath,'local',sceneDir,[n,e]); thisR.set('outputfile',outFile); % Set defaults for very low resolution (for testing) thisR.integrator.subtype = 'path'; thisR.set('pixelsamples', 32); thisR.set('filmresolution', [320, 320]); % If no camera was included, add a pinhole by default. if isempty(thisR.get('camera')) thisR.set('camera',piCameraCreate('pinhole')); end %% If requested, write the files now % Usually, however, we edit the recipe before writing and rendering. if write piWrite(thisR); fprintf('%s: Using piWrite to save %s in iset3d/local.\n',mfilename, sceneDir); end end function fname = piSceneWebTest(sceneName,sceneFile) % Check for a web scene % See if the scene is already in data/V3/web FilePath = fullfile(piRootPath,'data','V3','web',sceneName); fname = fullfile(FilePath,sceneFile); % Download the file to data/V3/web if ~exist(fname,'file') % Download and confirm. piWebGet('resourcename', sceneName, 'resourcetype', 'pbrt', 'op', 'fetch', 'unzip', true); if ~exist(fname, 'file'), error('File not found'); end else fprintf('File found %s in data/V3/web.\n',sceneName) end end
github
ISET/iset3d-v3-master
piAssetGeneratePattern.m
.m
iset3d-v3-master/utilities/asset/piAssetGeneratePattern.m
5,381
utf_8
74e79853c59cd1f583245e5ca1f4083a
function [asset, assetPattern] = piAssetGeneratePattern(asset, varargin) %% varargin = ieParamFormat(varargin); p = inputParser; p.addRequired('asset', @isstruct); p.addParameter('algorithm', 'halfdivision', @ischar); % Uniform spread alg p.addParameter('sz', 1, @isnumeric); p.addParameter('coretrindex', -1, @isnumeric); p.parse(asset, varargin{:}); asset = p.Results.asset; algorithm = ieParamFormat(p.Results.algorithm); sz = p.Results.sz; coreTRIndex = p.Results.coretrindex; %% Generate vertices = piThreeDCreate(asset.shape.integerindices); vertices = vertices + 1; points = piThreeDCreate(asset.shape.pointp); TR = triangulation(vertices, points); %% switch algorithm case 'halfsplit' %% Generate verticeOne and verticeTwo vertice = TR.ConnectivityList; numVerticeOne = cast(size(vertice, 1)/2, 'uint32'); % Generate verticeOne verticesOne = zeros(numVerticeOne, size(vertice, 2)); for ii = 1:size(verticesOne, 1) verticesOne(ii, :) = vertice(ii, :); end % Generate verticeTwo verticesTwo = zeros(size(vertice, 1) - numVerticeOne, size(vertice, 2)); for ii = numVerticeOne + 1 : size(vertice, 1) verticesTwo(ii - numVerticeOne, :) = vertice(ii, :); end case 'uniformspread' %% if sz == -1, sz = randi([1, uint64((max(size(TR.Points(:)))))]); end if sz > max(size(TR.Points(:))), sz = max(size(TR.Points(:))); end edgesNum = size(TR.ConnectivityList, 1); % Randomly pick one triangle as start if sTriangleIndex is not defined (-1) if coreTRIndex == -1, coreTRIndex = randi(edgesNum); end %% Initialize the algorithm structure nCollection = neighbors(TR); %{ index = 1891; verticePlot(TR.ConnectivityList(index, :), TR) %} indexList = [coreTRIndex]; qTriangleIndex = [coreTRIndex]; qDepthList = [0]; verticesTwo = [TR.ConnectivityList(coreTRIndex, :)]; visited = zeros(1, edgesNum); visited(coreTRIndex) = 1; %% while(~isempty(qTriangleIndex)) thisIndex = qTriangleIndex(1); thisDepth = qDepthList(1); curDepth = thisDepth + 1; if curDepth <= sz % Find the neighbor triangles, push them in queue thisNeighbors = nCollection(thisIndex, :); for ii = 1:numel(thisNeighbors) if ~isnan(thisNeighbors(ii)) newIndex = thisNeighbors(ii); else % Although it's neighbor is NaN, it can still means it has % a hidden neighbor as the tricky points naming issue from % c4d PBRT exporter - a same point can be assigned with two % point labels! % Here is what we propose to do - based on thisIndex, we % know the points of that triangle (A, B and C). Get the % xyz value for the three points, check the combination and % see which other points have the same xyz value. Then % check which triangle also have that xyz combination as % well. thisVertice = TR.ConnectivityList(thisIndex, :); xyzVertice = TR.Points(thisVertice,:); extraPoints = setdiff(find(ismember(TR.Points, xyzVertice, 'rows')), thisVertice); newIndex = find(sum(ismember(TR.ConnectivityList, extraPoints), 2)... == numel(extraPoints) & numel(extraPoints) ~= 0); end if ~isempty(newIndex) if visited(newIndex) == 0 qTriangleIndex = [qTriangleIndex newIndex']; qDepthList = [qDepthList curDepth * ones(1, numel(newIndex))]; indexList = [indexList newIndex']; verticesTwo = [verticesTwo; TR.ConnectivityList(newIndex, :)]; visited(newIndex) = 1; end end end end % Finished researching, pop the current element qTriangleIndex(1) = []; qDepthList(1) = []; end %{ verticesPlot(verticesTwo, TR); verticesReset(TR); %} %% Write verticeOne indexListOne = setdiff(1:edgesNum, indexList); verticesOne = zeros(numel(indexListOne), size(TR.ConnectivityList, 2)); for ii = 1:numel(indexListOne) verticesOne(ii, :) = TR.ConnectivityList(indexListOne(ii), :); end end verticesOne = uint64(verticesOne - 1)'; verticesTwo = uint64(verticesTwo - 1)'; %% Create a new asset with new vertices assetPattern = asset; assetPattern.shape.integerindices = verticesTwo(:); asset.shape.integerindices = verticesOne(:); end %% Some useful functions for mesh visualization function verticesPlot(vertice, TR) close all trimesh(TR) tmpTR = triangulation(vertice, TR.Points); hold all trisurf(tmpTR); end function verticesReset(TR) hold off trimesh(TR) end
github
ISET/iset3d-v3-master
piReadDAT.m
.m
iset3d-v3-master/utilities/pbrt/piReadDAT.m
4,122
utf_8
939863c572c191a44386fa81ecbc7052
function [imageData, imageSize, lens] = piReadDAT(filename, varargin) %% Read multispectral data from a .dat file (Stanford format) % % [imageData, imageSize, lens] = piReadDAT(filename) % % Required Input % filename - existing .dat file % % Optional parameter/val % maxPlanes - % % Returns % % Reads multi-spectral .dat image data from the fiven filename. The .dat % format is described by Andy Lin on the Stanford Vision and Imaging % Science and Technology wiki: % http://white.stanford.edu/pdcwiki/index.php/PBRTFileFormat % % imageData = piReadDAT(filename, 'maxPlanes', maxPlanes) % Reads image data from the given file, and limits the number of returned % spectral planse to maxPlanes. Any additional planes are ignored. % % Returns a matrix of multispectral image data, with size [height width n], % where height and width are image size in pixels, and n is the number of % spectral planes. Also returns the multispectral image dimensions [height % width n]. % % If the given .dat file contains an optional lens description, also % returns a struct of lens data with fields focalLength, fStop, and % fieldOfView. % %%% RenderToolbox4 Copyright (c) 2012-2016 The RenderToolbox Team. %%% About Us://github.com/RenderToolbox/RenderToolbox4/wiki/About-Us %%% RenderToolbox4 is released under the MIT License. See LICENSE file. %% parser = inputParser(); parser.addRequired('filename', @ischar); parser.addParameter('verbose', 2, @isnumeric); parser.parse(filename, varargin{:}); filename = parser.Results.filename; verbosity = parser.Results.verbose; % imageData = []; % imageSize = []; lens = []; %% Open the file. if verbosity > 2 fprintf('Opening file "%s".\n', filename); end [fid, message] = fopen(filename, 'r'); if fid < 0, error(message); end %% Read header line to get image size sizeLine = fgetl(fid); dataPosition = ftell(fid); [imageSize, count, err] = lineToMat(sizeLine); if count ~=3 fclose(fid); error('Could not read image size: %s', err); end wSize = imageSize(1); hSize = imageSize(2); nPlanes = imageSize(3); imageSize = [hSize, wSize, nPlanes]; if verbosity > 1 fprintf(' Reading image h=%d x w=%d x %d spectral planes.\n', ... hSize, wSize, nPlanes); end %% Optional second header line might contain lens info. pbrtVer = 2; % By default, we assume this is a version 2 file headerLine = fgetl(fid); [lensData, count, err] = lineToMat(headerLine); %#ok<ASGLU> if count == 3 dataPosition = ftell(fid); lens.focalLength = lensData(1); lens.fStop = lensData(2); lens.fieldOfView = lensData(3); fprintf(' Found lens data focalLength=%d, fStop=%d, fieldOfView=%d.\n', ... lens.focalLength, lens.fStop, lens.fieldOfView); elseif (~isempty(strfind(headerLine,'v3'))) % If in the header line we get a 'v3' flag, we know its a version 3 % output file. dataPosition = ftell(fid); pbrtVer = 3; end %% Read the remainder of the .dat file into memory fseek(fid, dataPosition, 'bof'); serializedImage = fread(fid, inf, 'double'); fclose(fid); % Can un-comment if someone needs to know %fprintf(' Read %d pixel elements for image.\n', numel(serializedImage)); % Check size if numel(serializedImage) ~= prod(imageSize) error('Image should have %d pixel elements.\n', prod(imageSize)) end %% Reshape the serialized data to image dimensions % Depending on the PBRT version, we reshape differently. This is due to % inherent difference in how v2 and v3 store the final image data. It is % much easier to do the reshape here than to change v3 to write out in the % same way v2 writes out. if(pbrtVer == 2) imageData = reshape(serializedImage, hSize, wSize, nPlanes); elseif(pbrtVer == 3) imageData = reshape(serializedImage, wSize, hSize, nPlanes); imageData = permute(imageData,[2 1 3]); end % fprintf('OK.\n'); end %% function [mat, count, err] = lineToMat(line) % is it an actual line? if isempty(line) || (isscalar(line) && line < 0) mat = []; count = -1; err = 'Invalid line.'; return; end % scan line for numbers [mat, count, err] = sscanf(line, '%f', inf); end
github
ISET/iset3d-v3-master
piAssetsRebuild.m
.m
iset3d-v3-master/utilities/pbrt/piAssetsRebuild.m
1,993
utf_8
795b0fc6c9b8d4e6b8ae12e07495a679
function thisR = piAssetsRebuild(thisR) % % Description: % Rearrange the assets with the new structure to make the old recipe % compatible. % %% p = inputParser; p.addRequired('thisR', @(x)isequal(class(x), 'recipe')); p.parse(thisR); %% Make sure the modern fields exist in all assets in the old format recipe fieldList = {"name", "index", "mediumInterface", "material",... "light", "areaLight", "shape", "output", "motion", "scale"}; for ii = 1:numel(thisR.assets) thisR.assets(ii).groupobjs = []; thisR.assets(ii).scale = [1, 1, 1]; if isempty(thisR.assets(ii).rotate) thisR.assets(ii).rotate = [0 0 0; 0 0 1; 0 1 0; 1 0 0]; end for jj = 1:numel(thisR.assets(ii).children) for kk = 1:numel(fieldList) if strcmp(fieldList{kk}, "scale") thisR.assets(ii).children(jj).(fieldList{kk}) = [1, 1, 1]; end if ~isfield(thisR.assets(ii).children(jj), fieldList{kk}) thisR.assets(ii).children(jj).(fieldList{kk}) = []; end end end end %% The old assets are flat structure. % We created a root node and put all the old assets into the groupobj. So % when new assets are created from the old ones, they will always be flat. % You'll have to rearrange if you want them to be hierarcichal. newAssets = createGroupObject(); newAssets.name = 'root'; newAssets.groupobjs = thisR.assets; % All the assets in the first and only level thisR.assets = newAssets; end function obj = createGroupObject() % Initialize a structure representing a group object. obj.name = []; obj.size.l = 0; obj.size.w = 0; obj.size.h = 0; obj.size.pmin = [0 0]; obj.size.pmax = [0 0]; obj.scale = [1 1 1]; obj.position = [0 0 0]; obj.rotate = [0 0 0; 0 0 1; 0 1 0; 1 0 0]; obj.children = []; obj.groupobjs = []; end
github
ISET/iset3d-v3-master
writePFM.m
.m
iset3d-v3-master/utilities/pbrt/writePFM.m
1,310
utf_8
9237c69e65fe2310b2a7eea77f43e65a
% writePFM write an a matrix to a Portable Float Map Image. % % [] = writePFM( image, filename, scale ) % % When image is height x width x 3, the image is considered RGB. % When image is height x width, the image is considered grayscale. % scale must be a positive value indicating the overall intensity scale. function [] = writePFM( image, filename, scale ) if exist( 'scale', 'var' ), if scale <= 0, error( 'scale must be positive' ); end else scale = 1; end if size( image, 3 ) == 3 % RGB fid = fopen( filename, 'wb' ); fprintf( fid, 'PF\n' ); fprintf( fid, '%d %d\n', size( image,2 ), size( image, 1 ) ); fprintf( fid, '%f\n', -scale ); tmp( :, :, 1 ) = image( :, :, 1 )'; tmp( :, :, 2 ) = image( :, :, 2 )'; tmp( :, :, 3 ) = image( :, :, 3 )'; % fwrite( fid, tmp, 'float32' ); fwrite( fid, shiftdim( tmp, 2 ), 'float32' ); fclose( fid ); elseif size( image, 3 ) == 1 % Greyscale fid = fopen( filename, 'wb' ); fprintf( fid, 'Pf\n' ); fprintf( fid, '%d %d\n', size( image,2 ), size( image, 1 ) ); fprintf( fid, '%f\n', -scale ); fwrite( fid, image', 'float32' ); fclose( fid ); else error( 'Image must be RGB ( height x width x 3 ) or Grayscale (height x width)' ); end
github
ISET/iset3d-v3-master
readPFM.m
.m
iset3d-v3-master/utilities/pbrt/readPFM.m
1,646
utf_8
70b57ada40ef5141730fb13d94fce5fa
% read_pfm % % read_pfm( filename ) % Reads a Portable Float Map (PFM) from file located in filename % A greyscale PFM (header: 'Pf') is returned as a ( height x width ) % matrix % An RGB color PFM (header: 'PF') is returned as a ( height x width x 3 ) % matrix function image = readPFM( filename ) fid = fopen( filename ); % read header id = fgetl( fid ); imgsize = fgetl( fid ); % scale = fgetl( fid ); imgsize = strsplit(imgsize,' '); width = imgsize{1}; height = imgsize{2}; % TODO: deal with the stupid whitespace issue dim( 1 ) = sscanf( width, '%d' ); dim( 2 ) = sscanf( height, '%d' ); scale = fgetl( fid ); scale = sscanf( scale, '%f' ); % TODO: deal with endianness scale = abs( scale ); data = fread( fid, inf, 'float32' ); fclose( fid ); if strcmp( id, 'PF' ), % RGB % check size if size( data, 1 ) == 3 * prod( dim ), redIndices = 1 : 3 : size( data, 1 ); red = data( redIndices ); green = data( redIndices + 1 ); blue = data( redIndices + 2 ); % transpose image image = zeros( dim(2), dim(1), 3 ); image( :, :, 1 ) = reshape( red, dim(1), dim(2) )'; image( :, :, 2 ) = reshape( green, dim(1), dim(2) )'; image( :, :, 3 ) = reshape( blue, dim(1), dim(2) )'; else error( 'File size and image dimensions mismatched!' ); end elseif strcmp( id, 'Pf' ), % grey % check size if size( data, 1 ) == prod( dim ) image( :, : ) = reshape( data, dim(1), dim(2) )'; else error( 'File size and image dimensions mismatched!' ); end else error( 'Invalid file header!' ); end
github
ISET/iset3d-v3-master
piBlock2Struct.m
.m
iset3d-v3-master/utilities/pbrt/piBlock2Struct.m
3,923
utf_8
16620ac99360047b12e5878917303da3
% DEPRECATED function s = piBlock2Struct(blockLines,varargin) % Parse a block of scene file text (e.g. from piExtractBlock) and % return it as a structure % % s = piBlock2Struct(blockLines,varargin) % % Required input % blockLines - a block of text from the top of a scene.pbrt file % % Return % s - a struct containing the critical information from the block % of text. % % We take advantage of the regular structure of the PBRT file % (assuming it is "well structured") and use regular expressions to % extract values within. % % Example % txtLines = piRead('/home/wandell/pbrt-v2-spectral/pbrt-scenes/sanmiguel.pbrt'); % cameraBlock = piBlockExtract(txtLines,'blockName','camera') % cameraStruct = piBlock2Struct(cameraBlock) % % TL Scienstanford 2017 %% Programming TODO % % TODO: The struct converter doesn't quite capture all the variations it % needs to. For example, the spectrum type can be a string filename of a % spd file, but it can also be a vector that directly describes the spd % (e.g. [400 800 1]) % %% p = inputParser; p.addRequired('blockLines',@(x)(iscell(blockLines) && ~isempty(blockLines))); p.parse(blockLines,varargin{:}); %% Go through the text block, line by line, and try to extract the parameters nLines = length(blockLines); % Get the main type/subtype of the block (e.g. Camera: pinhole or % SurfaceIntegrator: path) % TL Note: This is a pretty hacky way to do it, you can probably do the % whole thing in one line using regular expressions. C = textscan(blockLines{1},'%s'); blockType = C{1}{1}; C = regexp(blockLines{1}, '(?<=")[^"]+(?=")', 'match'); blockSubtype = C{1}; % Set the main type and subtype s = struct('type',blockType,'subtype',blockSubtype); % Get all other parameters within the block % Generally they are in the form: % "type name" [value] or "type name" "value" for ii = 2:nLines currLine = blockLines{ii}; % Find everything between quotation marks ("type name") C = regexp(currLine, '(?<=")[^"]+(?=")', 'match'); C = strsplit(C{1}); valueType = C{1}; valueName = C{2}; % Get the value corresponding to this type and name if(strcmp(valueType,'string') || strcmp(valueType,'bool')) % Find everything between quotation marks C = regexp(currLine, '(?<=")[^"]+(?=")', 'match'); value = C{3}; elseif(strcmp(valueType,'spectrum')) %{ TODO: Spectrum can either be a spectrum file "xxx.spd" or it can be a series of four numbers [wave1 wave2 value1 value2]. There might be other variations, but we should check to see if brackets exist and to read numbers instead of a string if they do. %} % Find everything between quotation marks C = regexp(currLine, '(?<=")[^"]+(?=")', 'match'); value = C{3}; elseif(strcmp(valueType,'float') || strcmp(valueType,'integer')) % Find everything between brackets value = regexp(currLine, '(?<=\[)[^)]*(?=\])', 'match', 'once'); value = str2double(value); elseif(strcmp(valueType,'rgb')) % TODO: Find three values between the brackets, e.g. [r g b] end if(isempty(value)) % Some types can potentially be % defined as a vector, string, or float. We have to be able to % catch all those cases. Take a look at the "Parameter Lists" % in this document to see a few examples: % http://www.pbrt.org/fileformat.html#parameter-lists fprintf('Value Type: %s \n',valueType); fprintf('Value Name: %s \n',valueName); fprintf('Line to parse: %s \n',currLine) error('Parser cannot find the value associated with this type. The parser is still incomplete, so we cannot yet recognize all type cases.'); end % Set this value and type as a field in the structure [s.(valueName)] = struct('value',value,'type',valueType); end end
github
ISET/iset3d-v3-master
piFluorescentPattern.m
.m
iset3d-v3-master/utilities/fluorescent/piFluorescentPattern.m
12,558
utf_8
dbf807faf029c08894a2f305ed5d233d
function thisR = piFluorescentPattern(thisR, assetInfo, varargin) %% Apply pattern generation algorithms and change pbrt files for the pattern % % piFluorescentPattern % % Description: % Steps to add pattern on certain location area are: % (1) Based on the target location, read corresponding child geometry % pbrt file(s) % (2) Call piFluorescentDivision function to apply algorithm on the % geometry pbrt file(s) % % Inputs: % thisR - recipe of the scene % location - target region of pattern % base - create the fluorescent based on the base material % algorithm - the algorithm being used for pattern generation. The % default algorithm is 'half split', split the location % area into half and assign pattern on half of the whole % area % % Outputs: % None % % Authors: % ZLY, BW, 2020 % % See also: % t_piFluorescentPattern % % TODO: In the future, we want to assign the pattern within recipe. This % will be done when assets get updated. % % Algorithm input: % Half split: % % 02/11/2021 Update: % ZLY: Come to this round of updating: (1) creating patterns on assets % makes more sense since we have the tree assets structure. (2) The pattern % should be generated within recipe - creating new objects and then write % them out along with the old assets. %% % Examples %{ thisR = piRecipeDefault('scene name', 'slantedbar'); assetName = 'WhitePlane_O'; piFluorescentPattern(thisR, assetName, 'algorithm', 'half split'); %} %% Parse parameters varargin = ieParamFormat(varargin); p = inputParser; p.KeepUnmatched = true; vFunc = @(x)(isequal(class(x),'recipe')); p.addRequired('thisR',vFunc); p.addRequired('assetInfo', @(x)(ischar(x) || isnumeric(x))); p.addParameter('algorithm','halfsplit',@ischar); p.addParameter('type', 'add', @ischar); p.addParameter('fluoname', 'protoporphyrin', @ischar); p.addParameter('concentration', rand(1), @isnumeric); p.addParameter('coretrindex', -1, @isnumeric); p.addParameter('sz', 1, @isnumeric); p.addParameter('maxconcentration', 1, @isnumeric); p.addParameter('minconcentration', 0, @isnumeric); p.addParameter('maxsize', 1, @isnumeric); p.addParameter('minsize', 1, @isnumeric); p.addParameter('corenum', 1, @isnumeric); p.parse(thisR, assetInfo, varargin{:}); thisR = p.Results.thisR; assetInfo = p.Results.assetInfo; tp = p.Results.type; fluoName = p.Results.fluoname; algorithm = ieParamFormat(p.Results.algorithm); %% Set parameter values switch algorithm case 'halfsplit' concentration = p.Results.concentration; thisR = piFluorescentHalfSplit(thisR, assetInfo,... 'concentration', concentration,... 'fluoname', fluoName,... 'type', tp); case 'uniformspread' concentration = p.Results.concentration; coreTRIndex = p.Results.coretrindex; sz = p.Results.sz; thisR = piFluorescentUniformSpread(thisR, assetInfo,... 'concentration', concentration,... 'fluoname', fluoName,... 'sz', sz,... 'coretrindex', coreTRIndex,... 'type', tp); case 'multicore' maxConcentration = p.Results.maxconcentration; minConcentration = p.Results.minconcentration; maxSize = p.Results.maxsize; minSize = p.Results.minsize; coreNum = p.Results.corenum; thisR = piFluorescentMultiCore(thisR, assetInfo,... 'max concentration', maxConcentration,... 'min concentration', minConcentration,... 'max size', maxSize,... 'min size', minSize,... 'fluoname', fluoName,... 'core num', coreNum,... 'type', tp); otherwise error('Unknown algorithm: %s, maybe implement it in the future. \n', algorithm); end %% %{ %% Old version %% Parse parameters p = inputParser; p.KeepUnmatched = true; vFunc = @(x)(isequal(class(x),'recipe')); p.addRequired('thisR',vFunc); p.addRequired('matIdx', @(x)(ischar(x) || isnumeric(x))); p.addParameter('algorithm','halfsplit',@ischar); p.addParameter('type', 'add', @ischar); p.addParameter('fluoName', 'protoporphyrin', @ischar); p.parse(thisR, varargin{:}); thisR = p.Results.thisR; matIdx = p.Results.matIdx; type = p.Results.type; fluoName = p.Results.fluoName; algorithm = ieParamFormat(p.Results.algorithm); %% Address unmatched parameters switch algorithm case 'halfsplit' if isfield(p.Unmatched, 'concentration') concentration = p.Unmatched.concentration; else concentration = 1; end case 'corespread' % Concentration if isfield(p.Unmatched, 'concentration') concentration = p.Unmatched.concentration; else concentration = -1; end % coreTRIndex if isfield(p.Unmatched, 'coreTRIndex') coreTRIndex = p.Unmatched.coreTRIndex; else coreTRIndex = -1; end % sz if isfield(p.Unmatched, 'sz') sz = p.Unmatched.sz; else sz = -1; end case 'multicore' % Note: different from corespread where only one pattern will be % created: % maxConcentration: the max difference that % will be applied on the base pattern. % maxSz: the max size of the pattern % max concentration if isfield(p.Unmatched, 'maxConcentration') maxConcentration = p.Unmatched.maxConcentration; else maxConcentration = -1; end % min concentration if isfield(p.Unmatched, 'minConcentration') minConcentration = p.Unmatched.minConcentration; else minConcentration = 0; end % max size if isfield(p.Unmatched, 'maxSz') maxSz = p.Unmatched.maxSz; else maxSz = -1; end % min size if isfield(p.Unmatched, 'minSz') minSz = p.Unmatched.minSz; else minSz = 0; end if isfield(p.Unmatched, 'coreNum') coreNum = p.Unmatched.coreNum; else coreNum = -1; end end %% Convert baseMaterial and targetMaterial into index if not if ischar(matIdx) matIdx = piMaterialFind(thisR, 'name', matIdx); end %% Get material name matName = piMaterialGet(thisR, 'idx', matIdx, 'param','name'); %% Read child geometry files from the written pbrt files [Filepath,sceneFileName] = fileparts(thisR.outputFile); % Find the corresponding child geometry files based on the region name rootGeometryFile = fullfile(Filepath, sprintf('%s_geometry.pbrt',sceneFileName)); fid_rtGeo = fopen(rootGeometryFile,'r'); tmp = textscan(fid_rtGeo,'%s','Delimiter','\n'); rtGeomTxtLines = tmp{1}; % We change the last object if selected material is used more than once. % With NamedMaterial line, we can make sure the line below is the child % geometry path. index = find(contains(rtGeomTxtLines, strcat("NamedMaterial ", '"', matName)),1,'last') + 1; % Need to see next line tmp = strsplit(rtGeomTxtLines{index}, '"'); % Complete the child Geometry Path childGeometryPath = fullfile(Filepath, tmp{2}); % Edit the "unhealthy" region fid_obj = fopen(childGeometryPath,'r'); tmp = textscan(fid_obj,'%s','Delimiter','\n'); txtLines = tmp{1}; txtLines = strsplit(txtLines{1}, {'[',']'}); indicesStr = txtLines{2}; pointsStr = txtLines{4}; vertices = threeDCreate(indicesStr); vertices = vertices + 1; % Process the points (seems won't be used) points = threeDCreate(pointsStr); %% Create triangulation object using MATLAB Computational Geometry toolbox TR = triangulation(vertices, points); %{ % Visualization trimesh(TR); %} %% Apply algorithm for mesh split switch algorithm case 'halfsplit' piFluorescentHalfDivision(thisR, TR, childGeometryPath,... txtLines, matIdx,... 'fluoName', fluoName,... 'concentration', concentration,... 'type', type); case 'corespread' piFluorescentCoreSpread(thisR, TR, childGeometryPath, txtLines, matIdx,... 'type', type,... 'concentration', concentration,... 'fluoName', fluoName,... 'sz', sz,... 'coreTRIndex', coreTRIndex); %{ if isfield(p.Unmatched, 'depth') if isfield(p.Unmatched, 'sTriangleIndex') piFluorescentUniformSpread(thisR, TR, childGeometryPath,... txtLines, base, location, type,... 'depth', p.Unmatched.depth,... 'sTriangleIndex', p.Unmatched.sTriangleIndex); else piFluorescentUniformSpread(thisR, TR, childGeometryPath,... txtLines, base, location, type,... 'depth', p.Unmatched.depth); end else if isfield(p.Unmatched, 'sTriangleIndex') piFluorescentUniformSpread(thisR, TR, childGeometryPath,... txtLines, base, location, type,... 'sTriangleIndex', p.Unmatched.sTriangleIndex); else piFluorescentUniformSpread(thisR, TR, childGeometryPath,... txtLines, base, location, type); end end %} case 'multicore' piFluorescentMultiCore(thisR, TR, childGeometryPath, txtLines, matIdx,... 'type', type,... 'fluoName', fluoName,... 'maxConcentration', maxConcentration,... 'minConcentration', minConcentration,... 'maxSz', maxSz,... 'minSz', minSz,... 'coreNum', coreNum); %{ if isfield(p.Unmatched, 'maxDepth') if isfield(p.Unmatched, 'coreNumber') piFluorescentMultiUniform(thisR, TR, childGeometryPath,... txtLines, base, location, type,... 'maxDepth', p.Unmatched.maxDepth,... 'coreNumber', p.Unmatched.coreNumber); else piFluorescentMultiUniform(thisR, TR, childGeometryPath,... txtLines, base, location, type,... 'maxDepth', p.Unmatched.maxDepth); end else if isfield(p.Unmatched, 'coreNumber') piFluorescentMultiUniform(thisR, TR, childGeometryPath,... txtLines, base, location, type,... 'coreNumber', p.Unmatched.coreNumber); else piFluorescentMultiUniform(thisR, TR, childGeometryPath,... txtLines, base, location, type); end end %} case 'irregular' piFluorescentIrregular(thisR, TR, childGeometryPath, txtLines, base,... location, type); otherwise error('Unknown algorithm: %s, maybe implement it in the future. \n', algorithm); end end %% function points = threeDCreate(pointsStr) % Create cell array from a string. Suitable for situations where every % three numbers are considered as a data point. pointsNum = str2num(pointsStr); points = []; % xyz position & triangle mesh for ii = 1:numel(pointsNum)/3 pointList = zeros(1, 3); for jj = 1:3 pointList(jj) = pointsNum((ii - 1) * 3 + jj); end points = [points; pointList]; end end %} end
github
ISET/iset3d-v3-master
piFluorescentMultiCore.m
.m
iset3d-v3-master/utilities/fluorescent/algorithms/piFluorescentMultiCore.m
5,994
utf_8
dc5defa7a3dc6cd0783faa02aa06e085
function thisR = piFluorescentMultiCore(thisR, assetInfo, varargin) %% Generate multiple uniformly spreaded pattern on target location % % piFluorescentMultiUniform % % Description: % Generate several patterns on target location % % Inputs: % thisR - scene recipe % TR - triangulation object % childGeometryPath - path to the child pbrt geometry files % txtLines - geometry file text lines % matIdx - material index % Optional: % type - add/reduce % fluoName - name of fluorophore % maxConcentration - max concentration of new fluorophore % maxSz - max size of pattern % coreNum - number of patterns % % Outputs: % None. % % Authors: % ZLY, BW, 2020 % Examples: %{ ieInit; if ~piDockerExists, piDockerConfig; end thisR = piRecipeDefault('scene name', 'sphere'); piMaterialPrint(thisR); piLightDelete(thisR, 'all'); thisR = piLightAdd(thisR,... 'type','distant',... 'light spectrum','OralEye_385',... 'spectrumscale', 1,... 'cameracoordinate', true); piWrite(thisR); %{ scene = piRender(thisR); sceneWindow(scene); %} thisIdx = 1; piFluorescentPattern(thisR, thisIdx, 'algorithm', 'multi core',... 'fluoName','protoporphyrin','maxSz', 10,... 'maxConcentration', 1, 'coreNum', 10); wave = 365:5:705; thisDocker = 'vistalab/pbrt-v3-spectral:basisfunction'; [scene, result] = piRender(thisR, 'dockerimagename', thisDocker,'wave', wave, 'render type', 'radiance'); sceneWindow(scene) %} %% varargin = ieParamFormat(varargin); p = inputParser; p.addRequired('thisR', @(x)isequal(class(x), 'recipe')); p.addRequired('assetInfo', @(x)(ischar(x) || isnumeric(x))); p.addParameter('fluoname', 'protoporphyrin', @ischar); p.addParameter('maxconcentration', 1, @isnumeric); p.addParameter('minconcentration', 1, @isnumeric); p.addParameter('maxsize', 1, @isnumeric); p.addParameter('minsize', 1, @isnumeric); p.addParameter('corenum', 3, @isnumeric); p.addParameter('type', 'add', @ischar); p.parse(thisR, assetInfo, varargin{:}); thisR = p.Results.thisR; assetInfo = p.Results.assetInfo; fluoName = p.Results.fluoname; maxConcentration = p.Results.maxconcentration; minConcentration = p.Results.minconcentration; maxSize = p.Results.maxsize; minSize = p.Results.minsize; coreNum = p.Results.corenum; tp = p.Results.type; %% sfConHigh = 1; sfConLow = 0.5; sfSzHigh = 0.3; sfSzLow = 0.1; for ii=1:coreNum thisConcentration = (maxConcentration - minConcentration) * ((sfConHigh - sfConLow) * rand(1) + sfConLow)... + minConcentration; thisSz = uint64((maxSize - minSize) * ((sfSzHigh - sfSzLow) * rand(1) + sfSzLow) + minSize); thisR = piFluorescentUniformSpread(thisR, assetInfo,... 'concentration', thisConcentration,... 'fluoname', fluoName,... 'sz', thisSz,... 'type', tp,... 'number', ii); % Gradually decrease max concentration if ii > 0.1 * coreNum sfConHigh = 0.5; sfConLow = 0.25; sfSzHigh = 0.5; sfSzLow = 0.3; elseif ii > 0.5 * coreNum sfConHigh = 0.25; sfConLow = 0.125; sfSzHigh = 0.7; sfSzLow = 0.5; elseif ii > 0.8 * coreNum sfConHigh = 0.125; sfConLow = 0.0626; sfSzHigh = 1; sfSzLow = 0.7; end end %% Old version %{ %% Parse input p = inputParser; p.addRequired('thisR', @(x)isequal(class(x), 'recipe')); p.addRequired('TR'); p.addRequired('childGeometryPath', @ischar); p.addRequired('txtLines', @iscell); p.addRequired('matIdx', @(x)(ischar(x) || isnumeric(x))); p.addParameter('type', 'add',@ischar); p.addParameter('fluoName', 'protoporphyrin', @ischar); p.addParameter('maxConcentration', -1, @isscalar); p.addParameter('minConcentration', 0, @isscalar); p.addParameter('maxSz', -1, @isscalar); p.addParameter('minSz', 0, @isscalar); p.addParameter('coreNum', 1, @isscalar); p.parse(thisR, TR, childGeometryPath, txtLines, matIdx, varargin{:}); thisR = p.Results.thisR; TR = p.Results.TR; childGeometryPath = p.Results.childGeometryPath; txtLines = p.Results.txtLines; matIdx = p.Results.matIdx; type = p.Results.type; fluoName = p.Results.fluoName; maxConcentration = p.Results.maxConcentration; minConcentration = p.Results.minConcentration; maxSz = p.Results.maxSz; minSz = p.Results.minSz; coreNum = p.Results.coreNum; %% Initialize parameters if maxSz == -1, maxSz = randi([1, uint64((max(TR.Points(:))))]); end if maxConcentration == -1, maxConcentration = 1; end %% generate a list of cores and depths % tip: randi(indexRange, dimention) szList = (maxSz - minSz) * randi(maxSz, 1, coreNum) + minSz; concentrationList = (maxConcentration - minConcentration) * rand(1, coreNum) + minConcentration; curTR = TR; verticeHis = cell(1, coreNum); for ii = 1:coreNum curCore = randi(size(curTR.ConnectivityList, 1)); curVertice = piFluorescentCoreSpread(thisR, curTR, childGeometryPath,... txtLines, matIdx,... 'type', type,... 'concentration', concentrationList(ii),... 'fluoName', fluoName,... 'sz', szList(ii),... 'coreTRIndex', curCore); if ~isempty(curVertice) curTR = triangulation(curVertice, TR.Points); verticeHis{ii} = curVertice; else warning('Generated fewer cores. Returning...') break; end %{ verticesPlot(curVertice, TR); %} end end %% Some useful functions for mesh visualization function verticesPlot(vertice, TR) close all trimesh(TR) tmpTR = triangulation(vertice, TR.Points); hold all trisurf(tmpTR); end function verticesReset(TR) hold off trimesh(TR) end %}
github
ISET/iset3d-v3-master
piFluorescentUniformSpread.m
.m
iset3d-v3-master/utilities/fluorescent/algorithms/piFluorescentUniformSpread.m
7,890
utf_8
6b0c43bd93eb2a7014a0d8831275f398
function thisR = piFluorescentUniformSpread(thisR, assetInfo, varargin) %% Generate a pattern from single triangle % % piFluorescentUniformSpread % % Description: % Generate an unifrom oriented pattern from a random single triangle % % Inputs: % thisR - scene recipe % TR - triangulation object % childGeometryPath - path to the child pbrt geometry files % indices - triangle meshes in the scene % txtLines - geometry file text lines % base - reference material % location - target locaiton for pattern % depth - steps from center of the pattern % sTriangleIndex - vertex index number(seed for the pattern) % % Ouputs: % None % % Examples: %{ ieInit; if ~piDockerExists, piDockerConfig; end thisR = piRecipeDefault('scene name', 'sphere'); piMaterialPrint(thisR); piLightDelete(thisR, 'all'); thisR = piLightAdd(thisR,... 'type','distant',... 'light spectrum','OralEye_385',... 'spectrumscale', 1,... 'cameracoordinate', true); piWrite(thisR); %{ scene = piRender(thisR); sceneWindow(scene); %} thisIdx = 1; piFluorescentPattern(thisR, thisIdx, 'algorithm', 'core spread',... 'fluoName','protoporphyrin','sz', 10,... 'concentration', 1); wave = 365:5:705; thisDocker = 'vistalab/pbrt-v3-spectral:basisfunction'; [scene, result] = piRender(thisR, 'dockerimagename', thisDocker,'wave', wave, 'render type', 'radiance'); sceneWindow(scene) %} %% varargin = ieParamFormat(varargin); p = inputParser; p.addRequired('thisR', @(x)isequal(class(x), 'recipe')); p.addRequired('assetInfo', @(x)(ischar(x) || isnumeric(x))); p.addParameter('concentration', rand(1), @isnumeric); p.addParameter('fluoname', 'protoporphyrin', @ischar); p.addParameter('sz', 1, @isnumeric); p.addParameter('coretrindex', -1, @isnumeric); p.addParameter('type', 'add', @ischar); p.addParameter('number', 2, @isnumeric); p.parse(thisR, assetInfo, varargin{:}); thisR = p.Results.thisR; assetInfo = p.Results.assetInfo; concentration = p.Results.concentration; fluoname = p.Results.fluoname; tp = p.Results.type; number = p.Results.number; sz = p.Results.sz; coreTRIndex = p.Results.coretrindex; %% Get material info matName = thisR.get('asset',assetInfo, 'material name'); %% Create a new material matPattern = thisR.get('material', matName); matPattern = piMaterialSet(matPattern,... 'name', sprintf('%s_%s_#%d', matName, fluoname, number)); matPattern = piMaterialApplyFluorescence(matPattern,... 'type', tp,... 'fluoname', fluoname,... 'concentration', concentration); thisR.set('material', 'add', matPattern); %% Get verticies and points asset = thisR.get('assets', assetInfo); %% Generate new asset with pattern [asset, assetPattern] = piAssetGeneratePattern(asset,... 'algorithm', 'uniform spread',... 'sz', sz,... 'coretrindex', coreTRIndex); % Update name assetPattern.name = sprintf('%s_%s_#%d_O',... asset.name, fluoname, number); % Update material name assetPattern.material.namedmaterial = matPattern.name; % Add new asset parentAsset = thisR.get('asset parent', asset.name); thisR.set('asset', parentAsset.name, 'add', assetPattern); thisR.set('asset', asset.name, 'shape', asset.shape); %% Old version %{ %% Parse the input p = inputParser; p.addRequired('thisR', @(x)isequal(class(x), 'recipe')); p.addRequired('TR'); p.addRequired('childGeometryPath', @ischar); p.addRequired('txtLines', @iscell); p.addRequired('matIdx', @(x)(ischar(x) || isnumeric(x))); p.addParameter('type', 'add',@ischar); p.addParameter('concentration', -1, @isnumeric); p.addParameter('fluoName', 'protoporphyrin', @ischar); p.addParameter('sz', -1, @isscalar) p.addParameter('coreTRIndex', -1, @isscalar) p.parse(thisR, TR, childGeometryPath, txtLines,... matIdx, varargin{:}); thisR = p.Results.thisR; TR = p.Results.TR; childGeometryPath = p.Results.childGeometryPath; txtLines = p.Results.txtLines; matIdx = p.Results.matIdx; tp = p.Results.type; fluoName = p.Results.fluoName; concentration = p.Results.concentration; sz = p.Results.sz; coreTRIndex = p.Results.coreTRIndex; %% Parameter initialize if concentration == -1, concentration = rand(1); end if sz == -1, sz = randi([1, uint64((max(TR.Points(:))))]); end edgesNum = size(TR.ConnectivityList, 1); % Randomly pick one triangle as start if sTriangleIndex is not defined (-1) if coreTRIndex == -1, coreTRIndex = randi(edgesNum); end %% Initialize the algorithm structure nCollection = neighbors(TR); %{ index = 1891; verticePlot(TR.ConnectivityList(index, :), TR) %} indexList = [coreTRIndex]; qTriangleIndex = [coreTRIndex]; qDepthList = [0]; verticesTwo = [TR.ConnectivityList(coreTRIndex, :)]; visited = zeros(1, edgesNum); %% while(~isempty(qTriangleIndex)) thisIndex = qTriangleIndex(1); thisDepth = qDepthList(1); curDepth = thisDepth + 1; if curDepth <= sz % Find the neighbor triangles, push them in queue thisNeighbors = nCollection(thisIndex, :); for ii = 1:numel(thisNeighbors) if ~isnan(thisNeighbors(ii)) newIndex = thisNeighbors(ii); else % Although it's neighbor is NaN, it can still means it has % a hidden neighbor as the tricky points naming issue from % c4d PBRT exporter - a same point can be assigned with two % point labels! % Here is what we propose to do - based on thisIndex, we % know the points of that triangle (A, B and C). Get the % xyz value for the three points, check the combination and % see which other points have the same xyz value. Then % check which triangle also have that xyz combination as % well. thisVertice = TR.ConnectivityList(thisIndex, :); xyzVertice = TR.Points(thisVertice,:); extraPoints = setdiff(find(ismember(TR.Points, xyzVertice, 'rows')), thisVertice); newIndex = find(sum(ismember(TR.ConnectivityList, extraPoints), 2)... == numel(extraPoints) & numel(extraPoints) ~= 0); end if ~isempty(newIndex) if visited(newIndex) == 0 qTriangleIndex = [qTriangleIndex newIndex']; qDepthList = [qDepthList curDepth * ones(1, numel(newIndex))]; indexList = [indexList newIndex']; verticesTwo = [verticesTwo; TR.ConnectivityList(newIndex, :)]; visited(newIndex) = 1; end end end end % Finished researching, pop the current element qTriangleIndex(1) = []; qDepthList(1) = []; end %{ verticesPlot(verticesTwo, TR); verticesReset(TR); %} %% Write verticeOne indexListOne = setdiff(1:edgesNum, indexList); verticesOne = zeros(numel(indexListOne), size(TR.ConnectivityList, 2)); for ii = 1:numel(indexListOne) verticesOne(ii, :) = TR.ConnectivityList(indexListOne(ii), :); end %% Go edit PBRT files piFluorescentPBRTEdit(thisR, childGeometryPath, txtLines,... matIdx, verticesOne, verticesTwo, tp,... fluoName, concentration); end %% Some useful functions for mesh visualization function verticesPlot(vertice, TR) close all trimesh(TR) tmpTR = triangulation(vertice, TR.Points); hold all trisurf(tmpTR); end function verticesReset(TR) hold off trimesh(TR) end %}
github
ISET/iset3d-v3-master
piBlender2C4D.m
.m
iset3d-v3-master/utilities/blender/piBlender2C4D.m
33,904
utf_8
9d6dcd7e8c192950425ec7e8f7e25037
function fname = piBlender2C4D(fname) % Converts the exported blender files into C4D format % % Synopsis % fname = piBlender2C4D(fname); % % Input: % fname - PBRT file exported by Blender % % Output % fnane - new filename for C4D compliant file % % Description % This function creates the material and geometry files from the exported % Blender PBRT file. After this function has run, the format should % comply with the C4D exported format. That way we can run the usual set % of functions. % % See also % piRead % % Example: %{ % See s_blenderTest %} %% Copy the original Blender exported files to a new directory [sourceDir,sceneName,ext] = fileparts(fname); [~,destDirName] = fileparts(sourceDir); destDir = fullfile(piRootPath,'local',[destDirName,'_C4D']); copyfile(sourceDir,destDir); %% We convert the files in the new directory to C4D format fname = fullfile(destDir,[sceneName,ext]); [txtLines, header] = piReadText(fname); thisR = recipe; thisR.exporter = 'Blender'; thisR.inputFile = fname; %% Split text lines into pre-WorldBegin and WorldBegin sections txtLines = piReadWorldText(thisR,txtLines); %% Set flag indicating whether this is exported Cinema 4D file % exporterFlag = piReadExporter(thisR,header); piReadExporter(thisR,header); %% If this is an exported Blender file: % 1) rewrite 'txtLines' in C4D format % 2) create materials and geometry files in C4D format % 3) rewrite 'thisR.world' in C4D format % 4) extract geometry information from .ply functions in the geometry file % 5) convert the coordinate system from right-handed to left-handed % 6) calculate 'Vector' information in the geometry file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: section added % to rewrite a pbrt file exported from Blender into the format of pbrt % files exported from C4D % NOTE: this is a new helper function % that rewrites 'txtLines' in C4D format txtLines = piWriteC4Dformat_txt(txtLines); % NOTE: this is a new helper function % that creates materials and geometry files in C4D format % (the Blender exporter does not create materials and geometry files) piWriteC4Dformat_files(thisR); % NOTE: this is a new helper function % that rewrites 'thisR.world' in C4D format thisR = piWriteC4Dformat_world(thisR); % NOTE: this is a new helper function % that extracts geometry information from .ply functions in the % geometry file % NOTE: this is currently called for Blender exports only % but should be useful for converting any .ply functions piWriteC4Dformat_ply(thisR); % NOTE: this is a new helper function % that converts a right-handed coordinate system into the left-handed % pbrt system % NOTE: this function should always be called once for Blender exports % because Blender uses a right-handed coordinate system piWriteC4Dformat_handedness(thisR); % NOTE: this is a new helper function % that calculate 'Vector' information in the geometry file % NOTE: this function should always be called for Blender exports % because the Blender exporter does not include vector information % automatically, but should be useful for any pbrt files without Vector % information included piWriteC4Dformat_vector(thisR); %% Set thisR.lookAt and determine if we need to flip the image [flip, thisR] = piReadLookAt(thisR,txtLines); % Sometimes the axis flip is "hidden" in the concatTransform matrix. In % this case, the flip flag will be true. When the flip flag is true, we % always output Scale -1 1 1. % ZLY: when flip is not true, it means there is no need for flipping, we % will get rid of the Scale -1 1 1 section if ~flip scaleIdx = find(piContains(txtLines, 'Scale -1 1 1')); if ~isempty(scaleIdx) txtLines(scaleIdx) = []; end end % Override the original lookAt block with the look at in the PBRT % coordinate. lookAtIdx = find(piContains(txtLines, 'LookAt')); if ~isempty(lookAtIdx) from = thisR.get('from'); to = thisR.get('to'); up = thisR.get('up'); txtLines{lookAtIdx} = sprintf('LookAt %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f \n', ... [from(:); to(:); up(:)]); end % Erase Transform, ConcatTransform since all the transformations are included % in lookAt transformIdx = find(piContains(txtLines, 'Transform')); if ~isempty(transformIdx) txtLines(transformIdx) = []; end %% Now we re-write the scene file newSceneFile = txtLines; % Lines before WorldBegin newSceneFile{end+1} = 'WorldBegin'; newSceneFile{end+1} = sprintf('Include "%s_materials.pbrt"',sceneName); newSceneFile{end+1} = sprintf('Include "%s_geometry.pbrt"',sceneName); newSceneFile{end+1} = 'WorldEnd'; fid = fopen(fname,'w'); for ii=1:numel(newSceneFile) fprintf(fid,'%s\n',newSceneFile{ii}); end fclose(fid); end function [txtLines, header] = piReadText(fname) % Open, read, close excluding comment lines fileID = fopen(fname); tmp = textscan(fileID,'%s','Delimiter','\n','CommentStyle',{'#'}); txtLines = tmp{1}; fclose(fileID); % Include comments so we can read only the first line, really fileID = fopen(fname); tmp = textscan(fileID,'%s','Delimiter','\n'); header = tmp{1}; fclose(fileID); end function txtLines = piReadWorldText(thisR,txtLines) % txtLines are the lines before WorldBegin % thisR.world contains the world text % worldBeginIndex = 0; for ii = 1:length(txtLines) currLine = txtLines{ii}; if(piContains(currLine,'WorldBegin')) worldBeginIndex = ii; break; end end % fprintf('Through the loop\n'); if(worldBeginIndex == 0) warning('Cannot find WorldBegin.'); worldBeginIndex = ii; end % Store the text from WorldBegin to the end here thisR.world = txtLines(worldBeginIndex:end); % Store the text lines from before WorldBegin here txtLines = txtLines(1:(worldBeginIndex-1)); end function exporterFlag = piReadExporter(thisR,header) % % Read the first line of the scene file to see if it is a Cinema 4D file % Also, check the materials file for consistency. % Set the recipe accordingly and return a true/false flag % if piContains(header{1}, 'Exported by PBRT exporter for Cinema 4D') % Interprets the information and writes the _geometry.pbrt and % _materials.pbrt files to the rendering folder. exporterFlag = true; thisR.exporter = 'C4D'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to also set the exporterFlag to true if the exporter was Blender elseif isequal(thisR.exporter,'Blender') % Interprets the information and writes the _geometry.pbrt and % _materials.pbrt files to the rendering folder. exporterFlag = true; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % Copies the original _geometry.pbrt and _materials.pbrt to the % rendering folder. exporterFlag = false; thisR.exporter = 'Copy'; end % Check that the materials file export information matches the scene file % export % Read the materials file if it exists. inputFile_materials = thisR.get('materials file'); if exist(inputFile_materials,'file') % Confirm that the material file matches the exporter of the main scene % file. fileID = fopen(inputFile_materials); tmp = textscan(fileID,'%s','Delimiter','\n'); headerCheck_material = tmp{1}; fclose(fileID); if ~piContains(headerCheck_material{1}, 'Exported by piMaterialWrite') if isequal(exporterFlag,true) && isequal(thisR.exporter,'C4D') % Everything is fine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % to deal with the exporter being Blender elseif isequal(exporterFlag,true) && isequal(thisR.exporter,'Blender') % Everything is fine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif isequal(thisR.exporter,'Copy') % Everything is still fine else warning('Puzzled about the materials file.'); end else if isequal(exporterFlag,false) % Everything is fine else warning('Non-standard materials file. Export match not C4D like main file'); end end else % No material field. If exporter is Cinema4D, that's not good. Check % that condition here if isequal(thisR.exporter,'C4D') warning('No materials file for a C4D export'); end end end function [flip,thisR] = piReadLookAt(thisR,txtLines) % Reads multiple blocks to create the lookAt field and flip variable % % The lookAt is built up by reading from, to, up field and transform and % concatTransform. % % Interpreting these variables from the text can be more complicated w.r.t. % formatting. % A flag for flipping from a RHS to a LHS. flip = 0; % Get the block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above [s, lookAtBlock] = piBlockExtract_Blender(txtLines,'blockName','LookAt','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(isempty(lookAtBlock)) % If it is empty, use the default thisR.lookAt = struct('from',[0 0 0],'to',[0 1 0],'up',[0 0 1]); else % We have values values = textscan(lookAtBlock{1}, '%s %f %f %f %f %f %f %f %f %f'); from = [values{2} values{3} values{4}]; to = [values{5} values{6} values{7}]; up = [values{8} values{9} values{10}]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % to convert the right-handed coordinate system of the Blender export % into the left-handed pbrt system if isequal(thisR.exporter,'Blender') from = from([1 3 2]); to = to([1 3 2]); up = up([1 3 2]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end % If there's a transform, we transform the LookAt. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above [~, transformBlock] = piBlockExtract_Blender(txtLines,'blockName','Transform','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(~isempty(transformBlock)) values = textscan(transformBlock{1}, '%s [%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); values = cell2mat(values(2:end)); transform = reshape(values,[4 4]); [from,to,up,flip] = piTransform2LookAt(transform); end % If there's a concat transform, we use it to update the current camera % position. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above [~, concatTBlock] = piBlockExtract_Blender(txtLines,'blockName','ConcatTransform','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(~isempty(concatTBlock)) values = textscan(concatTBlock{1}, '%s [%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); values = cell2mat(values(2:end)); concatTransform = reshape(values,[4 4]); % Apply transform and update lookAt lookAtTransform = piLookat2Transform(from,to,up); [from,to,up,flip] = piTransform2LookAt(lookAtTransform*concatTransform); end % Warn the user if nothing was found if(isempty(transformBlock) && isempty(lookAtBlock)) warning('Cannot find "LookAt" or "Transform" in PBRT file. Returning default.'); end thisR.lookAt = struct('from',from,'to',to,'up',up); end %% Rewrite txtLines in C4D format function txtLines = piWriteC4Dformat_txt(txtLines) % Remove a parameter that is not currently identified by piBlockExtractC4D.m % as well as any empty lines lineidx = cellfun('isempty',txtLines); txtLines(lineidx) = []; lineidx = piContains(txtLines,'bool'); txtLines(lineidx) = []; % Rewrite each block's lines into a single line, including lines that begin % with a double quote, as well as lines that begin with a +/- number (this % is unique to Blender exports) nLines = length(txtLines); ii=1; while ii<nLines % Append to the iith line any subsequent line/s whose first symbol is a % double quote ("), a number, or a negative sign (-) until the block ends for jj=(ii+1):nLines if isequal(txtLines{jj}(1),'"') || ... ~isnan(str2double(txtLines{jj}(1))) || isequal(txtLines{jj}(1),'-') txtLines{ii} = append(txtLines{ii},' ',txtLines{jj}); txtLines{jj} = []; if jj==nLines ii = jj; end else ii = jj; break end end end % Remove empty lines lineidx = cellfun('isempty',txtLines); txtLines(lineidx) = []; end %% Create materials and geometry files in C4D format function piWriteC4Dformat_files(thisR) % Get materials and geometry file names inputFile_materials = thisR.get('materials file'); [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If both files already exist, exit this function; otherwise, proceed if exist(inputFile_materials,'file') && exist(inputFile_geometry,'file') fprintf('Materials and geometry files not created - they already exist.\n'); return end % Since the materials and/or geometry files don't exist, start the process % of creating them allLines = thisR.world; % Find how many objects need to be defined beginLines = find(piContains(allLines,'AttributeBegin')); numbeginLines = numel(beginLines); % Preallocate cell arrays for materials and geometry text materials = cell(size(allLines)); geometry = cell(size(allLines)); % Read out one object at a time for ii = 1:numbeginLines % Start with the 'AttributeBegin' line startidx = beginLines(ii); % Find the index for the last line for this object endidx = find(piContains(allLines(startidx+1:end),'AttributeEnd'),1,'first'); endallidx = endidx + startidx; % Pull all of the lines for this object objectLines = allLines(startidx:endallidx); % For now, not reading out object light sources lightidx = piContains(objectLines,'LightSource'); if any(lightidx) continue end % Preallocate cell array for object's geometry text geometryobj = cell(numel(objectLines)+6,1); % Add an 'AttributeBegin' line geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeBegin'; % Get object name (Blender files are not exported with object names) % If there is a .ply file associated with the object, use that file name plylineidx = piContains(objectLines,'.ply'); if any(plylineidx) plyline = objectLines{plylineidx}; [~,objectname] = fileparts(plyline); % Remove the '_mat0' that the Blender exporter adds automatically objectname = objectname(1:end-5); % If there is no .ply file, give the object a generic name else objectname = (['object' num2str(ii)]); end % Reformat the object name line in the same format as a C4D geometry file % (The 'Vector' parameter will be set later) nameline = append('#ObjectName ',objectname); geometryobj{find(cellfun(@isempty,geometryobj),1)} = nameline; %Add the transform line Tlineidx = piContains(objectLines,'Transform'); if any(Tlineidx) geometryobj{find(cellfun(@isempty,geometryobj),1)} = objectLines{Tlineidx}; end % Add an 'AttributeBegin' line geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeBegin'; % Get material name and parameters Mlineidx = piContains(objectLines,'Material'); if any(Mlineidx) Mline = objectLines{Mlineidx}; % Get material name only Mname = textscan(Mline,'%q'); Mname = Mname{1}; Mname = Mname{2}; % Start this part of the material line with the material name Mline = append('"',Mname,'"'); % Append all material parameters to the material line started above nLines = endidx-1; for jj=find(Mlineidx)+1:nLines thisLine = objectLines{jj}; % If the next line contains a double quote (") it gets appended if isequal(thisLine(1),'"') % The color parameters get special treatment because of how % they are exported from Blender if piContains(thisLine,'color') % The Blender exporter puts a space after the '[' % character for color parameters, which has to be % removed to be compatible with piParseRGB.m later thisLine = replace(thisLine,'[ ', '['); % Rename color parameters because the Blender exporter % uses the 'color' synonym for 'rgb' and not all % 'color' values are read out in piBlockExtractMaterial.m thisLine = replace(thisLine,'color','rgb'); end % Append the line Mline = append(Mline,' ',strtrim(thisLine)); % If the next line does not contain a double quote, break else break end end else % If the object was exported from Blender without a pbrt material % assign a default material here (gray matte) Mline = '"matte" "float sigma" [0] "rgb Kd" [.9 .9 .9]'; end % Assign material name (Blender files are not exported with % material names) based on the object name assigned above materialname = append(objectname,'_material'); % Reformat the material line for this object's materials text Materialline = append('MakeNamedMaterial "',materialname,'" "string type" ',Mline); % Get texture parameters Tlineidx = piContains(objectLines,'Texture'); if any(Tlineidx) Textureline = objectLines{Tlineidx}; % Replace "color" with "spectrum" to match C4D format Textureline = strrep(Textureline,"color","spectrum"); % The pbrt file exported from Blender refers to texture files in a % 'textures' folder, but any texture files were moved directly into % the scene folder for use in iset3d, so we need to remove any % references to a 'textures' folder Textureline = strrep(Textureline,"[""textures/",""""); Textureline = strrep(Textureline,".exr""]",".exr"""); % Add the texture line to this object's materials text materials{find(cellfun(@isempty,materials),1)} = Textureline; end % Add the material line to this object's materials text (it is added % after this object's texture line, if this object has a texture) materials{find(cellfun(@isempty,materials),1)} = Materialline; % Create a material line for this object's geometry text GMaterialline = append('NamedMaterial "',materialname,'"'); geometryobj{find(cellfun(@isempty,geometryobj),1)} = GMaterialline; % Get shape parameters Slineidx = piContains(objectLines,'Shape'); if any(Slineidx) % If the shape parameters are described by a .ply file, don't % reformat the shape line (the .ply file will be read out later) if piContains(objectLines{Slineidx},'.ply') Sline = objectLines{Slineidx}; % But if not, reformat the shape parameters into a single line else objectLines(1:find(Slineidx)-1) = []; objectLines(end) = []; Sline = cellfun(@string,objectLines); Sline = join(Sline); % Remove an extra space after the '[' character Sline = replace(Sline,'[ ', '['); Sline = convertStringsToChars(Sline); end geometryobj{find(cellfun(@isempty,geometryobj),1)} = Sline; end % Complete this object description geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeEnd'; geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeEnd'; % Remove any empty cells lineidx = cellfun('isempty',geometryobj); geometryobj(lineidx) = []; % Add to geometry text Gstartidx = find(cellfun(@isempty,geometry),1); Gendidx = Gstartidx + numel(geometryobj) - 1; try geometry(Gstartidx:Gendidx) = geometryobj; catch geometry = [geometry; geometryobj]; end end % Complete materials text and geometry text lineidx = cellfun('isempty',geometry); geometry(lineidx) = []; lineidx = cellfun('isempty',materials); materials(lineidx) = []; % If the materials file doesn't exist, create it in the same folder as the % pbrt scene file if ~exist(inputFile_materials,'file') % Open up a new materials file fileID = fopen(inputFile_materials,'w'); % Write in a comment describing when this file was created fprintf(fileID,'# PBRT file created in C4D exporter format on %i/%i/%i %i:%i:%0.2f \n',clock); % Blank line fprintf(fileID,'\n'); % Write in materials text materials = materials'; fprintf(fileID,'%s\n',materials{:}); % Close the materials file fclose(fileID); fprintf('A new materials file was created in %s\n', inFilepath); end % If the geometry file doesn't exist, create it in the same folder as the % pbrt scene file if ~exist(inputFile_geometry,'file') % Open up a new geometry file fileID = fopen(inputFile_geometry,'w'); % Write in a comment describing when this file was created fprintf(fileID,'# PBRT file created in C4D exporter format on %i/%i/%i %i:%i:%0.2f \n',clock); % Blank line fprintf(fileID,'\n'); % Write in geometry text geometry = geometry'; fprintf(fileID,'%s\n',geometry{:}); % Close the materials file fclose(fileID); fprintf('A new geometry file was created in %s\n', inFilepath); end end function thisR = piWriteC4Dformat_world(thisR) world{1,1} = 'WorldBegin'; % Include the materials file [~,scene_fname] = fileparts(thisR.inputFile); world{2,1} = append('Include "',scene_fname,'_materials.pbrt"'); % Include the geometry file world{3,1} = append('Include "',scene_fname,'_geometry.pbrt"'); world{4,1} = 'WorldEnd'; % Update thisR.world thisR.world = world; end function piWriteC4Dformat_ply(thisR) % Get geometry file name [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If the geometry file doesn't exist, give warning and exit this function if ~exist(inputFile_geometry,'file') warning('Geometry file does not exist.'); return end % Get text from geometry file fileID = fopen(inputFile_geometry,'r'); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); % Check for .ply files and exit this function if they do not exist sLines = find(piContains(txtLines,'.ply')); if ~any(sLines) return end % Replace text lines referencing .ply files with their geometry information numsLines = numel(sLines); for ii = 1:numsLines thisLine = txtLines{sLines(ii)}; % Get the name of the .ply file plyLine = textscan(thisLine,'%q'); plyLine = plyLine{1}; plylineidx = piContains(plyLine,'.ply'); plyLine = plyLine{plylineidx}; [~,objectname] = fileparts(plyLine); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: new function below % The function below is a modified version of pcread.m % that reads out the per-vertex texture coordinates (in addition to the % per-vertex locations and normals read out by pcread.m)from the .ply file [ptCloud,plyTexture] = pcread_Blender([objectname '.ply']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set up .ply file output in pbrt format plyLocation = ptCloud.Location; plyNormal = ptCloud.Normal; %pcshow(ptCloud); %uncomment this line to plot points % NOTE: for now, assumes all exported objects are triangle mesh Shape = 'trianglemesh'; % Align vertices with their corresponding normals and texture coordinates plyAll = [plyLocation plyNormal plyTexture]; % Get the unique vertices/normals/texture coordinates uvertices = unique(plyAll,'rows'); % Separate out the three parameters pointP = uvertices(:,1:size(plyLocation,2)); normalN = uvertices(:,size(plyLocation,2)+1:size(plyLocation,2)+size(plyNormal,2)); floatuv = uvertices(:,size(plyLocation,2)+size(plyNormal,2)+1:end); % Calculate the integer indices [~,integerindices] = ismember(plyAll,uvertices,'rows'); % Integers currently start at 1 but need to start at 0 integerindices = integerindices - 1; % Reshape into pbrt format integerindices = integerindices'; pointP = reshape(pointP.',1,[]); normalN = reshape(normalN.',1,[]); floatuv = reshape(floatuv.',1,[]); % Convert to strings integerindices = mat2str(integerindices); pointP = mat2str(pointP); normalN = mat2str(normalN); floatuv = mat2str(floatuv); % Rewrite 'Shape' line in pbrt format newLine = append('Shape "',Shape,'" "integer indices" ',integerindices, ... ' "point P" ',pointP); if ~isempty(plyNormal) newLine = append(newLine,' "normal N" ',normalN); end if ~isempty(plyTexture) newLine = append(newLine,' "float uv" ',floatuv); end % Replace the old 'Shape' line with the rewritten line txtLines{sLines(ii)} = newLine; end % Update geometry file text fileID = fopen(inputFile_geometry,'w'); txtLines = txtLines'; fprintf(fileID,'%s\n',txtLines{:}); fclose(fileID); fprintf('One or more .ply functions were parsed in the geometry file.\n'); end %% Convert a right-handed coordinate system to the left-handed pbrt system % (this function should always be called once for Blender exports, because % Blender uses a right-handed coordinate system) function piWriteC4Dformat_handedness(thisR) % Get geometry file name [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If the geometry file doesn't exist, give warning and exit this function if ~exist(inputFile_geometry,'file') warning('Geometry file does not exist.'); return end % Get text from geometry file fileID = fopen(inputFile_geometry,'r'); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); % If this conversion to a left-handed coordinate system has already % occurred, exit this function (must only do this conversion once) checkflg = piContains(txtLines,'Converted to a left-handed coordinate system'); if any(checkflg) return end % Switch y and z coordinates per vertex for vertex positions ('point P') % and per-vertex normals ('normal N') in the 'Shape' line for each object pLines = find(piContains(txtLines,'"point P"')); numsLines = numel(pLines); for ii = 1:numsLines Pline = txtLines{pLines(ii)}; % Get 'point P' vector pidx = strfind(Pline,'"point P"'); pPline = Pline(pidx:end); openidx = strfind(pPline,'['); closeidx = strfind(pPline,']'); pointP = pPline(openidx(1)+1:closeidx(1)-1); pointP = str2num(pointP); % Reshape points into three columns (three axes) numvertices = numel(pointP)/3; pointP = reshape(pointP,[3,numvertices]); pointP = pointP'; % Switch y and z coordinates pointP = pointP(:,[1 3 2]); % Reshape points into vector pointP = reshape(pointP.',1,[]); % Convert to string pointP = mat2str(pointP); % Replace converted 'point P' in the 'Shape' line Pline = append(Pline(1:pidx+9),pointP,Pline(pidx+closeidx(1):end)); % If the 'normal N' vector exists, switch y and z coordinates as above nidx = strfind(Pline,'"normal N"'); if ~isempty(nidx) nPline = Pline(nidx:end); openidx = strfind(nPline,'['); closeidx = strfind(nPline,']'); normalN = nPline(openidx(1)+1:closeidx(1)-1); normalN = str2num(normalN); normalN = reshape(normalN,[3,numvertices]); normalN = normalN'; normalN = normalN(:,[1 3 2]); normalN = reshape(normalN.',1,[]); normalN = mat2str(normalN); Pline = append(Pline(1:nidx+10),normalN,Pline(nidx+closeidx(1):end)); end % Replace old 'Shape' text line with new text line txtLines{pLines(ii)} = Pline; end % Convert 'Transform' matrices into left-handed matrices for each object tLines = find(piContains(txtLines,'Transform')); numsLines = numel(tLines); for ii = 1:numsLines Tline = txtLines{tLines(ii)}; % Get 'Transform' vector openidx = strfind(Tline,'['); closeidx = strfind(Tline,']'); Transform = Tline(openidx(1)+1:closeidx-1); Transform = str2num(Transform); % Convert the right-handed matrix into a left-handed matrix Transform = reshape(Transform,[4,4]); Transform(:,[2 3]) = Transform(:,[3 2]); Transform([2 3],:) = Transform([3 2],:); % Reshape matrix into vector Transform = reshape(Transform,[1 16]); % Convert to string Transform = mat2str(Transform); % Replace converted 'Transform' vector Tline = append('Transform ',Transform); % Replace old 'Transform' text line with new text line txtLines{tLines(ii)} = Tline; end % Update geometry file text fileID = fopen(inputFile_geometry,'w'); fprintf(fileID,'%s\n',txtLines{1}); % Write in a comment describing when the handedness was converted % (this helper function will watch out for this comment in the future % because you must only do this conversion once) fprintf(fileID,'# Converted to a left-handed coordinate system on %i/%i/%i %i:%i:%0.2f \n',clock); txtLines = txtLines(2:end); txtLines = txtLines'; fprintf(fileID,'%s\n',txtLines{:}); fclose(fileID); fprintf('Coordinate system was converted to left-handed pbrt system in the geometry file.\n'); end %% Calculate vector information function piWriteC4Dformat_vector(thisR) % Get geometry file name [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If the geometry file doesn't exist, give warning and exit this function if ~exist(inputFile_geometry,'file') warning('Geometry file does not exist.'); return end % Get text from geometry file fileID = fopen(inputFile_geometry,'r'); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); % Check for 'Vector' parameter and exit this function if it already exists vLines = find(piContains(txtLines,':Vector(')); if any(vLines) return end % Add 'Vector' information to object name text lines oLines = find(piContains(txtLines,'#ObjectName')); numsLines = numel(oLines); for ii = 1:numsLines thisLine = txtLines{oLines(ii)}; % Find shape parameters for this object restoftxt = txtLines(oLines(ii)+1:numel(txtLines)); endLine = find(piContains(restoftxt,'AttributeEnd'),1,'first'); thistxt = restoftxt(1:endLine); lineidx = piContains(thistxt,'point P'); % If shape parameters do not exist for this object, give default vector if ~any(lineidx) thisLine = append(thisLine,':Vector(0, 0, 0)'); else % Get 'point P' vector Pline = thistxt{lineidx}; pidx = strfind(Pline,'"point P"'); Pline = Pline(pidx:end); openidx = strfind(Pline,'['); closeidx = strfind(Pline,']'); pointP = Pline(openidx(1)+1:closeidx(1)-1); pointP = str2num(pointP); % Reshape points into three columns (three axes) numvertices = numel(pointP)/3; pointP = reshape(pointP,[3,numvertices]); pointP = pointP'; % Calculate vector parameter minpointP = min(pointP); maxpointP = max(pointP); diffpointP = abs(minpointP)+abs(maxpointP); v = diffpointP/2; % Add vector to object name line in pbrt format, which is % NAME:Vector(X, Z, Y) thisLine = append(thisLine,':Vector(',num2str(v(1)),', ',num2str(v(3)),', ',num2str(v(2)),')'); end % Replace old object text line with new text line txtLines{oLines(ii)} = thisLine; end % Update geometry file text fileID = fopen(inputFile_geometry,'w'); txtLines = txtLines'; fprintf(fileID,'%s\n',txtLines{:}); fclose(fileID); fprintf('Vector information was updated in the geometry file.\n'); end
github
ISET/iset3d-v3-master
pcread_Blender.m
.m
iset3d-v3-master/utilities/blender/pcread_Blender.m
6,671
utf_8
2549d72c99f96a0d4cf115497feac9a9
function [ptCloud,texture] = pcread_Blender(filename) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: this is a modification of pcread.m % that also reads out per-vertex texture coordinates %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %pcread Read a 3-D point cloud from PLY or PCD file. % ptCloud = PCREAD(filename) reads a point cloud from the PCD or PLY file % specified by the string filename. If the file is not in the current % directory, or in a directory on the MATLAB path, specify the full % pathname. The return value ptCloud is a pointCloud object. % % Notes % ----- % - PLY or PCD files can contain numerous data entries. pcread loads only % the following properties: point locations, colors, normals and % intensities. % % Example : Read a point cloud from a PLY file % -------------------------------------------- % ptCloud = pcread('teapot.ply'); % pcshow(ptCloud) % % See also pointCloud, pcwrite, pcshow % Copyright 2015-2017 The MathWorks, Inc. % Validate the input if nargin > 0 filename = convertStringsToChars(filename); end if isstring(filename) filename = char(filename); end if ~ischar(filename) error(message('vision:pointcloud:badFileName')); end % Validate the file type idx = find(filename == '.'); if (~isempty(idx)) extension = lower(filename(idx(end)+1:end)); else extension = ''; end % Validate the file extension. if(~(strcmpi(extension,'pcd') || strcmpi(extension,'ply'))) error(message('vision:pointcloud:unsupportedFileExtension')); end % Verify that the file exists. fid = fopen(filename, 'r'); if (fid == -1) if ~isempty(dir(filename)) error(message('MATLAB:imagesci:imread:fileReadPermission', filename)); else error(message('MATLAB:imagesci:imread:fileDoesNotExist', filename)); end else % File exists. Get full filename. filename = fopen(fid); fclose(fid); end if( strcmpi(extension,'ply') ) % Read properties of 'Vertex' elementName = 'vertex'; requiredProperties = {'x','y','z'}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: edited below to read out float u and float v values % Alternative names are specified in a cell array within the main cell array. optionalProperties = {{'r','red'},{'g','green'},{'b','blue'},'nx','ny','nz','intensity','u','v'}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% properties = visionPlyRead(filename,elementName,requiredProperties,optionalProperties); % Get location property x = properties{1}; y = properties{2}; z = properties{3}; if isa(x,'double') || isa(y,'double') || isa(z,'double') loc = [double(x), double(y), double(z)]; else loc = [single(x), single(y), single(z)]; end % Get color property r = properties{4}; g = properties{5}; b = properties{6}; color = [im2uint8(r), im2uint8(g), im2uint8(b)]; % Get normal property nx = properties{7}; ny = properties{8}; nz = properties{9}; if isa(nx,'double') || isa(ny,'double') || isa(nz,'double') normal = [double(nx), double(ny), double(nz)]; else normal = [single(nx), single(ny), single(nz)]; end % Get intensity property intensity = properties{10}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % Get texture coordinate property u = properties{11}; v = properties{12}; if isa(u,'double') || isa(v,'double') texture = [double(u), double(v)]; else texture = [single(u), single(v)]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif( strcmpi(extension,'pcd') ) requiredProperties = {'x','y','z'}; optionalProperties = {'r','g','b','normal_x','normal_y','normal_z','intensity'}; properties = visionPcdRead(filename,requiredProperties,optionalProperties); % Get location property x = properties{1}; y = properties{2}; z = properties{3}; % Get color property r = properties{4}; g = properties{5}; b = properties{6}; % Get normal property nx = properties{7}; ny = properties{8}; nz = properties{9}; % Get intensity property intensity = properties{10}; [~,cols] = size(x); % Check if it is organized or unorganized point cloud if cols == 1 dim = 2; else dim = 3; end if isempty(x) || isempty(y) || isempty(z) loc = []; else if dim > 2 x = reshapeValuesRowise(x); y = reshapeValuesRowise(y); z = reshapeValuesRowise(z); end if isa(x,'double') || isa(y,'double') || isa(z,'double') loc = cat(dim, double(x), double(y), double(z)); else loc = cat(dim,single(x), single(y), single(z)); end end if isempty(r) || isempty(g) || isempty(b) color = []; else if dim > 2 r = reshapeValuesRowise(r); g = reshapeValuesRowise(g); b = reshapeValuesRowise(b); end color = cat(dim,im2uint8(r), im2uint8(g), im2uint8(b)); end if isempty(nx) || isempty(ny) || isempty(nz) normal = []; else if dim > 2 nx = reshapeValuesRowise(nx); ny = reshapeValuesRowise(ny); nz = reshapeValuesRowise(nz); end if isa(nx,'double') || isa(ny,'double') || isa(nz,'double') normal = cat(dim, double(nx), double(ny), double(nz)); else normal = cat(dim,single(nx), single(ny), single(nz)); end end if ~isempty(intensity) intensity = reshapeValuesRowise(intensity); end end ptCloud = pointCloud(loc, 'Color', color, 'Normal', normal, ... 'Intensity', intensity); end function out = reshapeValuesRowise(in) [numRow,numCol] = size(in); temp = reshape(in,[numCol,numRow]); out = temp'; end
github
ISET/iset3d-v3-master
piGeometryRead_Blender.m
.m
iset3d-v3-master/utilities/blender/piGeometryRead_Blender.m
14,936
utf_8
2ab79496236215ea2b794da05222fb1b
function renderRecipe = piGeometryRead_Blender(renderRecipe) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % Adapted from piGeometryRead.m % to extract scale and rotation information separately per object %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Read a C4d geometry file and extract object information into a recipe % % Syntax: % renderRecipe = piGeometryRead(renderRecipe) % % Input % renderRecipe: an iset3d recipe object describing the rendering % parameters. This object includes the inputFile and the % outputFile, which are used to find the directories containing % all of the pbrt scene data. % % Return % renderRecipe - Updated by the processing in this function % % Zhenyi, 2018 % Henryk Blasinski 2020 % % Description % This includes a bunch of sub-functions and a logic that needs further % description. % % See also % piGeometryWrite %% p = inputParser; p.addRequired('renderRecipe',@(x)isequal(class(x),'recipe')); %% Check version number if(renderRecipe.version ~= 3) error('Only PBRT version 3 Cinema 4D exporter is supported.'); end %% give a geometry.pbrt % Best practice is to initalize the ouputFile. Sometimes people % don't. So we do this as the default behavior. [inFilepath, scene_fname] = fileparts(renderRecipe.inputFile); inputFile = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % Save the JSON file at AssetInfo % outputFile = renderRecipe.outputFile; outFilepath = fileparts(renderRecipe.outputFile); AssetInfo = fullfile(outFilepath,sprintf('%s.json',scene_fname)); %% Open the geometry file % Read all the text in the file. Read this way the text indents are % ignored. fileID = fopen(inputFile); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); %% Check whether the geometry have already been converted from C4D % If it was converted into ISET3d format, we don't need to do much work. if piContains(txtLines(1),'# PBRT geometry file converted from C4D exporter output') convertedflag = true; else convertedflag = false; end if ~convertedflag % It was not converted, so we go to work. renderRecipe.assets = parseGeometryText(txtLines,''); % jsonwrite(AssetInfo,renderRecipe); % fprintf('piGeometryRead done.\nSaving render recipe as a JSON file %s.\n',AssetInfo); else % The converted flag is true, so AssetInfo is already stored in a % JSON file with the recipe information. We just copy it isnto the % recipe. renderRecipe_tmp = jsonread(AssetInfo); % There may be a utility that accomplishes this. We should find % it and use it here. fds = fieldnames(renderRecipe_tmp); renderRecipe = recipe; % Assign the each field in the struct to a recipe class for dd = 1:length(fds) renderRecipe.(fds{dd})= renderRecipe_tmp.(fds{dd}); end end end %% function [res, children, parsedUntil] = parseGeometryText(txt, name) % % Inputs: % % txt - remaining text to parse % name - current object name % % Outputs: % res - struct of results % children - Attributes under the current object % parsedUntil - line number of the parsing end % % Description: % % The geometry text comes from C4D export. We parse the lines of text in % 'txt' cell array and recrursively create a tree structure of geometric objects. res = []; groupobjs = []; children = []; i = 1; while i <= length(txt) currentLine = txt{i}; % Return if we've reached the end of current attribute if strcmp(currentLine,'AttributeEnd') % Assemble all the read attributes into either a groub object, or a % geometry object. Only group objects can have subnodes (not % children). This can be confusing but is somewhat similar to % previous representation. if exist('rot','var') || exist('position','var') resCurrent = createGroupObject(); % If present populate fields. if exist('name','var'), resCurrent.name = name; end if exist('sz','var'), resCurrent.size = sz; end if exist('rot','var'), resCurrent.rotate = rot; end if exist('position','var'), resCurrent.position = position; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % to populate the 'scale' field if exist('scale','var'), resCurrent.scale = scale; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% resCurrent.groupobjs = groupobjs; resCurrent.children = children; children = []; res = cat(1,res,resCurrent); elseif exist('shape','var') || exist('mediumInterface','var') || exist('mat','var') || exist('areaLight','var') || exist('lght','var') resChildren = createGeometryObject(); if exist('shape','var'), resChildren.shape = shape; end if exist('medium','var'), resChildren.medium = medium; end if exist('mat','var'), resChildren.material = mat; end if exist('lght','var'), resChildren.light = lght; end if exist('areaLight','var'), resChildren.areaLight = areaLight; end if exist('name','var'), resChildren.name = name; end children = cat(1,children, resChildren); elseif exist('name','var') resCurrent = createGroupObject(); if exist('name','var'), resCurrent.name = name; end resCurrent.groupobjs = groupobjs; resCurrent.children = children; children = []; res = cat(1,res,resCurrent); end parsedUntil = i; return; elseif strcmp(currentLine,'AttributeBegin') % This is an Attribute inside an Attribute [subnodes, subchildren, retLine] = parseGeometryText(txt(i+1:end), name); groupobjs = cat(1, groupobjs, subnodes); % Give an index to the subchildren to make it different from its % parents and brothers (we are not sure if it works for more than % two levels). We name the subchildren based on the line number and % how many subchildren there are already. if ~isempty(subchildren) subchildren.name = sprintf('%d_%d_%s', i, numel(children)+1, subchildren.name); end children = cat(1, children, subchildren); i = i + retLine; elseif piContains(currentLine,'#ObjectName') [name, sz] = parseObjectName(currentLine); elseif piContains(currentLine,'ConcatTransform') [rot, position] = parseConcatTransform(currentLine); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % to extract scale and rotation information separately per object % (the Blender exporter uses 'Transform' instead of 'ConcatTransform' % per object, which is why the statement below looks for the 'Transform' % line, but the new 'parseTransform' helper function below could be % used for 'ConcatTransform' lines from the C4D exporter as well) elseif piContains(currentLine,'Transform') [position, rot, scale] = parseTransform(currentLine); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif piContains(currentLine,'MediumInterface') % MediumInterface could be water or other scattering media. medium = currentLine; elseif piContains(currentLine,'NamedMaterial') mat = currentLine; elseif piContains(currentLine,'AreaLightSource') areaLight = currentLine; elseif piContains(currentLine,'LightSource') ||... piContains(currentLine, 'Rotate') ||... piContains(currentLine, 'Scale') if ~exist('lght','var') lght{1} = currentLine; else lght{end+1} = currentLine; end elseif piContains(currentLine,'Shape') shape = currentLine; else % warning('Current line skipped: %s', currentLine); end i = i+1; end res = createGroupObject(); res.name = 'root'; res.groupobjs = groupobjs; res.children = children; parsedUntil = i; end %% function [name, sz] = parseObjectName(txt) % Parse an ObjectName string in 'txt' to extract the object name and size. % % Cinema4D produces a line with #ObjectName in it. The format of the % #ObjectName line appears to be something like this: % % #ObjectName Plane:Vector(5000, 0, 5000) % % The only cases we have seen are NAME:Vector(X,Z,Y). Someone seems to % know the meaning of these three values which are read into 'res' below. % The length is 2*X, width is 2*Y and height is 2*Z. % % Perhaps these numbers should always be treated as in meters or maybe % centimeters? We need to figure this out. For the slantedBar scene we % had the example above, and we think the scene might be about 100 meters, % so this would make sense. % % We do not have a routine to fill in these values for non-Cinema4D % objects. % Find the location of #ObjectName in the string pattern = '#ObjectName'; loc = strfind(txt,pattern); % Look for a colon pos = strfind(txt,':'); name = txt(loc(1)+length(pattern) + 1:max(pos(1)-1, 1)); posA = strfind(txt,'('); posB = strfind(txt,')'); res = sscanf(txt(posA(1)+1:posB(1)-1),'%f, %f, %f'); % Position minimima and maxima for lower left (X,Y), upper right. sz.pmin = [-res(1) -res(3)]; sz.pmax = [res(1) res(3)]; % We are not really sure what these coordinates represent with respect to % the scene or the camera direction. For one case we analyzed (a plane) % this is what the values meant. sz.l = 2*res(1); % length (X) sz.w = 2*res(2); % depth (Z) sz.h = 2*res(3); % height (Y) end %% function [rotation, translation] = parseConcatTransform(txt) % Given a string 'txt' extract the information about transform. posA = strfind(txt,'['); posB = strfind(txt,']'); tmp = sscanf(txt(posA(1):posB(1)), '[%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); tform = reshape(tmp,[4,4]); dcm = [tform(1:3); tform(5:7); tform(9:11)]; [rotz,roty,rotx]= piDCM2angle(dcm); if ~isreal(rotz) || ~isreal(roty) || ~isreal(rotx) warning('piDCM2angle returned complex angles. JSONWRITE will fail.'); % dcm % txt(posA(1):posB(1)) end %{ % Forcing to real is not a good idea. rotx = real(rotx*180/pi); roty = real(roty*180/pi); rotz = real(rotz*180/pi); %} % { rotx = rotx*180/pi; roty = roty*180/pi; rotz = rotz*180/pi; %} % Comment needed rotation = [rotz, roty, rotx; fliplr(eye(3))]; translation = reshape(tform(13:15),[3,1]); end %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: helper function added % to extract translation, rotation, and scale parameters from the % transformation matrix % (this helper function is currently only called for Blender exports % because the Blender export uses 'Transform' understead of % 'ConcatTransform', but this helper function could be called for % 'ConcatTransform' lines from the C4D exporter as well) function [translation, rotation, scale] = parseTransform(txt) % Get transformation matrix from the input (the 'Transform' line) openidx = strfind(txt,'['); closeidx = strfind(txt,']'); tmp = sscanf(txt(openidx(1):closeidx(1)), '[%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); T = reshape(tmp,[4,4]); % Extract translation from the transformation matrix translation = reshape(T(13:15),[3,1]); % Compute new transformation matrix without translation T = T(1:3,1:3); % Extract the pure rotation component of the new transformation matrix % using polar decomposition (the pbrt method) R = T; ii=0; normii=1; while ii<100 && normii>.0001 % Successively average the matrix with its inverse transpose until % convergence Rnext = 0.5 * (R + inv(R.')); % Compute norm of difference between R and Rnext normii = norm(abs(R - Rnext)); % Reset for next iteration R = Rnext; ii = ii+1; end % Calculate rotation angles about the X, Y, and Z axes from the transform matrix % (citation: Slabaugh, Gregory G., "Computing Euler angles from a rotation matrix", % https://www.gregslabaugh.net/publications/euler.pdf, December 5, 2020) if abs(round(R(3,1),2))~=1 roty = -asin(R(3,1)); cosy = cos(roty); rotx = atan2(R(3,2)/cosy, R(3,3)/cosy); rotz = atan2(R(2,1)/cosy, R(1,1)/cosy); else rotz = 0; if R(3,1)==-1 roty = pi/2; rotx = rotz + atan2(R(1,2),R(1,3)); else roty = -pi/2; rotx = -rotz + atan2(-R(1,2),-R(1,3)); end end % Convert rotation angles from radians to degrees rotx = rotx*180/pi; roty = roty*180/pi; rotz = rotz*180/pi; % Set up rotation matrix in pbrt format rotation = [rotz, roty, rotx; fliplr(eye(3))]; % Compute scale matrix using rotation matrix and transformation matrix S = R\T; % Set up scale parameters in pbrt format scale = [S(1,1) S(2,2), S(3,3)]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% function obj = createGroupObject() % Initialize a structure representing a group object. % % What makes something a group object rather than a child? % What if we want to read the nodes and edges of an object, can we do it? obj.name = []; % String obj.size.l = 0; % Length obj.size.w = 0; % Width obj.size.h = 0; % Height obj.size.pmin = [0 0]; % No idea obj.size.pmax = [0 0]; % No idea obj.scale = [1 1 1]; obj.position = [0 0 0]; % Maybe the middle of the object? obj.rotate = [0 0 0; 0 0 1; 0 1 0; 1 0 0]; obj.children = []; obj.groupobjs = []; end %% function obj = createGeometryObject() % This function creates a geometry object and initializes all fields to % empty values. obj.name = []; obj.index = []; obj.mediumInterface = []; obj.material = []; obj.light = []; obj.areaLight = []; obj.shape = []; obj.output = []; end
github
ISET/iset3d-v3-master
piRead_Blender.m
.m
iset3d-v3-master/utilities/blender/piRead_Blender.m
49,638
utf_8
2fd2d5031e4bfa67c3fd5e84e6f679d8
function thisR = piRead_Blender(fname,varargin) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % Adapted from piRead.m to also handle a scene file exported from Blender %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Read and parse a PBRT scene file, returning a rendering recipe % % Syntax % thisR = piRead(fname, varargin) % % Description % piREAD parses a pbrt scene file and returns the full set of rendering % information in the slots of the "recipe" object. The recipe object % contains all the information used by PBRT to render the scene. % % We extract blocks with these names from the text prior to WorldBegin % % Camera, Sampler, Film, PixelFilter, SurfaceIntegrator (V2, or % Integrator in V3), Renderer, LookAt, Transform, ConcatTransform, % Scale % % After creating the recipe from piRead, we modify the recipe % programmatically. The modified recipe is then used to write out the % PBRT file (piWrite). These PBRT files are rendered using piRender, % which executes the PBRT docker image and return an ISETCam scene or oi % format). % % We also have routines to execute these functions at scale in Google % Cloud (see isetcloud). % % Required inputs % fname - a full path to a pbrt scene file % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: header text below requires editing % because 'readmaterials' will be true for Blender exports, as well % Optional parameter/values % 'read materials' - When PBRT scene file is exported by cinema4d, % the exporterflag is set and we read the materials file. If % you do not want to read that file, set this to false. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % so that the user can input the exporter type 'Blender' when calling this % function % Optional parameter/values % 'exporter' - allows the user to specify that the scene was exported % from Blender %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Return % recipe - A recipe object with the parameters needed to write a new pbrt % scene file % % Assumptions: piRead assumes that % % * There is a block of text before WorldBegin and no more text after % * Comments (indicated by '#' in the first character) and blank lines % are ignored. % * When a block is encountered, the text lines that follow beginning % with a '"' are included in the block. % % piRead will not work with PBRT files that do not meet these criteria. % % Text starting at WorldBegin to the end of the file (not just WorldEnd) % is stored in recipe.world. % % TL, ZLy, BW Scienstanford 2017-2020 % % See also % piWrite, piRender, piBlockExtract % Examples: %{ thisR = piRecipeDefault('scene name','MacBethChecker'); % thisR = piRecipeDefault('scene name','SimpleScene'); % thisR = piRecipeDefault('scene name','teapot'); piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); %} %% Parse the inputs varargin =ieParamFormat(varargin); p = inputParser; p.addRequired('fname',@(x)(exist(fname,'file'))); p.addParameter('readmaterials', true,@islogical); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % so that the user can input exporter type 'Blender' p.addParameter('exporter','',@ischar); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% p.parse(fname,varargin{:}); thisR = recipe; thisR.inputFile = fname; readmaterials = p.Results.readmaterials; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % to set the exporter type to 'Blender' if user sets this input exporter = p.Results.exporter; if isequal(exporter,'Blender') thisR.exporter = 'Blender'; else warning('exporter is not Blender (%s); you are using piRead_Blender',exporter); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % summary = sprintf('Read summary %s\n',fname); %% Set the default output directory [~,scene_fname] = fileparts(fname); outFilepath = fullfile(piRootPath,'local',scene_fname); outputFile = fullfile(outFilepath,[scene_fname,'.pbrt']); thisR.set('outputFile',outputFile); %% Read the text and header from the PBRT file [txtLines, header] = piReadText(fname); %% Split text lines into pre-WorldBegin and WorldBegin sections txtLines = piReadWorldText(thisR,txtLines); %% Set flag indicating whether this is exported Cinema 4D file % exporterFlag = piReadExporter(thisR,header); piReadExporter(thisR,header); %% If this is an exported Blender file: % 1) rewrite 'txtLines' in C4D format % 2) create materials and geometry files in C4D format % 3) rewrite 'thisR.world' in C4D format % 4) extract geometry information from .ply functions in the geometry file % 5) convert the coordinate system from right-handed to left-handed % 6) calculate 'Vector' information in the geometry file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: section added % to rewrite a pbrt file exported from Blender into the format of pbrt % files exported from C4D if isequal(thisR.exporter,'Blender') % NOTE: this is a new helper function % that rewrites 'txtLines' in C4D format txtLines = piWriteC4Dformat_txt(txtLines); % NOTE: this is a new helper function % that creates materials and geometry files in C4D format % (the Blender exporter does not create materials and geometry files) piWriteC4Dformat_files(thisR); % NOTE: this is a new helper function % that rewrites 'thisR.world' in C4D format thisR = piWriteC4Dformat_world(thisR); % NOTE: this is a new helper function % that extracts geometry information from .ply functions in the % geometry file % NOTE: this is currently called for Blender exports only % but should be useful for converting any .ply functions piWriteC4Dformat_ply(thisR); % NOTE: this is a new helper function % that converts a right-handed coordinate system into the left-handed % pbrt system % NOTE: this function should always be called once for Blender exports % because Blender uses a right-handed coordinate system piWriteC4Dformat_handedness(thisR); % NOTE: this is a new helper function % that calculate 'Vector' information in the geometry file % NOTE: this function should always be called for Blender exports % because the Blender exporter does not include vector information % automatically, but should be useful for any pbrt files without Vector % information included piWriteC4Dformat_vector(thisR); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Extract camera block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to call an edited version of piBlockExtract.m % that handles the exporter being Blender thisR.camera = piBlockExtract_Blender(txtLines,'blockName','Camera','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Extract sampler block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above thisR.sampler = piBlockExtract_Blender(txtLines,'blockName','Sampler','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Extract film block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above thisR.film = piBlockExtract_Blender(txtLines,'blockName','Film','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Patch up the filmStruct to match the recipe requirements if(isfield(thisR.film,'filename')) % Remove the filename since it inteferes with the outfile name. thisR.film = rmfield(thisR.film,'filename'); end % Some PBRT files do not specify the film diagonal size. We set it to % 1mm here. try thisR.get('film diagonal'); catch disp('Setting film diagonal size to 1 mm'); thisR.set('film diagonal',1); end %% Extract surface pixel filter block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above thisR.filter = piBlockExtract_Blender(txtLines,'blockName','PixelFilter','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Extract (surface) integrator block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above thisR.integrator = piBlockExtract_Blender(txtLines,'blockName','Integrator','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Set thisR.lookAt and determine if we need to flip the image flip = piReadLookAt(thisR,txtLines); % Sometimes the axis flip is "hidden" in the concatTransform matrix. In % this case, the flip flag will be true. When the flip flag is true, we % always output Scale -1 1 1. if(flip) thisR.scale = [-1 1 1]; end %% Read the light sources and delete them in world %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below not used % For now, lights in pbrt files exported from Blender are not read out % (the Blender exporter does not automatically include a light in world; % instead, the user adds lights as objects) switch thisR.get('exporter') case 'C4D' thisR = piLightRead(thisR); otherwise end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE below added % Because a light is not automatically added by the Blender exporter, a % light is added here % Add an infinite light corresponding to mid-day sunlight lgt = piLightCreate('infiniteBlender','type','infinite','spd','D65'); thisR.set('light','add',lgt); % thisR = piLightAdd(thisR,'type','infinite','light spectrum','D65'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Read Scale, if it exists % Because PBRT is a LHS and many object models are exported with a RHS, % sometimes we stick in a Scale -1 1 1 to flip the x-axis. If this scaling % is already in the PBRT file, we want to keep it around. % fprintf('Reading scale\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above [~, scaleBlock] = piBlockExtract_Blender(txtLines,'blockName','Scale','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % The Blender exporter automatically sets the Scale at [-1 1 1] because % Blender is right-handed and pbrt is left-handed. But, this function % converts the handedness of the scene to be left-handed, so this scaling % is no longer needed. if isequal(thisR.exporter,'Blender') scaleBlock = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(isempty(scaleBlock)) thisR.scale = []; else values = textscan(scaleBlock{1}, '%s %f %f %f'); thisR.scale = [values{2} values{3} values{4}]; end %% Read Material.pbrt file if readmaterials piReadMaterials(thisR); elseif isequal(thisR.exporter,'Copy') fprintf('Copying materials.\n'); else fprintf('Skipping materials and texture read.\n'); end %% Read geometry.pbrt file if pbrt file is exported by C4D piReadGeometry(thisR); % I was thinking about summarizing what was read. % disp(summary) end %% Helper functions %% Generic text reading, omitting comments and including comments function [txtLines, header] = piReadText(fname) % Open, read, close excluding comment lines fileID = fopen(fname); tmp = textscan(fileID,'%s','Delimiter','\n','CommentStyle',{'#'}); txtLines = tmp{1}; fclose(fileID); % Include comments so we can read only the first line, really fileID = fopen(fname); tmp = textscan(fileID,'%s','Delimiter','\n'); header = tmp{1}; fclose(fileID); end %% Find the text in WorldBegin/End section function txtLines = piReadWorldText(thisR,txtLines) % % Finds the text lines from WorldBegin % It puts the world section into the thisR.world. % Then it removes the world section from the txtLines % % Why doesn't this go to WorldEnd? We are hoping that nothing is important % after WorldEnd. But ... % worldBeginIndex = 0; for ii = 1:length(txtLines) currLine = txtLines{ii}; if(piContains(currLine,'WorldBegin')) worldBeginIndex = ii; break; end end % fprintf('Through the loop\n'); if(worldBeginIndex == 0) warning('Cannot find WorldBegin.'); worldBeginIndex = ii; end % Store the text from WorldBegin to the end here thisR.world = txtLines(worldBeginIndex:end); % Store the text lines from before WorldBegin here txtLines = txtLines(1:(worldBeginIndex-1)); end %% Determine whether this is a Cinema4D export or not function exporterFlag = piReadExporter(thisR,header) % % Read the first line of the scene file to see if it is a Cinema 4D file % Also, check the materials file for consistency. % Set the recipe accordingly and return a true/false flag % if piContains(header{1}, 'Exported by PBRT exporter for Cinema 4D') % Interprets the information and writes the _geometry.pbrt and % _materials.pbrt files to the rendering folder. exporterFlag = true; thisR.exporter = 'C4D'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to also set the exporterFlag to true if the exporter was Blender elseif isequal(thisR.exporter,'Blender') % Interprets the information and writes the _geometry.pbrt and % _materials.pbrt files to the rendering folder. exporterFlag = true; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % Copies the original _geometry.pbrt and _materials.pbrt to the % rendering folder. exporterFlag = false; thisR.exporter = 'Copy'; end % Check that the materials file export information matches the scene file % export % Read the materials file if it exists. inputFile_materials = thisR.get('materials file'); if exist(inputFile_materials,'file') % Confirm that the material file matches the exporter of the main scene % file. fileID = fopen(inputFile_materials); tmp = textscan(fileID,'%s','Delimiter','\n'); headerCheck_material = tmp{1}; fclose(fileID); if ~piContains(headerCheck_material{1}, 'Exported by piMaterialWrite') if isequal(exporterFlag,true) && isequal(thisR.exporter,'C4D') % Everything is fine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % to deal with the exporter being Blender elseif isequal(exporterFlag,true) && isequal(thisR.exporter,'Blender') % Everything is fine %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif isequal(thisR.exporter,'Copy') % Everything is still fine else warning('Puzzled about the materials file.'); end else if isequal(exporterFlag,false) % Everything is fine else warning('Non-standard materials file. Export match not C4D like main file'); end end else % No material field. If exporter is Cinema4D, that's not good. Check % that condition here if isequal(thisR.exporter,'C4D') warning('No materials file for a C4D export'); end end end %% Read the materials file function thisR = piReadMaterials(thisR) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to include Blender exporter if isequal(thisR.exporter,'C4D') || isequal(thisR.exporter,'Blender') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This reads both the materials and the textures inputFile_materials = thisR.get('materials file'); % Check if the materials.pbrt exist if ~exist(inputFile_materials,'file'), error('File not found'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % Edited on Oct 12, 2021, for updated version of 'piMateralRead' thisR.materials.list = piMaterialRead(thisR, inputFile_materials); %[thisR.materials.list,thisR.materials.txtLines] = piMaterialRead(thisR, inputFile_materials); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% thisR.materials.inputFile_materials = inputFile_materials; % Call material lib thisR.materials.lib = piMateriallib; %{ % Convert all jpg textures to png format % Only *.png & *.exr are supported in pbrt. piTextureFileFormat(thisR); %} % Now read the textures from the materials file [thisR.textures.list, thisR.textures.txtLines] = piTextureRead(thisR, inputFile_materials); thisR.textures.inputFile_textures = inputFile_materials; end end %% Build the lookAt information function [flip,thisR] = piReadLookAt(thisR,txtLines) % Reads multiple blocks to create the lookAt field and flip variable % % The lookAt is built up by reading from, to, up field and transform and % concatTransform. % % Interpreting these variables from the text can be more complicated w.r.t. % formatting. % A flag for flipping from a RHS to a LHS. flip = 0; % Get the block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above [~, lookAtBlock] = piBlockExtract_Blender(txtLines,'blockName','LookAt','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(isempty(lookAtBlock)) % If it is empty, use the default thisR.lookAt = struct('from',[0 0 0],'to',[0 1 0],'up',[0 0 1]); else % We have values values = textscan(lookAtBlock{1}, '%s %f %f %f %f %f %f %f %f %f'); from = [values{2} values{3} values{4}]; to = [values{5} values{6} values{7}]; up = [values{8} values{9} values{10}]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % to convert the right-handed coordinate system of the Blender export % into the left-handed pbrt system if isequal(thisR.exporter,'Blender') from = from([1 3 2]); to = to([1 3 2]); up = up([1 3 2]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end % If there's a transform, we transform the LookAt. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above [~, transformBlock] = piBlockExtract_Blender(txtLines,'blockName','Transform','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(~isempty(transformBlock)) values = textscan(transformBlock{1}, '%s [%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); values = cell2mat(values(2:end)); transform = reshape(values,[4 4]); [from,to,up,flip] = piTransform2LookAt(transform); end % If there's a concat transform, we use it to update the current camera % position. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % as above [~, concatTBlock] = piBlockExtract_Blender(txtLines,'blockName','ConcatTransform','exporter',thisR.exporter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(~isempty(concatTBlock)) values = textscan(concatTBlock{1}, '%s [%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); values = cell2mat(values(2:end)); concatTransform = reshape(values,[4 4]); % Apply transform and update lookAt lookAtTransform = piLookat2Transform(from,to,up); [from,to,up,flip] = piTransform2LookAt(lookAtTransform*concatTransform); end % Warn the user if nothing was found if(isempty(transformBlock) && isempty(lookAtBlock)) warning('Cannot find "LookAt" or "Transform" in PBRT file. Returning default.'); end thisR.lookAt = struct('from',from,'to',to,'up',up); end %% Read the geometry file function thisR = piReadGeometry(thisR) % Call the geometry reading and parsing function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to include Blender exporter if isequal(thisR.exporter,'C4D') || isequal(thisR.exporter,'Blender') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('Reading C4D geometry information.\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to call an edited version of piGeometryRead.m % that extracts scale and rotation information separately per object thisR = piGeometryRead_Blender(thisR); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif isequal(thisR.exporter,'Copy') fprintf('Geometry file will be copied by piWriteCopy.\n'); else fprintf('Skipping geometry.\n'); end end %% Rewrite txtLines in C4D format %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: helper function added % This helper function is called if the Blender exporter was used % and it rewrites 'txtLines' in C4D format function txtLines = piWriteC4Dformat_txt(txtLines) % Remove a parameter that is not currently identified by piBlockExtractC4D.m % as well as any empty lines lineidx = cellfun('isempty',txtLines); txtLines(lineidx) = []; lineidx = piContains(txtLines,'bool'); txtLines(lineidx) = []; % Rewrite each block's lines into a single line, including lines that begin % with a double quote, as well as lines that begin with a +/- number (this % is unique to Blender exports) nLines = length(txtLines); ii=1; while ii<nLines % Append to the iith line any subsequent line/s whose first symbol is a % double quote ("), a number, or a negative sign (-) until the block ends for jj=(ii+1):nLines if isequal(txtLines{jj}(1),'"') || ... ~isnan(str2double(txtLines{jj}(1))) || isequal(txtLines{jj}(1),'-') txtLines{ii} = append(txtLines{ii},' ',txtLines{jj}); txtLines{jj} = []; if jj==nLines ii = jj; end else ii = jj; break end end end % Remove empty lines lineidx = cellfun('isempty',txtLines); txtLines(lineidx) = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Create materials and geometry files in C4D format %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: helper function added % This helper function is called if the Blender exporter was used % and it creates materials and geometry files in C4D format % (the Blender exporter does not create materials and geometry files) function piWriteC4Dformat_files(thisR) % Get materials and geometry file names inputFile_materials = thisR.get('materials file'); [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If both files already exist, exit this function; otherwise, proceed if exist(inputFile_materials,'file') && exist(inputFile_geometry,'file') fprintf('Materials and geometry files not created - they already exist.\n'); return end % Since the materials and/or geometry files don't exist, start the process % of creating them allLines = thisR.world; % Find how many objects need to be defined beginLines = find(piContains(allLines,'AttributeBegin')); numbeginLines = numel(beginLines); % Preallocate cell arrays for materials and geometry text materials = cell(size(allLines)); geometry = cell(size(allLines)); % Read out one object at a time for ii = 1:numbeginLines % Start with the 'AttributeBegin' line startidx = beginLines(ii); % Find the index for the last line for this object endidx = find(piContains(allLines(startidx+1:end),'AttributeEnd'),1,'first'); endallidx = endidx + startidx; % Pull all of the lines for this object objectLines = allLines(startidx:endallidx); % For now, not reading out object light sources lightidx = piContains(objectLines,'LightSource'); if any(lightidx) continue end % Preallocate cell array for object's geometry text geometryobj = cell(numel(objectLines)+6,1); % Add an 'AttributeBegin' line geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeBegin'; % Get object name (Blender files are not exported with object names) % If there is a .ply file associated with the object, use that file name plylineidx = piContains(objectLines,'.ply'); if any(plylineidx) plyline = objectLines{plylineidx}; [~,objectname] = fileparts(plyline); % Remove the '_mat0' that the Blender exporter adds automatically objectname = objectname(1:end-5); % If there is no .ply file, give the object a generic name else objectname = (['object' num2str(ii)]); end % Reformat the object name line in the same format as a C4D geometry file % (The 'Vector' parameter will be set later) nameline = append('#ObjectName ',objectname); geometryobj{find(cellfun(@isempty,geometryobj),1)} = nameline; %Add the transform line Tlineidx = piContains(objectLines,'Transform'); if any(Tlineidx) geometryobj{find(cellfun(@isempty,geometryobj),1)} = objectLines{Tlineidx}; end % Add an 'AttributeBegin' line geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeBegin'; % Get material name and parameters Mlineidx = piContains(objectLines,'Material'); if any(Mlineidx) Mline = objectLines{Mlineidx}; % Get material name only Mname = textscan(Mline,'%q'); Mname = Mname{1}; Mname = Mname{2}; % Start this part of the material line with the material name Mline = append('"',Mname,'"'); % Append all material parameters to the material line started above nLines = endidx-1; for jj=find(Mlineidx)+1:nLines thisLine = objectLines{jj}; % If the next line contains a double quote (") it gets appended if isequal(thisLine(1),'"') % The color parameters get special treatment because of how % they are exported from Blender if piContains(thisLine,'color') % The Blender exporter puts a space after the '[' % character for color parameters, which has to be % removed to be compatible with piParseRGB.m later thisLine = replace(thisLine,'[ ', '['); % Rename color parameters because the Blender exporter % uses the 'color' synonym for 'rgb' and not all % 'color' values are read out in piBlockExtractMaterial.m thisLine = replace(thisLine,'color','rgb'); end % Append the line Mline = append(Mline,' ',strtrim(thisLine)); % If the next line does not contain a double quote, break else break end end else % If the object was exported from Blender without a pbrt material % assign a default material here (gray matte) Mline = '"matte" "float sigma" [0] "rgb Kd" [.9 .9 .9]'; end % Assign material name (Blender files are not exported with % material names) based on the object name assigned above materialname = append(objectname,'_material'); % Reformat the material line for this object's materials text Materialline = append('MakeNamedMaterial "',materialname,'" "string type" ',Mline); % Get texture parameters Tlineidx = piContains(objectLines,'Texture'); if any(Tlineidx) Textureline = objectLines{Tlineidx}; % Replace "color" with "spectrum" to match C4D format Textureline = strrep(Textureline,"color","spectrum"); % The pbrt file exported from Blender refers to texture files in a % 'textures' folder, but any texture files were moved directly into % the scene folder for use in iset3d, so we need to remove any % references to a 'textures' folder Textureline = strrep(Textureline,"[""textures/",""""); Textureline = strrep(Textureline,".exr""]",".exr"""); % Add the texture line to this object's materials text materials{find(cellfun(@isempty,materials),1)} = Textureline; end % Add the material line to this object's materials text (it is added % after this object's texture line, if this object has a texture) materials{find(cellfun(@isempty,materials),1)} = Materialline; % Create a material line for this object's geometry text GMaterialline = append('NamedMaterial "',materialname,'"'); geometryobj{find(cellfun(@isempty,geometryobj),1)} = GMaterialline; % Get shape parameters Slineidx = piContains(objectLines,'Shape'); if any(Slineidx) % If the shape parameters are described by a .ply file, don't % reformat the shape line (the .ply file will be read out later) if piContains(objectLines{Slineidx},'.ply') Sline = objectLines{Slineidx}; % But if not, reformat the shape parameters into a single line else objectLines(1:find(Slineidx)-1) = []; objectLines(end) = []; Sline = cellfun(@string,objectLines); Sline = join(Sline); % Remove an extra space after the '[' character Sline = replace(Sline,'[ ', '['); Sline = convertStringsToChars(Sline); end geometryobj{find(cellfun(@isempty,geometryobj),1)} = Sline; end % Complete this object description geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeEnd'; geometryobj{find(cellfun(@isempty,geometryobj),1)} = 'AttributeEnd'; % Remove any empty cells lineidx = cellfun('isempty',geometryobj); geometryobj(lineidx) = []; % Add to geometry text Gstartidx = find(cellfun(@isempty,geometry),1); Gendidx = Gstartidx + numel(geometryobj) - 1; try geometry(Gstartidx:Gendidx) = geometryobj; catch geometry = [geometry; geometryobj]; end end % Complete materials text and geometry text lineidx = cellfun('isempty',geometry); geometry(lineidx) = []; lineidx = cellfun('isempty',materials); materials(lineidx) = []; % If the materials file doesn't exist, create it in the same folder as the % pbrt scene file if ~exist(inputFile_materials,'file') % Open up a new materials file fileID = fopen(inputFile_materials,'w'); % Write in a comment describing when this file was created fprintf(fileID,'# PBRT file created in C4D exporter format on %i/%i/%i %i:%i:%0.2f \n',clock); % Blank line fprintf(fileID,'\n'); % Write in materials text materials = materials'; fprintf(fileID,'%s\n',materials{:}); % Close the materials file fclose(fileID); fprintf('A new materials file was created in %s\n', inFilepath); end % If the geometry file doesn't exist, create it in the same folder as the % pbrt scene file if ~exist(inputFile_geometry,'file') % Open up a new geometry file fileID = fopen(inputFile_geometry,'w'); % Write in a comment describing when this file was created fprintf(fileID,'# PBRT file created in C4D exporter format on %i/%i/%i %i:%i:%0.2f \n',clock); % Blank line fprintf(fileID,'\n'); % Write in geometry text geometry = geometry'; fprintf(fileID,'%s\n',geometry{:}); % Close the materials file fclose(fileID); fprintf('A new geometry file was created in %s\n', inFilepath); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Rewrite thisR.world in C4D format %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: helper function added % This helper function is called if the Blender exporter was used % and it rewrites 'thisR.world' in C4D format % to include the materials and geometry files function thisR = piWriteC4Dformat_world(thisR) world{1,1} = 'WorldBegin'; % Include the materials file [~,scene_fname] = fileparts(thisR.inputFile); world{2,1} = append('Include "',scene_fname,'_materials.pbrt"'); % Include the geometry file world{3,1} = append('Include "',scene_fname,'_geometry.pbrt"'); world{4,1} = 'WorldEnd'; % Update thisR.world thisR.world = world; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Rewrite .ply functions in C4D format %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: helper function added % that extracts geometry information from .ply functions in the geometry file function piWriteC4Dformat_ply(thisR) % Get geometry file name [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If the geometry file doesn't exist, give warning and exit this function if ~exist(inputFile_geometry,'file') warning('Geometry file does not exist.'); return end % Get text from geometry file fileID = fopen(inputFile_geometry,'r'); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); % Check for .ply files and exit this function if they do not exist sLines = find(piContains(txtLines,'.ply')); if ~any(sLines) return end % Replace text lines referencing .ply files with their geometry information numsLines = numel(sLines); for ii = 1:numsLines thisLine = txtLines{sLines(ii)}; % Get the name of the .ply file plyLine = textscan(thisLine,'%q'); plyLine = plyLine{1}; plylineidx = piContains(plyLine,'.ply'); plyLine = plyLine{plylineidx}; [~,objectname] = fileparts(plyLine); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: new function below % The function below is a modified version of pcread.m % that reads out the per-vertex texture coordinates (in addition to the % per-vertex locations and normals read out by pcread.m)from the .ply file [ptCloud,plyTexture] = pcread_Blender([objectname '.ply']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set up .ply file output in pbrt format plyLocation = ptCloud.Location; plyNormal = ptCloud.Normal; %pcshow(ptCloud); %uncomment this line to plot points % NOTE: for now, assumes all exported objects are triangle mesh Shape = 'trianglemesh'; % Align vertices with their corresponding normals and texture coordinates plyAll = [plyLocation plyNormal plyTexture]; % Get the unique vertices/normals/texture coordinates uvertices = unique(plyAll,'rows'); % Separate out the three parameters pointP = uvertices(:,1:size(plyLocation,2)); normalN = uvertices(:,size(plyLocation,2)+1:size(plyLocation,2)+size(plyNormal,2)); floatuv = uvertices(:,size(plyLocation,2)+size(plyNormal,2)+1:end); % Calculate the integer indices [~,integerindices] = ismember(plyAll,uvertices,'rows'); % Integers currently start at 1 but need to start at 0 integerindices = integerindices - 1; % Reshape into pbrt format integerindices = integerindices'; pointP = reshape(pointP.',1,[]); normalN = reshape(normalN.',1,[]); floatuv = reshape(floatuv.',1,[]); % Convert to strings integerindices = mat2str(integerindices); pointP = mat2str(pointP); normalN = mat2str(normalN); floatuv = mat2str(floatuv); % Rewrite 'Shape' line in pbrt format newLine = append('Shape "',Shape,'" "integer indices" ',integerindices, ... ' "point P" ',pointP); if ~isempty(plyNormal) newLine = append(newLine,' "normal N" ',normalN); end if ~isempty(plyTexture) newLine = append(newLine,' "float uv" ',floatuv); end % Replace the old 'Shape' line with the rewritten line txtLines{sLines(ii)} = newLine; end % Update geometry file text fileID = fopen(inputFile_geometry,'w'); txtLines = txtLines'; fprintf(fileID,'%s\n',txtLines{:}); fclose(fileID); fprintf('One or more .ply functions were parsed in the geometry file.\n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Convert a right-handed coordinate system to the left-handed pbrt system %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: helper function added % that converts a right-handed coordinate system into the left-handed pbrt % system % (this function should always be called once for Blender exports, because % Blender uses a right-handed coordinate system) function piWriteC4Dformat_handedness(thisR) % Get geometry file name [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If the geometry file doesn't exist, give warning and exit this function if ~exist(inputFile_geometry,'file') warning('Geometry file does not exist.'); return end % Get text from geometry file fileID = fopen(inputFile_geometry,'r'); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); % If this conversion to a left-handed coordinate system has already % occurred, exit this function (must only do this conversion once) checkflg = piContains(txtLines,'Converted to a left-handed coordinate system'); if any(checkflg) return end % Switch y and z coordinates per vertex for vertex positions ('point P') % and per-vertex normals ('normal N') in the 'Shape' line for each object pLines = find(piContains(txtLines,'"point P"')); numsLines = numel(pLines); for ii = 1:numsLines Pline = txtLines{pLines(ii)}; % Get 'point P' vector pidx = strfind(Pline,'"point P"'); pPline = Pline(pidx:end); openidx = strfind(pPline,'['); closeidx = strfind(pPline,']'); pointP = pPline(openidx(1)+1:closeidx(1)-1); pointP = str2num(pointP); % Reshape points into three columns (three axes) numvertices = numel(pointP)/3; pointP = reshape(pointP,[3,numvertices]); pointP = pointP'; % Switch y and z coordinates pointP = pointP(:,[1 3 2]); % Reshape points into vector pointP = reshape(pointP.',1,[]); % Convert to string pointP = mat2str(pointP); % Replace converted 'point P' in the 'Shape' line Pline = append(Pline(1:pidx+9),pointP,Pline(pidx+closeidx(1):end)); % If the 'normal N' vector exists, switch y and z coordinates as above nidx = strfind(Pline,'"normal N"'); if ~isempty(nidx) nPline = Pline(nidx:end); openidx = strfind(nPline,'['); closeidx = strfind(nPline,']'); normalN = nPline(openidx(1)+1:closeidx(1)-1); normalN = str2num(normalN); normalN = reshape(normalN,[3,numvertices]); normalN = normalN'; normalN = normalN(:,[1 3 2]); normalN = reshape(normalN.',1,[]); normalN = mat2str(normalN); Pline = append(Pline(1:nidx+10),normalN,Pline(nidx+closeidx(1):end)); end % Replace old 'Shape' text line with new text line txtLines{pLines(ii)} = Pline; end % Convert 'Transform' matrices into left-handed matrices for each object tLines = find(piContains(txtLines,'Transform')); numsLines = numel(tLines); for ii = 1:numsLines Tline = txtLines{tLines(ii)}; % Get 'Transform' vector openidx = strfind(Tline,'['); closeidx = strfind(Tline,']'); Transform = Tline(openidx(1)+1:closeidx-1); Transform = str2num(Transform); % Convert the right-handed matrix into a left-handed matrix Transform = reshape(Transform,[4,4]); Transform(:,[2 3]) = Transform(:,[3 2]); Transform([2 3],:) = Transform([3 2],:); % Reshape matrix into vector Transform = reshape(Transform,[1 16]); % Convert to string Transform = mat2str(Transform); % Replace converted 'Transform' vector Tline = append('Transform ',Transform); % Replace old 'Transform' text line with new text line txtLines{tLines(ii)} = Tline; end % Update geometry file text fileID = fopen(inputFile_geometry,'w'); fprintf(fileID,'%s\n',txtLines{1}); % Write in a comment describing when the handedness was converted % (this helper function will watch out for this comment in the future % because you must only do this conversion once) fprintf(fileID,'# Converted to a left-handed coordinate system on %i/%i/%i %i:%i:%0.2f \n',clock); txtLines = txtLines(2:end); txtLines = txtLines'; fprintf(fileID,'%s\n',txtLines{:}); fclose(fileID); fprintf('Coordinate system was converted to left-handed pbrt system in the geometry file.\n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Calculate vector information %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: helper function added % that calculate 'Vector' information in the geometry file % (this function should always be called for Blender exports, because the % Blender exporter does not include vector information automatically) function piWriteC4Dformat_vector(thisR) % Get geometry file name [inFilepath,scene_fname] = fileparts(thisR.inputFile); inputFile_geometry = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); % If the geometry file doesn't exist, give warning and exit this function if ~exist(inputFile_geometry,'file') warning('Geometry file does not exist.'); return end % Get text from geometry file fileID = fopen(inputFile_geometry,'r'); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); % Check for 'Vector' parameter and exit this function if it already exists vLines = find(piContains(txtLines,':Vector(')); if any(vLines) return end % Add 'Vector' information to object name text lines oLines = find(piContains(txtLines,'#ObjectName')); numsLines = numel(oLines); for ii = 1:numsLines thisLine = txtLines{oLines(ii)}; % Find shape parameters for this object restoftxt = txtLines(oLines(ii)+1:numel(txtLines)); endLine = find(piContains(restoftxt,'AttributeEnd'),1,'first'); thistxt = restoftxt(1:endLine); lineidx = piContains(thistxt,'point P'); % If shape parameters do not exist for this object, give default vector if ~any(lineidx) thisLine = append(thisLine,':Vector(0, 0, 0)'); else % Get 'point P' vector Pline = thistxt{lineidx}; pidx = strfind(Pline,'"point P"'); Pline = Pline(pidx:end); openidx = strfind(Pline,'['); closeidx = strfind(Pline,']'); pointP = Pline(openidx(1)+1:closeidx(1)-1); pointP = str2num(pointP); % Reshape points into three columns (three axes) numvertices = numel(pointP)/3; pointP = reshape(pointP,[3,numvertices]); pointP = pointP'; % Calculate vector parameter minpointP = min(pointP); maxpointP = max(pointP); diffpointP = abs(minpointP)+abs(maxpointP); v = diffpointP/2; % Add vector to object name line in pbrt format, which is % NAME:Vector(X, Z, Y) thisLine = append(thisLine,':Vector(',num2str(v(1)),', ',num2str(v(3)),', ',num2str(v(2)),')'); end % Replace old object text line with new text line txtLines{oLines(ii)} = thisLine; end % Update geometry file text fileID = fopen(inputFile_geometry,'w'); txtLines = txtLines'; fprintf(fileID,'%s\n',txtLines{:}); fclose(fileID); fprintf('Vector information was updated in the geometry file.\n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
ISET/iset3d-v3-master
piWrite_Blender.m
.m
iset3d-v3-master/utilities/blender/piWrite_Blender.m
25,616
utf_8
360ff1a5d7e4647038905bc7467e780d
function workingDir = piWrite_Blender(thisR,varargin) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below added % Adapted from piWrite.m to handle the exporter being set to 'Blender' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Write a PBRT scene file based on its renderRecipe % % Syntax % workingDir = piWrite(thisR,varargin) % % The pbrt scene file and all the relevant resource files (geometry, % materials, spds, others) are written out in a working directory. These % are the files that will be mounted by the docker container and used by % PBRT to create the radiance, depth, mesh metadata outputs. % % There are multiple options as to whether or not to overwrite files that % are already present in the output directory. The logic and conditions % about these overwrites is quite complex right now, and we need to % simplify. % % In some cases, multiple PBRT scenes use the same resources files. If you % know the resources files are already there, you can set % overwriteresources to false. Similarly if you do not want to overwrite % the pbrt scene file, set overwritepbrtfile to false. % % Input % thisR: a recipe object describing the rendering parameters. % % Optional key/value parameters % There are too many of these options. We hope to simplify % % overwrite pbrtfile - If scene PBRT file exists, overwrite (default true) % overwrite resources - If the resources files exist, overwrite (default true) % overwrite lensfile - Logical. Default true % overwrite materials - Logical. Default true % overwrite geometry - Logical. Default true % overwrite json - Logical. Default true % creatematerials - Logical. Default false % lightsFlag % thistrafficflow % % Return % workingDir - path to the output directory mounted by the Docker % container. This is not necessary, however, because we % can find it from thisR.get('output dir') % % TL Scien Stanford 2017 % JNM -- Add Windows support 01/25/2019 % % See also % piRead, piRender % Examples: %{ thisR = piRecipeDefault('scene name','MacBethChecker'); % thisR = piRecipeDefault('scene name','SimpleScene'); % thisR = piRecipeDefault('scene name','teapot'); piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); %} %{ thisR = piRecipeDefault('scene name','chessSet'); lensfile = 'fisheye.87deg.6.0mm.json'; thisR.camera = piCameraCreate('omni','lensFile',lensfile); thisR.set('film resolution',round([300 200])); thisR.set('pixel samples',32); % Number of rays set the quality. thisR.set('focus distance',0.45); thisR.set('film diagonal',10); thisR.integrator.subtype = 'path'; thisR.sampler.subtype = 'sobol'; thisR.set('aperture diameter',3); piWrite(thisR,'creatematerials',true); oi = piRender(thisR,'render type','radiance'); oiWindow(oi); %} %{ piWrite(thisR,'overwrite resources',false,'overwrite pbrt file',true); piWrite(thisR); %} %% Parse inputs varargin = ieParamFormat(varargin); p = inputParser; % When varargin contains a number, the ieParamFormat() method fails. % It takes only a string or cell. We should look into that. % varargin = ieParamFormat(varargin); p.addRequired('thisR',@(x)isequal(class(x),'recipe')); % % JNM -- Why format variables twice? % % Format the parameters by removing spaces and forcing lower case. % if ~isempty(varargin), varargin = ieParamFormat(varargin); end % Copy over the whole directory p.addParameter('overwriteresources', true,@islogical); % Overwrite the specific scene file p.addParameter('overwritepbrtfile',true,@islogical); % Force overwrite of the lens file p.addParameter('overwritelensfile',true,@islogical); % Overwrite materials.pbrt p.addParameter('overwritematerials',true,@islogical); % Overwrite geometry.pbrt p.addParameter('overwritegeometry',true,@islogical); % Create a new materials.pbrt p.addParameter('creatematerials',false,@islogical); % control lighting in geomtery.pbrt p.addParameter('lightsflag',false,@islogical); % Read trafficflow variable p.addParameter('thistrafficflow',[]); % Second rendering for reflectance calculation % p.addParameter('reflectancerender',false,@islogical); % Store JSON recipe for the traffic scenes p.addParameter('overwritejson',true,@islogical); p.parse(thisR,varargin{:}); overwriteresources = p.Results.overwriteresources; overwritepbrtfile = p.Results.overwritepbrtfile; overwritelensfile = p.Results.overwritelensfile; overwritematerials = p.Results.overwritematerials; overwritegeometry = p.Results.overwritegeometry; creatematerials = p.Results.creatematerials; lightsFlag = p.Results.lightsflag; thistrafficflow = p.Results.thistrafficflow; overwritejson = p.Results.overwritejson; %% Check exporter condition % What we read and copy depends on how we got the PBRT files in the first % place. The exporter string identifies whether it is a C4D set of files, % the most common for us, or another source that we are simply copying % ('Copy') or just 'Unknown'. We impose some constraints on the % over-writing flags if the exporter is 'Copy'. exporter = thisR.get('exporter'); switch exporter case 'Copy' creatematerials = false; overwritegeometry = false; overwritematerials = false; overwritejson = false; otherwise % In most cases, we accept whatever the user set. The other cases % at present are 'C4D' and 'Unknown' end %% Check the input and output directories % Input must exist inputDir = thisR.get('input dir'); if ~exist(inputDir,'dir'), warning('Could not find %s\n',inputDir); end % Make working dir if it does not already exist workingDir = thisR.get('output dir'); if ~exist(workingDir,'dir'), mkdir(workingDir); end % Make a geometry directory geometryDir = thisR.get('geometry dir'); if ~exist(geometryDir, 'dir'), mkdir(geometryDir); end renderDir = thisR.get('rendered dir'); if ~exist(renderDir,'dir'), mkdir(renderDir); end %% Selectively copy data from the input to the output directory. piWriteCopy(thisR,overwriteresources,overwritepbrtfile) %% If the optics type is lens, copy the lens file to a lens sub-directory if isequal(thisR.get('optics type'),'lens') % realisticEye has a lens file slot but it is empty. So we check % whether there is a lens file or not. if ~isempty(thisR.get('lensfile')) piWriteLens(thisR,overwritelensfile); end end %% Open up the main PBRT scene file. outFile = thisR.get('output file'); fileID = fopen(outFile,'w'); %% Write header piWriteHeader(thisR,fileID) %% Write Scale and LookAt commands first piWriteLookAtScale(thisR,fileID); %% Write all other blocks that we have field names for piWriteBlocks(thisR,fileID); %% Write out the lights piLightWrite(thisR); %{ renderRecipe = piLightDeleteWorld(thisR, 'all'); % Check if we removed all lights piLightGetFromWorld(thisR) %} %% Add 'Include' lines for materials, geometry and lights into the scene PBRT file piIncludeLines(thisR,fileID, creatematerials,overwritegeometry); %% Close the main PBRT scene file fclose(fileID); %% Write scene_materials.pbrt piWriteMaterials(thisR,creatematerials,overwritematerials); %% Overwrite geometry.pbrt piWriteGeometry(thisR,overwritegeometry,lightsFlag,thistrafficflow) %% Overwrite xxx.json if overwritejson [~,scene_fname,~] = fileparts(thisR.outputFile); jsonFile = fullfile(workingDir,sprintf('%s.json',scene_fname)); jsonwrite(jsonFile,thisR); end end %% Helper functions %% Copy the input resources to the output directory function piWriteCopy(thisR,overwriteresources,overwritepbrtfile) % Copy files from the input to output dir % % In some cases we are looping over many renderings. In that case we may % turn off the repeated copies by setting overwriteresources to false. inputDir = thisR.get('input dir'); outputDir = thisR.get('output dir'); % We check for the overwrite here and we make sure there is also an input % directory to copy from. if overwriteresources && ~isempty(inputDir) sources = dir(inputDir); status = true; for i=1:length(sources) if startsWith(sources(i).name(1),'.') % Skip dot-files continue; elseif sources(i).isdir && (strcmpi(sources(i).name,'spds') || strcmpi(sources(i).name,'textures')) % Copy the spds and textures directory files. status = status && copyfile(fullfile(sources(i).folder, sources(i).name), fullfile(outputDir,sources(i).name)); else % Selectively copy the files in the scene root folder [~, ~, extension] = fileparts(sources(i).name); if ~(piContains(extension,'pbrt') || piContains(extension,'zip') || piContains(extension,'json')) thisFile = fullfile(sources(i).folder, sources(i).name); fprintf('Copying %s\n',thisFile) status = status && copyfile(thisFile, fullfile(outputDir,sources(i).name)); end end end if(~status) error('Failed to copy input directory to docker working directory.'); else fprintf('Copied resources from:\n'); fprintf('%s \n',inputDir); fprintf('to \n'); fprintf('%s \n \n',outputDir); end end %% Potentially overwrite the scene PBRT file outFile = thisR.get('output file'); % Check if the outFile exists. If it does, decide what to do. if(exist(outFile,'file')) if overwritepbrtfile % A pbrt scene file exists. We delete here and write later. fprintf('Overwriting PBRT file %s\n',outFile) delete(outFile); else % Do not overwrite is set, and yet it exists. We don't like this % condition, so we throw an error. error('PBRT file %s exists.',outFile); end end end %% Put the header into the scene PBRT file function piWriteHeader(thisR,fileID) % Write the header % fprintf(fileID,'# PBRT file created with piWrite on %i/%i/%i %i:%i:%0.2f \n',clock); fprintf(fileID,'# PBRT version = %i \n',thisR.version); fprintf(fileID,'\n'); % If a crop window exists, write out a warning if(isfield(thisR.film,'cropwindow')) fprintf(fileID,'# Warning: Crop window exists! \n'); end end %% Write lens information function piWriteLens(thisR,overwritelensfile) % Write out the lens file. Manage cases of overwrite or not % % We also manage special human eye model cases Some of these require % auxiliary files like Index of Refraction files that are specified using % Include statements in the World block. % % See also % navarroWrite, navarroLensCreate, setNavarroAccommodation % Make sure the we have the full path to the input lens file inputLensFile = thisR.get('lens file'); outputDir = thisR.get('output dir'); outputLensFile = thisR.get('lens file output'); outputLensDir = fullfile(outputDir,'lens'); if ~exist(outputLensDir,'dir'), mkdir(outputLensDir); end if isequal(thisR.get('realistic eye model'),'navarro') % Write lens file and the ior files into the output directory. navarroWrite(thisR); elseif isequal(thisR.get('realistic eye model'),'legrand') % Write lens file and the ior files into the output directory. legrandWrite(thisR); elseif isequal(thisR.get('realistic eye model'),'arizona') % Write lens file into the output directory. % Still tracking down why no IOR files are associated with this model. arizonaWrite(thisR); else % If the working copy doesn't exist, copy it. % If it exists but there is a force overwrite, delete and copy. if ~exist(outputLensFile,'file') copyfile(inputLensFile,outputLensFile); elseif overwritelensfile % It must exist. So if we are supposed overwrite delete(outputLensFile); copyfile(inputLensFile,outputLensFile); end end end %% LookAt and Scale fields function piWriteLookAtScale(thisR,fileID) % Optional Scale theScale = thisR.get('scale'); if(~isempty(theScale)) fprintf(fileID,'Scale %0.2f %0.2f %0.2f \n', [theScale(1) theScale(2) theScale(3)]); fprintf(fileID,'\n'); end % Optional Motion Blur % default StartTime and EndTime is 0 to 1; if isfield(thisR.camera,'motion') motionTranslate = thisR.get('camera motion translate'); motionStart = thisR.get('camera motion rotation start'); motionEnd = thisR.get('camera motion rotation end'); fprintf(fileID,'ActiveTransform StartTime \n'); fprintf(fileID,'Translate 0 0 0 \n'); fprintf(fileID,'Rotate %f %f %f %f \n',motionStart(:,1)); % Z fprintf(fileID,'Rotate %f %f %f %f \n',motionStart(:,2)); % Y fprintf(fileID,'Rotate %f %f %f %f \n',motionStart(:,3)); % X fprintf(fileID,'ActiveTransform EndTime \n'); fprintf(fileID,'Translate %0.2f %0.2f %0.2f \n',... [motionTranslate(1),... motionTranslate(2),... motionTranslate(3)]); fprintf(fileID,'Rotate %f %f %f %f \n',motionEnd(:,1)); % Z fprintf(fileID,'Rotate %f %f %f %f \n',motionEnd(:,2)); % Y fprintf(fileID,'Rotate %f %f %f %f \n',motionEnd(:,3)); % X fprintf(fileID,'ActiveTransform All \n'); end % Required LookAt from = thisR.get('from'); to = thisR.get('to'); up = thisR.get('up'); fprintf(fileID,'LookAt %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f \n', ... [from(:); to(:); up(:)]); fprintf(fileID,'\n'); end %% function piWriteBlocks(thisR,fileID) % Loop through the thisR fields, writing them out as required % % The blocks that are written out include % % Camera and lens % workingDir = thisR.get('output dir'); % These are the main fields in the recipe. We call them the outer fields. % Within each outer field, there will be inner fields. outerFields = fieldnames(thisR); for ofns = outerFields' ofn = ofns{1}; % If empty, we skip this field. if(~isfield(thisR.(ofn),'type') || ... ~isfield(thisR.(ofn),'subtype')) continue; end % Skip, we don't want to write these out here. So if any one of these, % we skip to the next for-loop step if(strcmp(ofn,'world') || ... strcmp(ofn,'lookAt') || ... strcmp(ofn,'inputFile') || ... strcmp(ofn,'outputFile')|| ... strcmp(ofn,'version')) || ... strcmp(ofn,'materials')|| ... strcmp(ofn,'world') continue; end % Deal with camera and medium if strcmp(ofn,'camera') && isfield(thisR.(ofn),'medium') if ~isempty(thisR.(ofn).medium) currentMedium = []; for j=1:length(thisR.media.list) if strcmp(thisR.media.list(j).name,thisR.(ofn).medium) currentMedium = thisR.media.list; end end fprintf(fileID,'MakeNamedMedium "%s" "string type" "water" "string absFile" "spds/%s_abs.spd" "string vsfFile" "spds/%s_vsf.spd"\n',currentMedium.name,... currentMedium.name,currentMedium.name); fprintf(fileID,'MediumInterface "" "%s"\n',currentMedium.name); end end % Write header that identifies which block this is fprintf(fileID,'# %s \n',ofn); % Write out the main type and subtypes fprintf(fileID,'%s "%s" \n',thisR.(ofn).type,... thisR.(ofn).subtype); % Find and then loop through inner field names innerFields = fieldnames(thisR.(ofn)); if(~isempty(innerFields)) for ifns = innerFields' ifn = ifns{1}; % Skip these since we've written these out earlier. if(strcmp(ifn,'type') || ... strcmp(ifn,'subtype') || ... strcmp(ifn,'subpixels_h') || ... strcmp(ifn,'subpixels_w') || ... strcmp(ifn,'motion') || ... strcmp(ifn,'subpixels_w') || ... strcmp(ifn,'medium')) continue; end %{ Many fields are written out in here. Some examples are type, subtype, lensfile retinaDistance retinaRadius pupilDiameter retinaSemiDiam ior1 ior2 ior3 ior4 type subtype pixelsamples type subtype xresolution yresolution type subtype maxdepth %} currValue = thisR.(ofn).(ifn).value; currType = thisR.(ofn).(ifn).type; if(strcmp(currType,'string') || ischar(currValue)) % We have a string with some value lineFormat = ' "%s %s" "%s" \n'; % The currValue might be a full path to a file with an % extension. We find the base file name and copy the file % to the working directory. Then, we transform the string % to be printed in the pbrt scene file to be its new % relative path. There is a minor exception for the lens % file. Perhaps we should have a better test here, say an % exist() test. (BW). [~,name,ext] = fileparts(currValue); if(~isempty(ext)) % This looks like a file with an extension. If it is a % lens file or an iorX.spd file, indicate that it is in % the lens/ directory. Otherwise, copy the file to the % working directory. fileName = strcat(name,ext); if strcmp(ifn,'specfile') || strcmp(ifn,'lensfile') % It is a lens, so just update the name. It % was already copied % This should work. % currValue = strcat('lens',[filesep, strcat(name,ext)]); if ispc() currValue = strcat('lens/',strcat(name,ext)); else currValue = fullfile('lens',strcat(name,ext)); end elseif piContains(ifn,'ior') % The the innerfield name contains the ior string, % then we change it to this currValue = strcat('lens',[filesep, strcat(name,ext)]); else [success,~,id] = copyfile(currValue,workingDir); if ~success && ~strcmp(id,'MATLAB:COPYFILE:SourceAndDestinationSame') warning('Problem copying %s\n',currValue); end % Update the file for the relative path currValue = fileName; end end elseif(strcmp(currType,'spectrum') && ~ischar(currValue)) % A spectrum of type [wave1 wave2 value1 value2]. TODO: % There are probably more variations of this... lineFormat = ' "%s %s" [%f %f %f %f] \n'; elseif(strcmp(currType,'rgb')) lineFormat = ' "%s %s" [%f %f %f] \n'; elseif(strcmp(currType,'float')) if(length(currValue) > 1) lineFormat = ' "%s %s" [%f %f %f %f] \n'; else lineFormat = ' "%s %s" [%f] \n'; end elseif(strcmp(currType,'integer')) lineFormat = ' "%s %s" [%i] \n'; end fprintf(fileID,lineFormat,... currType,ifn,currValue); end end % Blank line. fprintf(fileID,'\n'); end end %% function piIncludeLines(thisR,fileID, creatematerials,overwritegeometry) % Insert the 'Include scene_materials.pbrt' and similarly for geometry and % lights into the main scene file % % We may have created new materials in ISET3d. We insert 'Include' for % materials, geometry, and lights. if creatematerials for ii = 1:length(thisR.world) currLine = thisR.world{ii}; if piContains(currLine, 'materials.pbrt') [~,n] = fileparts(thisR.outputFile); currLine = sprintf('Include "%s_materials.pbrt"',n); end if overwritegeometry % We get here if we generated the geometry file from the % recipe. if piContains(currLine, 'geometry.pbrt') [~,n] = fileparts(thisR.outputFile); currLine = sprintf('Include "%s_geometry.pbrt"',n); end end if piContains(currLine, 'WorldEnd') % We also insert a *_lights.pbrt include because we also write % out the lights file. This file might be empty, but it will % also exist. [~,n] = fileparts(thisR.outputFile); fprintf(fileID, sprintf('Include "%s_lights.pbrt" \n', n)); end fprintf(fileID,'%s \n',currLine); end else % No materials were created by ISET3d. % So we skip the 'Include *_materials.pbrt. But we still insert the % geometry and light Includes for ii = 1:length(thisR.world) currLine = thisR.world{ii}; if overwritegeometry % We get here if we generated the geometry file from the % recipe, even though we did not make any changes to the % materials. if piContains(currLine, 'geometry.pbrt') [~,n] = fileparts(thisR.outputFile); currLine = sprintf('Include "%s_geometry.pbrt"',n); end end if piContains(currLine, 'WorldEnd') % We also insert a *_lights.pbrt include because we also write % out the lights file. This file might be empty, but it will % also exist. [~,n] = fileparts(thisR.outputFile); fprintf(fileID, sprintf('Include "%s_lights.pbrt" \n', n)); end fprintf(fileID,'%s \n',currLine); end end end %% function piWriteMaterials(thisR,creatematerials,overwritematerials) % Write both materials and textures files into the output directory inDir = thisR.get('input dir'); outputDir = thisR.get('output dir'); basename = thisR.get('input basename'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to include Blender exporter if piContains(thisR.exporter, 'C4D') || piContains(thisR.exporter, 'Blender') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If the scene is from Cinema 4D, if ~creatematerials % We overwrite from the input directory, but we do not create % any new material files beyond what is already in the input if overwritematerials [~,n] = fileparts(thisR.inputFile); fname_materials = sprintf('%s_materials.pbrt',n); % thisR.materials.outputFile_materials = fullfile(outputDir,fname_materials); thisR.set('materials output file',fullfile(outputDir,fname_materials)); piMaterialWrite(thisR); end else % Create new material files that could come from somewhere % other than the input directory. [~,n] = fileparts(thisR.outputFile); fname_materials = sprintf('%s_materials.pbrt',n); thisR.set('materials output file',fullfile(outputDir,fname_materials)); % thisR.materials.outputFile_materials = fullfile(outputDir,fname_materials); piMaterialWrite(thisR); end elseif piContains(thisR.exporter,'Copy') % Copy the materials and geometry file mFileIn = fullfile(inDir,sprintf('%s_materials.pbrt',basename)); mFileOut = fullfile(outputDir,sprintf('%s_materials.pbrt',basename)); if exist(mFileIn,'file') copyfile(mFileIn,mFileOut); else % no materials file to copy end else % Other case. fprintf('Skip the materials\n'); end end %% function piWriteGeometry(thisR,overwritegeometry,lightsFlag,thistrafficflow) % Write the geometry file into the output dir % inDir = thisR.get('input dir'); outDir = thisR.get('output dir'); exporter = thisR.get('exporter'); basename = thisR.get('output basename'); % The scene's %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE: below changed % to include Blender exporter if piContains(exporter, 'C4D') || piContains(exporter, 'Blender') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if overwritegeometry piGeometryWrite(thisR,'lightsFlag',lightsFlag, ... 'thistrafficflow',thistrafficflow); end elseif piContains(exporter,'Copy') gFileIn = fullfile(inDir,sprintf('%s_geometry.pbrt',basename)); gFileOut = fullfile(outDir,sprintf('%s_geometry.pbrt',basename)); if exist(gFileIn,'file') copyfile(gFileIn,gFileOut); else % no geometry file to copy end else fprintf('Skip the geometry\n'); end end
github
ISET/iset3d-v3-master
piRead.m
.m
iset3d-v3-master/utilities/general-parser/piRead.m
18,102
utf_8
de628328ebacd9decf63a4ab20284021
function thisR = piRead(fname,varargin) % Read an parse a PBRT scene file, returning a rendering recipe % % Syntax % thisR = piRead(fname, varargin) % % Description % piREAD parses a pbrt scene file and returns the full set of rendering % information in the slots of the "recipe" object. The recipe object % contains all the information used by PBRT to render the scene. % % We extract blocks with these names from the text prior to WorldBegin % % Camera, Sampler, Film, PixelFilter, SurfaceIntegrator (V2, or % Integrator in V3), Renderer, LookAt, Transform, ConcatTransform, % Scale % % After creating the recipe from piRead, we modify the recipe % programmatically. The modified recipe is then used to write out the % PBRT file (piWrite). These PBRT files are rendered using piRender, % which executes the PBRT docker image and return an ISETCam scene or oi % format). % % We also have routines to execute these functions at scale in Google % Cloud (see isetcloud). % % Required inputs % fname - a full path to a pbrt scene file % % Optional parameter/values % 'read materials' - When PBRT scene file is exported by cinema4d, % the exporterflag is set and we read the materials file. If % you do not want to read that file, set this to false. % % Return % recipe - A recipe object with the parameters needed to write a new pbrt % scene file % % Assumptions: piRead assumes that % % * There is a block of text before WorldBegin and no more text after % * Comments (indicated by '#' in the first character) and blank lines % are ignored. % * When a block is encountered, the text lines that follow beginning % with a '"' are included in the block. % % piRead will not work with PBRT files that do not meet these criteria. % % Text starting at WorldBegin to the end of the file (not just WorldEnd) % is stored in recipe.world. % % TL, ZLy, BW Scienstanford 2017-2020 % Zhenyi, 2020 % See also % piWrite, piRender, piBlockExtract_gp % Examples: %{ thisR = piRecipeDefault('scene name','MacBethChecker'); % thisR = piRecipeDefault('scene name','SimpleScene'); % thisR = piRecipeDefault('scene name','teapot'); piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); %} %% Parse the inputs varargin =ieParamFormat(varargin); p = inputParser; p.addRequired('fname', @(x)(exist(fname,'file'))); p.addParameter('exporter', 'C4D', @ischar); p.parse(fname,varargin{:}); thisR = recipe; [~, inputname, ~] = fileparts(fname); thisR.inputFile = fname; exporter = p.Results.exporter; %% Set the default output directory outFilepath = fullfile(piRootPath,'local',inputname); outputFile = fullfile(outFilepath,[inputname,'.pbrt']); thisR.set('outputFile',outputFile); %% Split text lines into pre-WorldBegin and WorldBegin sections [txtLines, ~] = piReadText(thisR.inputFile); txtLines = strrep(txtLines, '[ "', '"'); txtLines = strrep(txtLines, '" ]', '"'); [options, world] = piReadWorldText(thisR, txtLines); %% Read options information % think about using piParameterGet; % Extract camera block thisR.camera = piParseOptions(options, 'Camera'); % Extract sampler block thisR.sampler = piParseOptions(options,'Sampler'); % Extract film block thisR.film = piParseOptions(options,'Film'); % Patch up the filmStruct to match the recipe requirements if(isfield(thisR.film,'filename')) % Remove the filename since it inteferes with the outfile name. thisR.film = rmfield(thisR.film,'filename'); end % Some PBRT files do not specify the film diagonal size. We set it to % 1mm here. try thisR.get('film diagonal'); catch disp('Setting film diagonal size to 1 mm'); thisR.set('film diagonal',1); end % Extract transform time block thisR.transformTimes = piParseOptions(options, 'TransformTimes'); % Extract surface pixel filter block thisR.filter = piParseOptions(options,'PixelFilter'); % Extract (surface) integrator block thisR.integrator = piParseOptions(options,'Integrator'); % % Extract accelerator % thisR.accelerator = piParseOptions(options,'Accelerator'); % Set thisR.lookAt and determine if we need to flip the image flip = piReadLookAt(thisR,options); % Sometimes the axis flip is "hidden" in the concatTransform matrix. In % this case, the flip flag will be true. When the flip flag is true, we % always output Scale -1 1 1. if(flip) thisR.scale = [-1 1 1]; end % Read the light sources and delete them in world thisR = piLightRead(thisR); % Read Scale, if it exists % Because PBRT is a LHS and many object models are exported with a RHS, % sometimes we stick in a Scale -1 1 1 to flip the x-axis. If this scaling % is already in the PBRT file, we want to keep it around. % fprintf('Reading scale\n'); [~, scaleBlock] = piParseOptions(options,'Scale'); if(isempty(scaleBlock)) thisR.scale = []; else values = textscan(scaleBlock, '%s %f %f %f'); thisR.scale = [values{2} values{3} values{4}]; end %% Read world information for the Include files if any(piContains(world,'Include')) && ... any(piContains(world,'_materials.pbrt')) % In this case we have an Include file for the materials. The world % should be left alone. We read the materials file to get the % materials and textures. % Find material file materialIdx = find(contains(world, '_materials.pbrt'), 1); % We get the name of the file we want to include. material_fname = erase(world{materialIdx},{'Include "','"'}); inputDir = thisR.get('inputdir'); inputFile_materials = fullfile(inputDir, material_fname); if ~exist(inputFile_materials,'file'), error('File not found'); end % We found the material file. We read it. [materialLines, ~] = piReadText(inputFile_materials); % Change to the single line format from the standard block format with % indented lines materialLinesFormatted = piFormatConvert(materialLines); % Read material and texture [materialLists, textureList] = parseMaterialTexture(materialLinesFormatted); fprintf('Read %d materials.\n', numel(materialLists)); fprintf('Read %d textures.\n', numel(textureList)); % If exporter is Copy, don't parse the geometry. if isequal(exporter, 'Copy') disp('Scene geometry will not be parsed.'); thisR.world = world; else % Read the geometry file and do the same. geometryIdx = find(contains(world, '_geometry.pbrt'), 1); geometry_fname = erase(world{geometryIdx},{'Include "','"'}); inputFile_geometry = fullfile(inputDir, geometry_fname); if ~exist(inputFile_geometry,'file'), error('File not found'); end % Could this be piReadText too? % we need to read file contents with comments fileID = fopen(inputFile_geometry); tmp = textscan(fileID,'%s','Delimiter','\n'); geometryLines = tmp{1}; fclose(fileID); % convert geometryLines into from the standard block indented format in % to the single line format. geometryLinesFormatted = piFormatConvert(geometryLines); [trees, ~] = parseGeometryText(thisR, geometryLinesFormatted,''); end else % In this case there is no Include file for the materials. They are % probably defined in the world block. We read the materials and % textures from the world block. We delete them from the block because % piWrite will create the scene_materials.pbrt file and insert an % Include scene_materials.pbrt line into the world block. inputFile_materials = []; % Read material & texture [materialLists, textureList, newWorld] = parseMaterialTexture(thisR.world); thisR.world = newWorld; fprintf('Read %d materials.\n', materialLists.Count); fprintf('Read %d textures.\n', textureList.Count); % If exporter is Copy, don't parse. if isequal(exporter, 'Copy') disp('Scene geometry will not be parsed.'); else % Read geometry [trees, parsedUntil] = parseGeometryText(thisR, thisR.world,''); if ~isempty(trees) parsedUntil(parsedUntil>numel(thisR.world))=numel(thisR.world); % remove parsed line from world thisR.world(2:parsedUntil-1)=[]; end end end thisR.materials.list = materialLists; thisR.materials.inputFile_materials = inputFile_materials; % Call material lib thisR.materials.lib = piMateriallib; thisR.textures.list = textureList; thisR.textures.inputFile_textures = inputFile_materials; if exist('trees','var') && ~isempty(trees) thisR.assets = trees.uniqueNames; else % needs to add function to read structure like this: % transform [...] / Translate/ rotate/ scale/ % material ... / NamedMaterial % shape ... disp('*** No AttributeBegin/End pair found. Set recipe.assets to empty'); end disp('***Scene parsed.') % remove this line after we become more sure that we can deal with scenes % which are not exported by C4D. thisR.exporter = 'C4D'; end %% Helper functions %% Generic text reading, omitting comments and including comments function [txtLines, header] = piReadText(fname) % Open, read, close excluding comment lines fileID = fopen(fname); tmp = textscan(fileID,'%s','Delimiter','\n','CommentStyle',{'#'}); txtLines = tmp{1}; fclose(fileID); % Include comments so we can read only the first line, really fileID = fopen(fname); tmp = textscan(fileID,'%s','Delimiter','\n'); header = tmp{1}; fclose(fileID); end %% Find the text in WorldBegin/End section function [options, world] = piReadWorldText(thisR,txtLines) % % Finds all the text lines from WorldBegin % It puts the world section into the thisR.world. % Then it removes the world section from the txtLines % % Question: Why doesn't this go to WorldEnd? We are hoping that nothing is % important after WorldEnd. In our experience, we see some files that % never even have a WorldEnd, just a World Begin. % The general parser (toply) writes out the PBRT file in a block format with % indentations. Zheng's Matlab parser (started with Cinema4D), expects the % blocks to be in a single line. % % This function converts the blocks to a single line. This function is % used a few places in piRead(). txtLines = piFormatConvert(txtLines); worldBeginIndex = 0; for ii = 1:length(txtLines) currLine = txtLines{ii}; if(piContains(currLine,'WorldBegin')) worldBeginIndex = ii; break; end end % fprintf('Through the loop\n'); if(worldBeginIndex == 0) warning('Cannot find WorldBegin.'); worldBeginIndex = ii; end % Store the text from WorldBegin to the end here world = txtLines(worldBeginIndex:end); thisR.world = world; % Store the text lines from before WorldBegin here options = txtLines(1:(worldBeginIndex-1)); end %% Build the lookAt information function [flip,thisR] = piReadLookAt(thisR,txtLines) % Reads multiple blocks to create the lookAt field and flip variable % % The lookAt is built up by reading from, to, up field and transform and % concatTransform. % % Interpreting these variables from the text can be more complicated w.r.t. % formatting. % A flag for flipping from a RHS to a LHS. flip = 0; % Get the block % [~, lookAtBlock] = piBlockExtract_gp(txtLines,'blockName','LookAt'); [~, lookAtBlock] = piParseOptions(txtLines,'LookAt'); if(isempty(lookAtBlock)) % If it is empty, use the default thisR.lookAt = struct('from',[0 0 0],'to',[0 1 0],'up',[0 0 1]); else % We have values % values = textscan(lookAtBlock{1}, '%s %f %f %f %f %f %f %f %f %f'); values = textscan(lookAtBlock, '%s %f %f %f %f %f %f %f %f %f'); from = [values{2} values{3} values{4}]; to = [values{5} values{6} values{7}]; up = [values{8} values{9} values{10}]; end % If there's a transform, we transform the LookAt. % to change [~, transformBlock] = piBlockExtract_gp(txtLines,'blockName','Transform'); if(~isempty(transformBlock)) values = textscan(transformBlock{1}, '%s [%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); values = cell2mat(values(2:end)); transform = reshape(values,[4 4]); [from,to,up,flip] = piTransform2LookAt(transform); end % If there's a concat transform, we use it to update the current camera % position. % to change [~, concatTBlock] = piBlockExtract_gp(txtLines,'blockName','ConcatTransform'); if(~isempty(concatTBlock)) values = textscan(concatTBlock{1}, '%s [%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f]'); values = cell2mat(values(2:end)); concatTransform = reshape(values,[4 4]); % Apply transform and update lookAt lookAtTransform = piLookat2Transform(from,to,up); [from,to,up,flip] = piTransform2LookAt(lookAtTransform*concatTransform); end % Warn the user if nothing was found if(isempty(transformBlock) && isempty(lookAtBlock)) warning('Cannot find "LookAt" or "Transform" in PBRT file. Returning default.'); end thisR.lookAt = struct('from',from,'to',to,'up',up); end % function [newlines] = piFormatConvert(txtLines) % % Format txtlines into a standard format. % nn=1; % nLines = numel(txtLines); % % ii=1; % tokenlist = {'A', 'C' , 'F', 'I', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T'}; % txtLines = regexprep(txtLines, '\t', ' '); % while ii <= nLines % thisLine = txtLines{ii}; % if ~isempty(thisLine) % if length(thisLine) >= length('Shape') % if any(strncmp(thisLine, tokenlist, 1)) && ... % ~strncmp(thisLine,'Include', length('Include')) && ... % ~strncmp(thisLine,'Attribute', length('Attribute')) % % It does, so this is the start % blockBegin = ii; % % Keep adding lines whose first symbol is a double quote (") % if ii == nLines % newlines{nn,1}=thisLine; % break; % end % for jj=(ii+1):nLines+1 % if jj==nLines+1 || isempty(txtLines{jj}) || ~isequal(txtLines{jj}(1),'"') % if jj==nLines+1 || isempty(txtLines{jj}) || isempty(str2num(txtLines{jj}(1:2))) ||... % any(strncmp(txtLines{jj}, tokenlist, 1)) % blockEnd = jj; % blockLines = txtLines(blockBegin:(blockEnd-1)); % texLines=blockLines{1}; % for texI = 2:numel(blockLines) % if ~strcmp(texLines(end),' ')&&~strcmp(blockLines{texI}(1),' ') % texLines = [texLines,' ',blockLines{texI}]; % else % texLines = [texLines,blockLines{texI}]; % end % end % newlines{nn,1}=texLines;nn=nn+1; % ii = jj-1; % break; % end % end % % end % else % newlines{nn,1}=thisLine; nn=nn+1; % end % end % end % ii=ii+1; % end % newlines(piContains(newlines,'Warning'))=[]; % end %% Parse several critical recipe options function [s, blockLine] = piParseOptions(txtLines, blockName) % Parse the options for a specific block % % How many lines of text? nline = numel(txtLines); s = [];ii=1; while ii<=nline blockLine = txtLines{ii}; % There is enough stuff to make it worth checking if length(blockLine) >= 5 % length('Shape') % If the blockLine matches the BlockName, do something if strncmp(blockLine, blockName, length(blockName)) s=[]; % If it is Transform, do this and then return if (strcmp(blockName,'Transform') || ... strcmp(blockName,'LookAt')|| ... strcmp(blockName,'ConcatTransform')|| ... strcmp(blockName,'Scale')) return; end % It was not Transform. So figure it out. thisLine = strrep(blockLine,'[',''); % Get rid of [ thisLine = strrep(thisLine,']',''); % Get rid of ] thisLine = textscan(thisLine,'%q'); % Find individual words into a cell array % thisLine is a cell of 1. % It contains a cell array with the individual words. thisLine = thisLine{1}; nStrings = length(thisLine); blockType = thisLine{1}; blockSubtype = thisLine{2}; s = struct('type',blockType,'subtype',blockSubtype); dd = 3; % Build a struct that will be used for representing this type % of Option (Camera, Sampler, Integrator, Film, ...) % This builds the struct and assigns the values of the % parameters while dd <= nStrings if piContains(thisLine{dd},' ') C = strsplit(thisLine{dd},' '); valueType = C{1}; valueName = C{2}; end value = thisLine{dd+1}; % Convert value depending on type if(isempty(valueType)) continue; elseif(strcmp(valueType,'string')) || strcmp(valueType,'bool') || strcmp(valueType,'spectrum') % Do nothing. elseif(strcmp(valueType,'float') || strcmp(valueType,'integer')) value = str2double(value); else error('Did not recognize value type, %s, when parsing PBRT file!',valueType); end tempStruct = struct('type',valueType,'value',value); s.(valueName) = tempStruct; dd = dd+2; end break; end end ii = ii+1; end end %% END
github
ISET/iset3d-v3-master
piPBRTReformat.m
.m
iset3d-v3-master/utilities/general-parser/piPBRTReformat.m
6,522
utf_8
81412976f053c181d95654481c780d2f
function outputFull = piPBRTReformat(fname,varargin) %% format a pbrt file from arbitrary source to standard format % % Syntax: % outputFull = piPBRTReformat(fname,varargin) % % Brief % PBRT V3 files can appear in many formats. This function uses the PBRT % docker container to read those files and write out the equivalent PBRT % file in the standard format. It does this by calling PBRT with the % 'toply' switch. So PBRT reads the existing data, converts any meshes % to ply format, and writes out the results. % % Input % fname: The full path to the filename of the PBRT scene file. % % Key/val options % outputFull: The full path to the PBRT scene file that we output % By default, this will be % outputFull = fullfile(piRootPath,'local','formatted',sceneName,sceneName.pbrt) % % Example: % piPBRTReformat(fname); % piPBRTReformat(fname,'output full',fullfile(piRootPath,'local','formatted','test','test.pbrt') % See also % % Examples: %{ fname = fullfile(piRootPath,'data','V3','SimpleScene','SimpleScene.pbrt'); formattedFname = piPBRTReformat(fname); %} %% Parse % Force to no spaces and lower case varargin = ieParamFormat(varargin); % fname can be the full file name. But it is only required that it be % found. p = inputParser; p.addRequired('fname',@(x)(exist(fname,'file'))); [inputdir,thisName,ext] = fileparts(fname); p.addParameter('outputfull',fullfile(piRootPath,'local','formatted',thisName,[thisName,ext]),@ischar); p.parse(fname,varargin{:}); outputFull = p.Results.outputfull; [outputDir, ~, ~] = fileparts(outputFull); if ~exist(outputDir,'dir') mkdir(outputDir); end % copy files from input folder to output folder piCopyFolder(inputdir, outputDir); %% convert %s mkdir mesh && cd mesh && % The Docker base command includes 'toply'. In that case, it does not % render the data, it just converts it. % basecmd = 'docker run -t --name %s --volume="%s":"%s" %s pbrt --toply %s > %s && ls'; basecmd = 'docker run -ti --name %s --volume="%s":"%s" %s /bin/bash -c "pbrt --toply %s > %s; ls mesh_*.ply"'; % The directory of the input file [volume, ~, ~] = fileparts(fname); % Which docker image we run dockerimage = 'vistalab/pbrt-v3-spectral:latest'; % Give a name to docker container dockercontainerName = ['ISET3d-',thisName,'-',num2str(randi(200))]; %% Build the command dockercmd = sprintf(basecmd, dockercontainerName, volume, volume, dockerimage, fname, [thisName, ext]); % dockercmd = sprintf(basecmd, dockercontainerName, volume, volume, dockerimage, fname, outputFull); % disp(dockercmd) %% Run the command % The variable 'result' has the formatted data. [~, result] = system(dockercmd); % Copy formatted pbrt files to local directory. cpcmd = sprintf('docker cp %s:/pbrt/pbrt-v3-spectral/build/%s %s',dockercontainerName, [thisName, ext], outputDir); [status_copy, ~ ] = system(cpcmd); if status_copy disp('No converted file found.'); end %% remove "Warning: No metadata written out." % Do this only for the main pbrt file if ~contains(outputFull,'_materials.pbrt') ||... ~contains(outputFull,'_geometry.pbrt') fileIDin = fopen(outputFull); outputFullTmp = fullfile(outputDir, [thisName, '_tmp',ext]); fileIDout = fopen(outputFullTmp, 'w'); while ~feof(fileIDin) thisline=fgets(fileIDin); if ~contains(thisline,'Warning: No metadata written out.') fprintf(fileIDout, '%s', thisline); end end fclose(fileIDin); fclose(fileIDout); movefile(outputFullTmp, outputFull); end %% % Status is good. So do stuff % find out how many ply mesh files are generated. PLYmeshFiles = textscan(result, '%s'); PLYmeshFiles = PLYmeshFiles{1}; % PLYFolder = fullfile(outputDir,'scene/PBRT/pbrt-geometry'); % % if ~exist(PLYFolder,'dir') % mkdir(PLYFolder); % end for ii = 1:numel(PLYmeshFiles) cpcmd = sprintf('docker cp %s:/pbrt/pbrt-v3-spectral/build/%s %s',dockercontainerName, PLYmeshFiles{ii}, outputDir); [status_copy, ~ ] = system(cpcmd); if status_copy % If it fails we assume that is because there is no corresponding % mesh file. So, we stop. break; end end % fprintf('Formatted file is in %s \n', outputDir); %% Either way, stop the container if it is still running. % Try to get rid of the return from this system command. rmCmd = sprintf('docker rm %s',dockercontainerName); system(rmCmd); %% % In case there are extra materials and geometry files % format scene_materials.pbrt and scene_geometry.pbrt, then save them at the % same place with scene.pbrt inputMaterialfname = fullfile(inputdir, [thisName, '_materials', ext]); outputMaterialfname = fullfile(outputDir, [thisName, '_materials', ext]); inputGeometryfname = fullfile(inputdir, [thisName, '_geometry', ext]); outputGeometryfname = fullfile(outputDir, [thisName, '_geometry', ext]); if exist(inputMaterialfname, 'file') piPBRTReformat(inputMaterialfname, 'outputfull', outputMaterialfname); end if exist(inputGeometryfname, 'file') piPBRTReformat(inputGeometryfname, 'outputfull', outputGeometryfname); end end %% piCopyFolder %{ % Changed to a utility function piCopyFolder % Should be deleted after a while. % function copyFolder(inputDir, outputDir) sources = dir(inputDir); status = true; for i=1:length(sources) if startsWith(sources(i).name(1),'.') % Skip dot-files continue; elseif sources(i).isdir && (strcmpi(sources(i).name,'spds') || strcmpi(sources(i).name,'textures')) % Copy the spds and textures directory files. status = status && copyfile(fullfile(sources(i).folder, sources(i).name), fullfile(outputDir,sources(i).name)); else % Selectively copy the files in the scene root folder [~, ~, extension] = fileparts(sources(i).name); if ~(piContains(extension,'pbrt') || piContains(extension,'zip') || piContains(extension,'json')) thisFile = fullfile(sources(i).folder, sources(i).name); fprintf('Copying %s\n',thisFile) status = status && copyfile(thisFile, fullfile(outputDir,sources(i).name)); end end end if(~status) error('Failed to copy input directory to docker working directory.'); else fprintf('Copied resources from:\n'); fprintf('%s \n',inputDir); fprintf('to \n'); fprintf('%s \n \n',outputDir); end end %}
github
ISET/iset3d-v3-master
piBlockExtract_gp.m
.m
iset3d-v3-master/utilities/general-parser/piBlockExtract_gp.m
6,600
utf_8
8e6eb9fc411c5f195a418d7243b71270
function [blockList, blockLinesList] = piBlockExtract(txtLines,varargin) % Parse text in a scene file, returning the info as a structure % % Syntax % [s, blockLines] = piBlockExtract(txtLines,varargin) % % Description % Used extensively by piRead to parse specific types of text blocks within % a PBRT scene file. % % Input % txtLines - Cell array of text lines % % Optional parameters % 'block name' - A string defining the block. In principle this can be % any string. In practice, there are several specific % types of blocks we use a lot (see below). % % 'exporter' - if true, we use piBlockExtractC4D instead since % the syntax given by the exporter is different. % % Return % blockList - a struct containing information from the block of text % blockLinesList % readSummary - Any warnings about unread sections returned here. % % Types of blocks we have tried to extract successfully, particularly with % PBRT V3 % % 'PixelFilter' % 'SurfaceIntegrator' % 'Integrator' (ver 2 'SurfaceIntegrator') % 'Renderer' % 'LookAt' % 'Transform' % 'ConcatTransform' % 'Scale' % 'Camera' % 'Film' % 'Sampler' % % TL Scienstanford 2017 % % See also % piRead, piWrite, piBlockExtractC4D %% Identify the blockname. varargin = ieParamFormat(varargin); p = inputParser; p.addRequired('txtLines',@(x)(iscell(txtLines) && ~isempty(txtLines))); % We need a valid list of potential block names here. addParameter(p,'blockname','Camera',@ischar); p.parse(txtLines,varargin{:}); blockName = p.Results.blockname; % Initialize %% Extract lines that correspond to specified keyword nLines = length(txtLines); blockList=[]; blockLinesList=[];nn=1; for ii=1:nLines thisLine = txtLines{ii}; if length(thisLine) >= length(blockName) % The line is long enough, so compare if it starts with the blockname if strncmp(thisLine,blockName,length(blockName)) % It does, so this is the start blockBegin = ii; % Keep adding lines whose first symbol is a double quote (") for jj=(ii+1):nLines if isempty(txtLines{jj}) || ~isequal(txtLines{jj}(1),'"') || jj==nLines % isempty(txtLines{jj}) % Some other character, so get out. if isempty(txtLines{jj}) || isempty(str2num(txtLines{jj}(1:2))) blockEnd = jj; blockLines = txtLines(blockBegin:(blockEnd-1)); blockLinesList{nn} = blockLines; switch blockName case {'MakeNamedMaterial','Material'} blockList{nn} = parseBlockMaterial(blockLines); case 'Texture' blockList{nn} = parseBlockTexture(texLines,ii); otherwise blockList{nn} = parseBlock(blockLines, blockName); blockLinesList{nn} = blockLines; end nn=nn+1; break; end end end end end end if numel(blockList)==1 && ... ~(strcmp(blockName, 'Texture') || ... strcmp(blockName, 'MakeNamedMaterial')) blockList = blockList{1}; blockLinesList = blockLinesList{1}; end end function s = parseBlock(blockLines, blockName) %% If it's a transform, automatically return without parsing s=[]; if(strcmp(blockName,'Transform') || ... strcmp(blockName,'LookAt')|| ... strcmp(blockName,'ConcatTransform')|| ... strcmp(blockName,'Scale')) return; end %% Go through the text block, line by line, and try to extract the parameters nLines = length(blockLines); % Get the main type/subtype of the block (e.g. Camera: pinhole or % SurfaceIntegrator: path) % TL Note: This is a pretty hacky way to do it, you can probably do the % whole thing in one line using regular expressions. C = textscan(blockLines{1},'%s'); blockType = C{1}{1}; C = regexp(blockLines{1}, '(?<=")[^"]+(?=")', 'match'); blockSubtype = C{1}; % Set the main type and subtype s = struct('type',blockType,'subtype',blockSubtype); % Get all other parameters within the block % Generally they are in the form: % "type name" [value] or "type name" "value" for ii = 2:nLines currLine = blockLines{ii}; % Find everything between quotation marks ("type name") C = regexp(currLine, '(?<=")[^"]+(?=")', 'match'); C = strsplit(C{1}); valueType = C{1}; valueName = C{2}; % Get the value corresponding to this type and name if(strcmp(valueType,'string') || strcmp(valueType,'bool')) % Find everything between quotation marks C = regexp(currLine, '(?<=")[^"]+(?=")', 'match'); value = C{3}; elseif(strcmp(valueType,'spectrum')) %{ TODO: Spectrum can either be a spectrum file "xxx.spd" or it can be a series of four numbers [wave1 wave2 value1 value2]. There might be other variations, but we should check to see if brackets exist and to read numbers instead of a string if they do. %} % Find everything between quotation marks C = regexp(currLine, '(?<=")[^"]+(?=")', 'match'); value = C{3}; elseif(strcmp(valueType,'float') || strcmp(valueType,'integer')) % Find everything between brackets value = regexp(currLine, '(?<=\[)[^)]*(?=\])', 'match', 'once'); value = str2double(value); elseif(strcmp(valueType,'rgb')) % TODO: Find three values between the brackets, e.g. [r g b] end if(isempty(value)) % Some types can potentially be % defined as a vector, string, or float. We have to be able to % catch all those cases. Take a look at the "Parameter Lists" % in this document to see a few examples: % http://www.pbrt.org/fileformat.html#parameter-lists fprintf('Value Type: %s \n',valueType); fprintf('Value Name: %s \n',valueName); fprintf('Line to parse: %s \n',currLine) error('Parser cannot find the value associated with this type. The parser is still incomplete, so we cannot yet recognize all type cases.'); end % Set this value and type as a field in the structure [s.(valueName)] = struct('value',value,'type',valueType); if isempty(s) warning('No information found for block %s\n',blockName); s = struct([]); end end end
github
ISET/iset3d-v3-master
piLightGetFromText_gp.m
.m
iset3d-v3-master/utilities/light/piLightGetFromText_gp.m
10,302
utf_8
2f5c66f6284503ca0c6994439fbceba2
function lightSources = piLightGetFromText_gp(thisR, intext, varargin) % Read a light source struct based on the parameters in the recipe % % This routine only works for light sources that are exported from % Cinema 4D. It will not work in all cases. We should fix that. % % Inputs % thisR: Recipe % intext % Optional key/val pairs % print: Printout the list of lights % % Returns % lightSources: Cell array of light source structures % % Zhenyi, SCIEN, 2019 % Zheng Lyu , 2020 % See also % piLightDeleteWorld, piLightAddToWorld % Examples %{ thisR = piRecipeDefault; lightSources = piLightGet(thisR); thisR = piLightDelete(thisR, 1); thisR = piLightAdd(thisR, 'type', 'point'); thisR = piLightAdd(thisR, 'type', 'point', 'camera coordinate', true); piLightGet(thisR); %} %% Parse inputs varargin = ieParamFormat(varargin); p = inputParser; p.addRequired('thisR', @(x)(isa(x,'recipe'))); p.addRequired('intext', @iscell); p.addParameter('printinfo',true); p.parse(thisR, intext, varargin{:}); %% Find the indices of the lines the .world slot that are a LightSource AttBegin = find(piContains(intext,'AttributeBegin')); AttEnd = find(piContains(intext,'AttributeEnd')); arealight = piContains(intext,'AreaLightSource'); light = piContains(intext,'LightSource'); lightIdx = find(light); % Find which lines have LightSource on them. %% Parse the properties of the light in each line in the lightIdx list nLights = sum(light); lightSources = cell(1, nLights); for ii = 1:nLights % % Initialize the light structure % lightSources{ii} = piLightCreate(thisR); % Find the attributes sections of the input text from the World. % if length(AttBegin) >= ii lightSources{ii}.line = intext(AttBegin(ii):AttEnd(ii)); lightSources{ii}.range = [AttBegin(ii), AttEnd(ii)]; lightSources{ii}.pos = lightIdx(ii) - AttBegin(ii) + 1; else light(arealight) = 0; lightSources{ii}.line = intext(lightIdx(ii)); lightSources{ii}.range = lightIdx(ii); end % The txt below is derived from the intext stored in the % lightSources.line slot. if find(piContains(lightSources{ii}.line, 'AreaLightSource')) lightSources{ii}.type = 'area'; txt = lightSources{ii}.line{piContains(lightSources{ii}.line, 'AreaLightSource')}; % Remove blank to avoid error txt = strrep(txt,'[ ','['); txt = strrep(txt,' ]',']'); thisLineStr = textscan(txt, '%q'); thisLineStr = thisLineStr{1}; % nsamples int = find(piContains(thisLineStr, 'integer nsamples')); if int, lightSources{ii}.nsamples = piParseNumericString(thisLineStr{int+1}); end % two sided twoside = find(piContains(thisLineStr, 'bool twosided')); if twoside if strcmp(thisLineStr{int+1}, 'false') lightSources{ii}.twosided = 0; else lightSources{ii}.twosided = 1; end end % Parse ConcatTransform concatTrans = find(piContains(lightSources{ii}.line, 'ConcatTransform')); if concatTrans [rot, position] = piParseConcatTransform(lightSources{ii}.line{concatTrans}); lightSources{ii}.rotate = rot; lightSources{ii}.position = position; end % Parse shape shp = find(piContains(lightSources{ii}.line, 'Shape')); if shp lightSources{ii}.shape = piParseShape(lightSources{ii}.line{shp}); end else % Assign type lightType = lightSources{ii}.line{piContains(lightSources{ii}.line,'LightSource')}; lightType = strsplit(lightType, ' '); lightSources{ii}.type = lightType{2}(2:end-1); % Remove the quote mark try % Zheng Lyu to have a look here % If this works, then we are C4D compatible txt = lightSources{ii}.line{piContains(lightSources{ii}.line, 'point from') |... piContains(lightSources{ii}.line, 'infinite')}; compatibility = 'C4D'; lightSources{ii}.cameracoordinate = false; catch % Exception happens when we use coordinate camera to place % the light at the from of the camera if any(piContains(lightSources{ii}.line, 'CoordSysTransform "camera"')) lightSources{ii}.cameracoordinate = true; txt = lightSources{ii}.line{piContains(lightSources{ii}.line, 'LightSource')}; compatibility = 'ISET3d'; else % We are not C4D compatible. So we do this error('Cannot interpret this file. Check for C4D and ISET3d compatibility.'); end end % Remove blank to avoid error txt = strrep(txt,'[ ','['); txt = strrep(txt,' ]',']'); % Get the string on the LightSource line thisLineStr = textscan(txt, '%q'); thisLineStr = thisLineStr{1}; % Start checking for key words about the light source if ~piContains(lightSources{ii}.type, 'infinite') switch compatibility case 'C4D' % Find the from and to. If C4D compatible, then the % number are on three consecutive. If not, we read the % from and to info from the recipe. from = find(piContains(thisLineStr, 'point from')); lightSources{ii}.from = [piParseNumericString(thisLineStr{from+1});... piParseNumericString(thisLineStr{from+2});... piParseNumericString(thisLineStr{from+3})]; to = find(piContains(thisLineStr, 'point to')); if to lightSources{ii}.to = [piParseNumericString(thisLineStr{to+1});... piParseNumericString(thisLineStr{to+2});... piParseNumericString(thisLineStr{to+3})]; end case 'ISET3d' lightSources{ii}.from = reshape(thisR.get('from'), [1, 3]); lightSources{ii}.to = reshape(thisR.get('to'), [1, 3]); end % Set the cone angle coneAngle = find(piContains(thisLineStr, 'float coneangle')); if coneAngle,lightSources{ii}.coneangle = piParseNumericString(thisLineStr{coneAngle+1}); end coneDeltaAngle = find(piContains(thisLineStr, 'float conedelataangle')); if coneDeltaAngle, lightSources{ii}.conedeltaangle = piParseNumericString(thisLineStr{coneDeltaAngle+1}); end else % Two parameters acceptable by infinite light mapname = find(piContains(thisLineStr, 'string mapname')); if mapname, lightSources{ii}.mapname = thisLineStr{mapname+1}; end int = find(piContains(thisLineStr, 'integer nsamples')); if int, lightSources{ii}.nsamples = piParseNumericString(thisLineStr{int+1}); end end end % Find common parameters % Set spectrum % Look for spectrum L/I spectrum = find(piContains(thisLineStr, 'spectrum L')+piContains(thisLineStr, 'spectrum I')); if spectrum if isnan(str2double(thisLineStr{spectrum+1})) thisSpectrum = thisLineStr{spectrum+1}; else thisSpectrum = piParseNumericString(thisLineStr{spectrum+1}); end end % Look for rgb/color L/I rgb = find(piContains(thisLineStr, 'color L') +... piContains(thisLineStr, 'rgb L')+... piContains(thisLineStr, 'color I') +... piContains(thisLineStr, 'rgb I')); if rgb if isnan(str2double(thisLineStr{rgb+1})) thisSpectrum = str2num([thisLineStr{rgb+1}, ' ',... thisLineStr{rgb+2}, ' ',... thisLineStr{rgb+3}]); else thisSpectrum = piParseNumericString([thisLineStr{rgb+1}, ' ',... thisLineStr{rgb+2}, ' ',... thisLineStr{rgb+3}]); end end % Look for blackbody L, the first parameter is the temperature in % Kelvin, and the second giving a scale factor. blk = find(piContains(thisLineStr, 'blackbody L')); if blk thisSpectrum = piParseNumericString([thisLineStr{blk+1}, ' ',... thisLineStr{blk+2}]); end if exist('thisSpectrum', 'var') lightSources{ii}.lightspectrum = thisSpectrum; end % Look up rotate rot = find(piContains(lightSources{ii}.line, 'Rotate')); if rot [~, lightSources{ii}.rotate] = piParseVector(lightSources{ii}.line(rot)); end % Look up translation trans = find(piContains(lightSources{ii}.line, 'Translate')); if trans [~, lightSources{ii}.position] = piParseVector(lightSources{ii}.line(trans)); end % Look up scale scl = find(piContains(lightSources{ii}.line, 'Scale')); if scl [~, lightSources{ii}.scale] = piParseVector(lightSources{ii}.line(scl)); end % Look up Material scl = find(piContains(lightSources{ii}.line, 'Material')); if scl matierallist = piBlockExtract_gp(lightSources{ii}.line,'blockname','Material'); lightSources{ii}.material = matierallist; end end %% Give to light for ii = 1:numel(lightSources) if ~isfield(lightSources{ii}, 'name') lightSources{ii}.name = sprintf('#%d_Light_type:%s', ii, lightSources{ii}.type); end end if p.Results.printinfo disp('---------------------') disp('*****Light Type******') for ii = 1:length(lightSources) fprintf('%d: name: %s type: %s\n', ii,lightSources{ii}.name,lightSources{ii}.type); end disp('*********************') disp('---------------------') end end %% Helper functions function val = piParseNumericString(str) str = strrep(str,'[',''); str = strrep(str,']',''); val = str2num(str); end
github
ISET/iset3d-v3-master
piLightGetFromWorld.m
.m
iset3d-v3-master/utilities/light/piLightGetFromWorld.m
8,617
utf_8
6a1a42a08c2b11ea7d4646ec0b607fe5
function lightSources = piLightGetFromWorld(thisR, varargin) % Read a light source struct based on the parameters in the recipe % % This routine only works for light sources that are exported from % Cinema 4D. It will not work in all cases. We should fix that. % % Inputs % thisR: Recipe % % Optional key/val pairs % print: Printout the list of lights % % Returns % lightSources: Cell array of light source structures % % Zhenyi, SCIEN, 2019 % Zheng Lyu , 2020 % See also % piLightDeleteWorld, piLightAddToWorld % Examples %{ thisR = piRecipeDefault; lightSources = piLightGet(thisR); thisR = piLightDelete(thisR, 1); thisR = piLightAdd(thisR, 'type', 'point'); thisR = piLightAdd(thisR, 'type', 'point', 'camera coordinate', true); piLightGet(thisR); %} %% Parse inputs varargin = ieParamFormat(varargin); p = inputParser; p.addRequired('recipe', @(x)(isa(x,'recipe'))); p.addParameter('print',true); p.parse(thisR, varargin{:}); %% Find the indices of the lines the .world slot that are a LightSource AttBegin = find(piContains(thisR.world,'AttributeBegin')); AttEnd = find(piContains(thisR.world,'AttributeEnd')); arealight = piContains(thisR.world,'AreaLightSource'); light = piContains(thisR.world,'LightSource'); lightIdx = find(light); % Find which lines have LightSource on them. %% Parse the properties of the light in each line in the lightIdx list nLights = sum(light); lightSources = cell(1, nLights); for ii = 1:nLights % % Initialize the light structure % lightSources{ii} = piLightCreae(thisR); % Find the attributes sections of the world text if length(AttBegin) >= ii lightSources{ii}.line = thisR.world(AttBegin(ii):AttEnd(ii)); lightSources{ii}.range = [AttBegin(ii), AttEnd(ii)]; lightSources{ii}.pos = lightIdx(ii) - AttBegin(ii) + 1; else light(arealight) = 0; lightSources{ii}.line = thisR.world(lightIdx(ii)); lightSources{ii}.range = lightIdx(ii); end if find(piContains(lightSources{ii}.line, 'AreaLightSource')) lightSources{ii}.type = 'area'; txt = lightSources{ii}.line{piContains(lightSources{ii}.line, 'AreaLightSource')}; % Remove blank to avoid error txt = strrep(txt,'[ ','['); txt = strrep(txt,' ]',']'); thisLineStr = textscan(txt, '%q'); thisLineStr = thisLineStr{1}; % nsamples int = find(piContains(thisLineStr, 'integer nsamples')); if int, lightSources{ii}.nsamples = piParseNumericString(thisLineStr{int+1}); end % two sided twoside = find(piContains(thisLineStr, 'bool twosided')); if twoside if strcmp(thisLineStr{int+1}, 'false') lightSources{ii}.twosided = 0; else lightSources{ii}.twosided = 1; end end else % Assign type lightType = lightSources{ii}.line{piContains(lightSources{ii}.line,'LightSource')}; lightType = strsplit(lightType, ' '); lightSources{ii}.type = lightType{2}(2:end-1); % Remove the quote mark try % Zheng Lyu to have a look here % If this works, then we are C4D compatible txt = lightSources{ii}.line{piContains(lightSources{ii}.line, 'point from') |... piContains(lightSources{ii}.line, 'infinite')}; compatibility = 'C4D'; lightSources{ii}.cameracoordinate = false; catch % Exception happens when we use coordinate camera to place % the light at the from of the camera if any(piContains(lightSources{ii}.line, 'CoordSysTransform "camera"')) lightSources{ii}.cameracoordinate = true; txt = lightSources{ii}.line{piContains(lightSources{ii}.line, 'LightSource')}; compatibility = 'ISET3d'; else % We are not C4D compatible. So we do this error('Cannot interpret this file. Check for C4D and ISET3d compatibility.'); end end % Remove blank to avoid error txt = strrep(txt,'[ ','['); txt = strrep(txt,' ]',']'); % Get the string on the LightSource line thisLineStr = textscan(txt, '%q'); thisLineStr = thisLineStr{1}; if ~piContains(lightSources{ii}.type, 'infinite') switch compatibility case 'C4D' % Find the from and to. If C4D compatible, then the % number are on three consecutive. If not, we read the % from and to info from the recipe. from = find(piContains(thisLineStr, 'point from')); lightSources{ii}.from = [piParseNumericString(thisLineStr{from+1});... piParseNumericString(thisLineStr{from+2});... piParseNumericString(thisLineStr{from+3})]; to = find(piContains(thisLineStr, 'point to')); if to lightSources{ii}.to = [piParseNumericString(thisLineStr{to+1});... piParseNumericString(thisLineStr{to+2});... piParseNumericString(thisLineStr{to+3})]; end case 'ISET3d' lightSources{ii}.from = reshape(thisR.get('from'), [1, 3]); lightSources{ii}.to = reshape(thisR.get('to'), [1, 3]); end % Set the cone angle coneAngle = find(piContains(thisLineStr, 'float coneangle')); if coneAngle,lightSources{ii}.coneangle = piParseNumericString(thisLineStr{coneAngle+1}); end coneDeltaAngle = find(piContains(thisLineStr, 'float conedelataangle')); if coneDeltaAngle, lightSources{ii}.conedeltaangle = piParseNumericString(thisLineStr{coneDeltaAngle+1}); end else % Two parameters acceptable by infinite light mapname = find(piContains(thisLineStr, 'string mapname')); if mapname, lightSources{ii}.mapname = thisLineStr{mapname+1}; end int = find(piContains(thisLineStr, 'integer nsamples')); if int, lightSources{ii}.nsamples = piParseNumericString(thisLineStr{int+1}); end end end % Set spectrum % Look for spectrum L/I spectrum = find(piContains(thisLineStr, 'spectrum L')+piContains(thisLineStr, 'spectrum I')); if spectrum if isnan(str2double(thisLineStr{spectrum+1})) thisSpectrum = thisLineStr{spectrum+1}; else thisSpectrum = piParseNumericString(thisLineStr{spectrum+1}); end end % Look for rgb/color L/I rgb = find(piContains(thisLineStr, 'color L') +... piContains(thisLineStr, 'rgb L')+... piContains(thisLineStr, 'color I') +... piContains(thisLineStr, 'rgb I')); if rgb if isnan(str2double(thisLineStr{rgb+1})) thisSpectrum = str2num([thisLineStr{rgb+1}, ' ',... thisLineStr{rgb+2}, ' ',... thisLineStr{rgb+3}]); else thisSpectrum = piParseNumericString([thisLineStr{rgb+1}, ' ',... thisLineStr{rgb+2}, ' ',... thisLineStr{rgb+3}]); end end % Look for blackbody L, the first parameter is the temperature in % Kelvin, and the second giving a scale factor. blk = find(piContains(thisLineStr, 'blackbody L')); if blk thisSpectrum = piParseNumericString([thisLineStr{blk+1}, ' ',... thisLineStr{blk+2}]); end if exist('thisSpectrum', 'var') lightSources{ii}.lightspectrum = thisSpectrum; end end if p.Results.print disp('---------------------') disp('*****Light Type******') for ii = 1:length(lightSources) fprintf('%d: name: %s type: %s\n', ii,lightSources{ii}.name,lightSources{ii}.type); end disp('*********************') disp('---------------------') end end %% Helper functions function val = piParseNumericString(str) str = strrep(str,'[',''); str = strrep(str,']',''); val = str2num(str); end
github
ISET/iset3d-v3-master
propertiesGUI.m
.m
iset3d-v3-master/external/propertiesGUI.m
69,330
utf_8
039cb42cf37eaa3a80a1e890e829f1f3
function [hPropsPane,parameters] = propertiesGUI(hParent, parameters, filename, selectedBranch) % propertiesGUI displays formatted editable list of properties % % Syntax: % % Initialization: % [hPropsPane,parameters] = propertiesGUI(hParent, parameters) % % Run-time interaction: % propertiesGUI(hPropsPane, mode, filename, branch) % % Description: % propertiesGUI processes a list of data properties and displays % them in a GUI table, where each parameter value has a unique % associated editor. % % propertiesGUI by itself, with no input parameters, displays a demo % % By default, propertiesGUI identifies and processes the following % field types: signed, unsigned, float, file, folder, text or string, % color, IPAddress, password, date, boolean, cell-array, numeric array, % font, struct and class object. % % Inputs: % Initialization (up to 2 inputs) % % hParent - optional handle of a parent GUI container (figure/uipanel % /uitab) in which the properties table will appear. % If missing or empty or 0, the table will be shown in a % new modal dialog window; otherwise it will be embedded % in the parent container. % % parameters - struct or object with data fields. The fields are % processed separately to determine their corresponding cell % editor. If parameters is not specified, then the global % test_data will be used. If test_data is also empty, then % a demo of several different data types will be used. % % Run-time interactions (4 inputs) % % hPropsPane - handle to the properties panel width (see output below) % % mode - char string, 'save' or 'load' to indicate the operation mode % to save data or load % % filename - char string of the filename to be saved. Can be full path % or relative. % % branch - char string to the branch to be saved or loaded. If it is a % sub branch then the items are to be delimited by '.' % If branch is empty -> then the full tree data is saved/loaded. % % Outputs: % hPropsPane - handle of the properties panel widget, which can be % customized to display field descriptions, toolbar, etc. % % parameters - the resulting (possibly-updated) parameters struct. % Naturally, this is only relevant in case of a modal dialog. % % (global test_data) - this global variable is updated internally when % the <OK> button is clicked. It is meant to enable easy data % passing between the properties GUI and other application % component. Using global vars is generally discouraged as % bad programming, but it simplifies component interaction. % % Customization: % This utility is meant to be used either as stand-alone, or as a % template for customization. For example, you can attach a unique % description to each property that will be shown in an internal % sub-panel: see the customizePropertyPane() and preparePropsList() % sub-functions. % % When passing the properties in an input parameters struct, the % utility automatically inspects each struct field and assigns a % corresponding cell-editor with no description and a field label % that reflects the field name. The properties are automatically % set as modifiable (editable) and assigned a default callback % function (propUpdatedCallback() sub-function). % See the demoParameters() sub-function for some examples. % % You can have specific control over each property's description, % label, editability, cell-editor and callback function. See the % preparePropsList() sub-functions for some examples. You can add % additional cell-editors/renderers in the newProperty() sub-function. % % You can place specific control over the acceptable property values % by entering custom code into the checkProp() sub-function. % % Future development: % 1. Improve the editor for time, numeric and cell arrays % 2. Enable more control over appearance and functionality via % propertiesGUI's input parameters % 3. Add additional built-in cell editors/renderers: slider, point, % rectangle (=position), ... % % Example: % propertiesGUI; % displays the demo % % params.name = 'Yair'; % params.age = uint8(41); % params.folder = pwd; % params.date = now; % params.size.width = 10; % params.size.height = 20; % [hPropsPane, params] = propertiesGUI(params); % % % runtime interation: % propertiesGUI(hPropsPane, 'save', 'width.mat', 'size.width'); % propertiesGUI(hPropsPane, 'load', 'width.mat', 'size.width'); % % Bugs and suggestions: % Please send to Yair Altman (altmany at gmail dot com) % % Warning: % This code heavily relies on undocumented and unsupported Matlab % functionality. It works on Matlab 7+, but use at your own risk! % % A technical description of the implementation can be found at: % http://undocumentedmatlab.com/blog/propertiesGUI % http://undocumentedmatlab.com/blog/jide-property-grids % http://undocumentedmatlab.com/blog/advanced-jide-property-grids % % Change log: % 2015-03-12: Fixes for R2014b; added support for matrix data, data save/load, feedback links % 2013-12-24: Fixes for R2013b & R2014a; added support for Font property % 2013-04-23: Handled multi-dimensional arrays % 2013-04-23: Fixed case of empty ([]) data, handled class objects & numeric/cell arrays, fixed error reported by Andrew Ness % 2013-01-26: Updated help section % 2012-11-07: Minor fix for file/folder properties % 2012-11-07: Accept any object having properties/fields as input parameter; support multi-level properties % 2012-10-31: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a> % % See also: % inspect, uiinspect (#17935 on the MathWorks File Exchange) % License to use and modify this code is granted freely to all interested, as long as the original author is % referenced and attributed as such. The original author maintains the right to be solely associated with this work. % Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com % $Revision: 1.15 $ $Date: 2015/03/12 12:37:46 $ % Get the initial data global test_data isDemo = false; if nargin < 2 try isObj = nargin==1; [hasProps,isHG] = hasProperties(hParent); isObj = isObj && hasProps && ~isHG; catch % ignore - maybe nargin==0, so no hParent is available end if isObj parameters = hParent; hParent = []; else parameters = test_data; % comment this if you do not want persistent parameters if isempty(parameters) % demo mode parameters = demoParameters; end isDemo = true; end elseif nargin == 4 % check if load or save mode mode = parameters; if ischar(mode) && ischar(filename) && (ischar(selectedBranch) || iscell(selectedBranch)) hParent = handle(hParent); hFig = ancestor(hParent,'figure'); %mirrorData = getappdata(hFig, 'mirror'); hgrid = getappdata(hFig, 'hgrid'); if strcmp(mode,'load') && isempty(selectedBranch) parameters = load(filename, '-mat'); container = hParent.Parent; delete(hParent) hPropsPane = propertiesGUI(container,parameters); else fileIO_Callback(hgrid, selectedBranch, mode, hFig, filename) end else error('propertiesGUI:incorrectUsage', 'Incorrect input parameters in input'); end return end % Accept any object having data fields/properties try parameters = get(parameters); catch oldWarn = warning('off','MATLAB:structOnObject'); parameters = struct(parameters); warning(oldWarn); end % Init JIDE com.mathworks.mwswing.MJUtilities.initJIDE; % Prepare the list of properties oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty'); warning off MATLAB:hg:PossibleDeprecatedJavaSetHGProperty isEditable = true; %=nargin < 1; propsList = preparePropsList(parameters, isEditable); % Create a mapping propName => prop propsHash = java.util.Hashtable; propsArray = propsList.toArray(); for propsIdx = 1 : length(propsArray) thisProp = propsArray(propsIdx); propName = getPropName(thisProp); propsHash.put(propName, thisProp); end warning(oldWarn); % Prepare a properties table that contains the list of properties model = javaObjectEDT(com.jidesoft.grid.PropertyTableModel(propsList)); model.expandAll(); % Prepare the properties table (grid) grid = javaObjectEDT(com.jidesoft.grid.PropertyTable(model)); grid.setShowNonEditable(grid.SHOW_NONEDITABLE_BOTH_NAME_VALUE); %set(handle(grid.getSelectionModel,'CallbackProperties'), 'ValueChangedCallback', @propSelectedCallback); com.jidesoft.grid.TableUtils.autoResizeAllColumns(grid); %com.jidesoft.grid.TableUtils.autoResizeAllRows(grid); grid.setRowHeight(19); % default=16; autoResizeAllRows=20 - we need something in between % Auto-end editing upon focus loss grid.putClientProperty('terminateEditOnFocusLost',true); % If no parent (or the root) was specified if nargin < 1 || isempty(hParent) || isequal(hParent,0) % Create a new figure window delete(findall(0, '-depth',1, 'Tag','fpropertiesGUI')); hFig = figure('NumberTitle','off', 'Name','Application properties', 'Units','pixel', 'Pos',[300,200,500,500], 'Menu','none', 'Toolbar','none', 'Tag','fpropertiesGUI', 'Visible','off'); hParent = hFig; setappdata(0,'isParamsGUIApproved',false) % Add the bottom action buttons btOK = uicontrol('String','OK', 'Units','pixel', 'Pos',[ 20,5,60,30], 'Tag','btOK', 'Callback',@btOK_Callback); btCancel = uicontrol('String','Cancel', 'Units','pixel', 'Pos',[100,5,60,30], 'Tag','btCancel', 'Callback',@(h,e)close(hFig)); %#ok<NASGU> % Add the rating link (demo mode only) if isDemo cursor = java.awt.Cursor(java.awt.Cursor.HAND_CURSOR); blogLabel = javax.swing.JLabel('<html><center>Additional interesting stuff at<br/><b><a href="">UndocumentedMatlab.com'); set(handle(blogLabel,'CallbackProperties'), 'MouseClickedCallback', 'web(''http://UndocumentedMatlab.com'',''-browser'');'); blogLabel.setCursor(cursor); javacomponent(blogLabel, [200,5,170,30], hFig); url = 'http://www.mathworks.com/matlabcentral/fileexchange/38864-propertiesgui'; rateLabel = javax.swing.JLabel('<html><center><b><a href="">Feedback / rating for this utility'); set(handle(rateLabel,'CallbackProperties'), 'MouseClickedCallback', ['web(''' url ''',''-browser'');']); rateLabel.setCursor(cursor); javacomponent(rateLabel, [380,5,110,30], hFig); end % Check the property values to determine whether the <OK> button should be enabled or not checkProps(propsList, btOK, true); % Set the figure icon & make visible jFrame = get(handle(hFig),'JavaFrame'); icon = javax.swing.ImageIcon(fullfile(matlabroot, '/toolbox/matlab/icons/tool_legend.gif')); jFrame.setFigureIcon(icon); set(hFig, 'WindowStyle','modal', 'Visible','on'); % Set the component's position %pos = [5,40,490,440]; hFigPos = getpixelposition(hFig); pos = [5,40,hFigPos(3)-10,hFigPos(4)-50]; wasFigCreated = true; else % Set the component's position drawnow; pos = getpixelposition(hParent); pos(1:2) = 5; pos = pos - [0,0,10,10]; hFig = ancestor(hParent,'figure'); wasFigCreated = false; % Clear the parent container if isequal(hFig,hParent) clf(hFig); else delete(allchild(hParent)); end end %drawnow; pause(0.05); pane = javaObjectEDT(com.jidesoft.grid.PropertyPane(grid)); customizePropertyPane(pane); [jPropsPane, hPropsPane_] = javacomponent(pane, pos, hParent); % A callback for touching the mouse hgrid = handle(grid, 'CallbackProperties'); set(hgrid, 'MousePressedCallback', {@MousePressedCallback, hFig}); setappdata(hFig, 'jPropsPane',jPropsPane); setappdata(hFig, 'propsList',propsList); setappdata(hFig, 'propsHash',propsHash); setappdata(hFig, 'mirror',parameters); setappdata(hFig, 'hgrid',hgrid); set(hPropsPane_,'tag','hpropertiesGUI'); set(hPropsPane_, 'Units','norm'); % Align the background colors bgcolor = pane.getBackground.getComponents([]); try set(hParent, 'Color', bgcolor(1:3)); catch, end % this fails in uitabs - never mind (works ok in stand-alone figures) try pane.setBorderColor(pane.getBackground); catch, end % error reported by Andrew Ness % If a new figure was created, make it modal and wait for user to close it if wasFigCreated uiwait(hFig); if getappdata(0,'isParamsGUIApproved') parameters = test_data; %=getappdata(hFig, 'mirror'); end end if nargout, hPropsPane = hPropsPane_; end % prevent unintentional printouts to the command window end % propertiesGUI % Mouse-click callback function function MousePressedCallback(grid, eventdata, hFig) % Get the clicked location %grid = eventdata.getSource; %columnModel = grid.getColumnModel; %leftColumn = columnModel.getColumn(0); clickX = eventdata.getX; clickY = eventdata.getY; %rowIdx = grid.getSelectedRow + 1; if clickX <= 20 %leftColumn.getWidth % clicked the side-bar return %elseif grid.getSelectedColumn==0 % didn't press on the value (second column) % return end % bail-out if right-click if eventdata.isMetaDown showGridContextMenu(hFig, grid, clickX, clickY); else % bail-out if the grid is disabled if ~grid.isEnabled, return; end %data = getappdata(hFig, 'mirror'); selectedProp = grid.getSelectedProperty; % which property (java object) was selected if ~isempty(selectedProp) if ismember('arrayData',fieldnames(get(selectedProp))) % Get the current data and update it actualData = get(selectedProp,'ArrayData'); updateDataInPopupTable(selectedProp.getName, actualData, hFig, selectedProp); end end end end %Mouse pressed % Update data in a popup table function updateDataInPopupTable(titleStr, data, hGridFig, selectedProp) figTitleStr = [char(titleStr) ' data']; hFig = findall(0, '-depth',1, 'Name',figTitleStr); if isempty(hFig) hFig = figure('NumberTitle','off', 'Name',figTitleStr, 'Menubar','none', 'Toolbar','none'); else figure(hFig); % bring into focus end try mtable = createTable(hFig, [], data); set(mtable,'DataChangedCallback',{@tableDataUpdatedCallback,hGridFig,selectedProp}); %uiwait(hFig) % modality catch delete(hFig); errMsg = {'Editing this data requires Yair Altman''s Java-based data table (createTable) utility from the Matlab File Exchange.', ... ' ', 'If you have already downloaded and unzipped createTable, then please ensure that it is on the Matlab path.'}; uiwait(msgbox(errMsg,'Error','warn')); web('http://www.mathworks.com/matlabcentral/fileexchange/14225-java-based-data-table'); end end % updateDataInPopupTable % User updated the data in the popup table function tableDataUpdatedCallback(mtable,eventData,hFig,selectedProp) %#ok<INUSL> % Get the latest data updatedData = cell(mtable.Data); try if ~iscellstr(updatedData) updatedData = cell2mat(updatedData); end catch % probably hetrogeneous data end propName = getRecursivePropName(selectedProp); % get the property name set(selectedProp,'ArrayData',updatedData); % update the appdata of the % specific property containing the actual information of the array %% Update the displayed value in the properties GUI dataClass = class(updatedData); value = regexprep(sprintf('%dx',size(updatedData)),{'^(.)','x$'},{'<$1',['> ' dataClass ' array']}); % set(selectProp,'value',value); selectedProp.setValue(value); % update the table % Update the display propsList = getappdata(hFig, 'propsList'); checkProps(propsList, hFig); % Refresh the GUI propsPane = getappdata(hFig, 'jPropsPane'); try propsPane.repaint; catch; end % Update the local mirror data = getappdata(hFig, 'mirror'); eval(['data.' propName ' = updatedData;']); setappdata(hFig, 'mirror',data); end % tableDataUpdatedCallback % Determine whether a specified object should be considered as having fields/properties % Note: HG handles must be processed seperately for the main logic to work function [hasProps,isHG] = hasProperties(object) % A bunch of tests, some of which may croak depending on the Matlab release, platform try isHG = ishghandle(object); catch, isHG = ishandle(object); end try isst = isstruct(object); catch, isst = false; end try isjav = isjava(object); catch, isjav = false; end try isobj = isobject(object); catch, isobj = false; end try isco = iscom(object); catch, isco = false; end hasProps = ~isempty(object) && (isst || isjav || isobj || isco); end % Customize the property-pane's appearance function customizePropertyPane(pane) pane.setShowDescription(false); % YMA: we don't currently have textual descriptions of the parameters, so no use showing an empty box that just takes up GUI space... pane.setShowToolBar(false); pane.setOrder(2); % uncategorized, unsorted - see http://undocumentedmatlab.com/blog/advanced-jide-property-grids/#comment-42057 end % Prepare a list of some parameters for demo mode function parameters = demoParameters parameters.floating_point_property = pi; parameters.signed_integer_property = int16(12); parameters.unsigned_integer_property = uint16(12); parameters.flag_property = true; parameters.file_property = mfilename('fullpath'); parameters.folder_property = pwd; parameters.text_property = 'Sample text'; parameters.fixed_choice_property = {'Yes','No','Maybe', 'No'}; parameters.editable_choice_property = {'Yes','No','Maybe','', {3}}; % editable if the last cell element is '' parameters.date_property = java.util.Date; % today's date parameters.another_date_property = now-365; % last year parameters.time_property = datestr(now,'HH:MM:SS'); parameters.password_property = '*****'; parameters.IP_address_property = '10.20.30.40'; parameters.my_category.width = 4; parameters.my_category.height = 3; parameters.my_category.and_a_subcategory.is_OK = true; parameters.numeric_array_property = [11,12,13,14]; parameters.numeric_matrix = magic(5); parameters.logical_matrix = true(2,5); parameters.mixed_data_matrix = {true,'abc',pi,uint8(123); false,'def',-pi,uint8(64)}; parameters.cell_array_property = {1,magic(3),'text',-4}; parameters.color_property = [0.4,0.5,0.6]; parameters.another_color_property = java.awt.Color.red; parameters.font_property = java.awt.Font('Arial', java.awt.Font.BOLD, 12); try parameters.class_object_property = matlab.desktop.editor.getActive; catch, end end % demoParameters % Prepare a list of properties function propsList = preparePropsList(parameters, isEditable) propsList = java.util.ArrayList(); % Convert a class object into a struct if isobject(parameters) parameters = struct(parameters); end % Check for an array of inputs (currently unsupported) %if numel(parameters) > 1, error('YMA:propertiesGUI:ArrayParameters','Non-scalar inputs are currently unsupported'); end % Prepare a dynamic list of properties, based on the struct fields if isstruct(parameters) && ~isempty(parameters) %allParameters = parameters(:); % convert ND array => 3D array allParameters = reshape(parameters, size(parameters,1),size(parameters,2),[]); numParameters = numel(allParameters); if numParameters > 1 for zIdx = 1 : size(allParameters,3) for colIdx = 1 : size(allParameters,2) for rowIdx = 1 : size(allParameters,1) parameters = allParameters(rowIdx,colIdx,zIdx); field_name = ''; field_label = sprintf('(%d,%d,%d)',rowIdx,colIdx,zIdx); field_label = regexprep(field_label,',1\)',')'); % remove 3D if unnecesary newProp = newProperty(parameters, field_name, field_label, isEditable, '', '', @propUpdatedCallback); propsList.add(newProp); end end end else % Dynamically (generically) inspect all the fields and assign corresponding props field_names = fieldnames(parameters); for field_idx = 1 : length(field_names) arrayData = []; field_name = field_names{field_idx}; value = parameters.(field_name); field_label = getFieldLabel(field_name); %if numParameters > 1, field_label = [field_label '(' num2str(parametersIdx) ')']; end field_description = ''; % TODO type = 'string'; if isempty(value) type = 'string'; % not really needed, but for consistency elseif isa(value,'java.awt.Color') type = 'color'; elseif isa(value,'java.awt.Font') type = 'font'; elseif isnumeric(value) try %if length(value)==3 colorComponents = num2cell(value); if numel(colorComponents) ~= 3 error(' '); % bail out if definitely not a color end try value = java.awt.Color(colorComponents{:}); % value between 0-1 catch colorComponents = num2cell(value/255); value = java.awt.Color(colorComponents{:}); % value between 0-255 end type = 'color'; catch %else if numel(value)==1 %value = value(1); if value > now-3650 && value < now+3650 type = 'date'; value = java.util.Date(datestr(value)); elseif isa(value,'uint') || isa(value,'uint8') || isa(value,'uint16') || isa(value,'uint32') || isa(value,'uint64') type = 'unsigned'; elseif isinteger(value) type = 'signed'; else type = 'float'; end else % a vector or a matrix arrayData = value; value = regexprep(sprintf('%dx',size(value)),{'^(.)','x$'},{'<$1','> numeric array'}); %{ value = num2str(value); if size(value,1) > size(value,2) value = value'; end if size(squeeze(value),2) > 1 % Convert multi-row string into a single-row string value = [value'; repmat(' ',1,size(value,1))]; value = value(:)'; end value = strtrim(regexprep(value,' +',' ')); if length(value) > 50 value(51:end) = ''; value = [value '...']; %#ok<AGROW> end value = ['[ ' value ' ]']; %#ok<AGROW> %} end end elseif islogical(value) if numel(value)==1 % a single value type = 'boolean'; else % an array of boolean values arrayData = value; value = regexprep(sprintf('%dx',size(value)),{'^(.)','x$'},{'<$1','> logical array'}); end elseif ischar(value) if exist(value,'dir') type = 'folder'; value = java.io.File(value); elseif exist(value,'file') type = 'file'; value = java.io.File(value); elseif value(1)=='*' type = 'password'; elseif sum(value=='.')==3 type = 'IPAddress'; else type = 'string'; if length(value) > 50 value(51:end) = ''; value = [value '...']; %#ok<AGROW> end end elseif iscell(value) type = value; % editable if the last cell element is '' if size(value,1)==1 || size(value,2)==1 % vector - treat as a drop-down (combo-box/popup) of values if ~iscellstr(value) type = value; for ii=1:length(value) if isnumeric(value{ii}) % if item is numeric -> change to string for display. type{ii} = num2str(value{ii}); else type{ii} = value{ii}; end end end else % Matrix - use table popup %value = ['{ ' strtrim(regexprep(evalc('disp(value)'),' +',' ')) ' }']; arrayData = value; value = regexprep(sprintf('%dx',size(value)),{'^(.)','x$'},{'<$1','> cell array'}); end elseif isa(value,'java.util.Date') type = 'date'; elseif isa(value,'java.io.File') if value.isFile type = 'file'; else % value.isDirectory type = 'folder'; end elseif isobject(value) oldWarn = warning('off','MATLAB:structOnObject'); value = struct(value); warning(oldWarn); elseif ~isstruct(value) value = strtrim(regexprep(evalc('disp(value)'),' +',' ')); end parameters.(field_name) = value; % possibly updated above newProp = newProperty(parameters, field_name, field_label, isEditable, type, field_description, @propUpdatedCallback); propsList.add(newProp); % Save the array as a new property of the object if ~isempty(arrayData) try set(newProp,'arrayData',arrayData) catch %setappdata(hProp,'UserData',propName) hp = schema.prop(handle(newProp),'arrayData','mxArray'); %#ok<NASGU> set(handle(newProp),'arrayData',arrayData) end newProp.setEditable(false); end end end else % You can also use direct assignments, instead of the generic code above. For example: % (Possible property types: signed, unsigned, float, file, folder, text or string, color, IPAddress, password, date, boolean, cell-array of strings) propsList.add(newProperty(parameters, 'flag_prop_name', 'Flag value:', isEditable, 'boolean', 'Turn this on if you want to make extra plots', @propUpdatedCallback)); propsList.add(newProperty(parameters, 'float_prop_name', 'Boolean prop', isEditable, 'float', 'description 123...', @propUpdatedCallback)); propsList.add(newProperty(parameters, 'string_prop_name', 'My text msg:', isEditable, 'string', 'Yaba daba doo', @propUpdatedCallback)); propsList.add(newProperty(parameters, 'int_prop_name', 'Now an integer', isEditable, 'unsigned', '123 456...', @propUpdatedCallback)); propsList.add(newProperty(parameters, 'choice_prop_name', 'And a drop-down', isEditable, {'Yes','No','Maybe'}, 'no description here!', @propUpdatedCallback)); end end % preparePropsList % Get a normalized field label (see also checkFieldName() below) function field_label = getFieldLabel(field_name) field_label = regexprep(field_name, '__(.*)', ' ($1)'); field_label = strrep(field_label,'_',' '); field_label(1) = upper(field_label(1)); end % Prepare a data property function prop = newProperty(dataStruct, propName, label, isEditable, dataType, description, propUpdatedCallback) % Auto-generate the label from the property name, if the label was not specified if isempty(label) label = getFieldLabel(propName); end % Create a new property with the chosen label prop = javaObjectEDT(com.jidesoft.grid.DefaultProperty); % UNDOCUMENTED internal MATLAB component prop.setName(label); prop.setExpanded(true); % Set the property to the current patient's data value try thisProp = dataStruct.(propName); catch thisProp = dataStruct; end origProp = thisProp; if isstruct(thisProp) %hasProperties(thisProp) % Accept any object having data fields/properties try thisProp = get(thisProp); catch oldWarn = warning('off','MATLAB:structOnObject'); thisProp = struct(thisProp); warning(oldWarn); end % Parse the children props and add them to this property %summary = regexprep(evalc('disp(thisProp)'),' +',' '); %prop.setValue(summary); % TODO: display summary dynamically if numel(thisProp) < 2 prop.setValue(''); else sz = size(thisProp); szStr = regexprep(num2str(sz),' +','x'); prop.setValue(['[' szStr ' struct array]']); end prop.setEditable(false); children = toArray(preparePropsList(thisProp, isEditable)); for childIdx = 1 : length(children) prop.addChild(children(childIdx)); end else prop.setValue(thisProp); prop.setEditable(isEditable); end % Set property editor, renderer and alignment if iscell(dataType) % treat this as drop-down values % Set the defaults firstIndex = 1; cbIsEditable = false; % Extract out the number of items in the user list nItems = length(dataType); % Check for any empty items emptyItem = find(cellfun('isempty', dataType) == 1); % If only 1 empty item found check editable rules if length(emptyItem) == 1 % If at the end - then remove it and set editable flag if emptyItem == nItems cbIsEditable = true; dataType(end) = []; % remove from the drop-down list elseif emptyItem == nItems - 1 cbIsEditable = true; dataType(end-1) = []; % remove from the drop-down list end end % Try to find the initial (default) drop-down index if ~isempty(dataType) if iscell(dataType{end}) if isnumeric(dataType{end}{1}) firstIndex = dataType{end}{1}; dataType(end) = []; % remove the [] from drop-down list end else try if ismember(dataType{end}, dataType(1:end-1)) firstIndex = find(strcmp(dataType(1:end-1),dataType{end})); dataType(end) = []; end catch % ignore - possibly mixed data end end % Build the editor editor = com.jidesoft.grid.ListComboBoxCellEditor(dataType); try editor.getComboBox.setEditable(cbIsEditable); catch, end % #ok<NOCOM> %set(editor,'EditingStoppedCallback',{@propUpdatedCallback,tagName,propName}); alignProp(prop, editor); try prop.setValue(origProp{firstIndex}); catch, end end else switch lower(dataType) case 'signed', %alignProp(prop, com.jidesoft.grid.IntegerCellEditor, 'int32'); model = javax.swing.SpinnerNumberModel(prop.getValue, -intmax, intmax, 1); editor = com.jidesoft.grid.SpinnerCellEditor(model); alignProp(prop, editor, 'int32'); case 'unsigned', %alignProp(prop, com.jidesoft.grid.IntegerCellEditor, 'uint32'); val = max(0, min(prop.getValue, intmax)); model = javax.swing.SpinnerNumberModel(val, 0, intmax, 1); editor = com.jidesoft.grid.SpinnerCellEditor(model); alignProp(prop, editor, 'uint32'); case 'float', %alignProp(prop, com.jidesoft.grid.CalculatorCellEditor, 'double'); % DoubleCellEditor alignProp(prop, com.jidesoft.grid.DoubleCellEditor, 'double'); case 'boolean', alignProp(prop, com.jidesoft.grid.BooleanCheckBoxCellEditor, 'logical'); case 'folder', alignProp(prop, com.jidesoft.grid.FolderCellEditor); case 'file', alignProp(prop, com.jidesoft.grid.FileCellEditor); case 'ipaddress', alignProp(prop, com.jidesoft.grid.IPAddressCellEditor); case 'password', alignProp(prop, com.jidesoft.grid.PasswordCellEditor); case 'color', alignProp(prop, com.jidesoft.grid.ColorCellEditor); case 'font', alignProp(prop, com.jidesoft.grid.FontCellEditor); case 'text', alignProp(prop); case 'time', alignProp(prop); % maybe use com.jidesoft.grid.FormattedTextFieldCellEditor ? case 'date', dateModel = com.jidesoft.combobox.DefaultDateModel; dateFormat = java.text.SimpleDateFormat('dd/MM/yyyy'); dateModel.setDateFormat(dateFormat); editor = com.jidesoft.grid.DateCellEditor(dateModel, 1); alignProp(prop, editor, 'java.util.Date'); try prop.setValue(dateFormat.parse(prop.getValue)); % convert string => Date catch % ignore end otherwise, alignProp(prop); % treat as a simple text field end end % for all possible data types prop.setDescription(description); if ~isempty(description) renderer = com.jidesoft.grid.CellRendererManager.getRenderer(prop.getType, prop.getEditorContext); renderer.setToolTipText(description); end % Set the property's editability state if prop.isEditable % Set the property's label to be black prop.setDisplayName(['<html><font color="black">' label]); % Add callbacks for property-change events hprop = handle(prop, 'CallbackProperties'); set(hprop,'PropertyChangeCallback',{propUpdatedCallback,propName}); else % Set the property's label to be gray prop.setDisplayName(['<html><font color="gray">' label]); end setPropName(prop,propName); end % newProperty % Set property name in the Java property reference function setPropName(hProp,propName) try set(hProp,'UserData',propName) catch %setappdata(hProp,'UserData',propName) hp = schema.prop(handle(hProp),'UserData','mxArray'); %#ok<NASGU> set(handle(hProp),'UserData',propName) end end % setPropName % Get property name from the Java property reference function propName = getPropName(hProp) try propName = get(hProp,'UserData'); catch %propName = char(getappdata(hProp,'UserData')); propName = get(handle(hProp),'UserData'); end end % getPropName % Get recursive property name function propName = getRecursivePropName(prop, propBaseName) try oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty'); try prop = java(prop); catch, end if nargin < 2 propName = getPropName(prop); else propName = propBaseName; end while isa(prop,'com.jidesoft.grid.Property') prop = get(prop,'Parent'); newName = getPropName(prop); if isempty(newName) %% check to see if it's a (1,1) displayName = char(prop.getName); [flag, index] = CheckStringForBrackets(displayName); if flag propName = sprintf('(%i).%s',index,propName); else break; end else propName = [newName '.' propName]; %#ok<AGROW> end end catch % Reached the top of the property's heirarchy - bail out warning(oldWarn); end end % getRecursivePropName % Align a text property to right/left function alignProp(prop, editor, propTypeStr, direction) persistent propTypeCache if isempty(propTypeCache), propTypeCache = java.util.Hashtable; end if nargin < 2 || isempty(editor), editor = com.jidesoft.grid.StringCellEditor; end %(javaclass('char',1)); if nargin < 3 || isempty(propTypeStr), propTypeStr = 'cellstr'; end % => javaclass('char',1) if nargin < 4 || isempty(direction), direction = javax.swing.SwingConstants.RIGHT; end % Set this property's data type propType = propTypeCache.get(propTypeStr); if isempty(propType) propType = javaclass(propTypeStr); propTypeCache.put(propTypeStr,propType); end prop.setType(propType); % Prepare a specific context object for this property if strcmpi(propTypeStr,'logical') %TODO - FIXME context = editor.CONTEXT; prop.setEditorContext(context); %renderer = CheckBoxRenderer; %renderer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); %com.jidesoft.grid.CellRendererManager.registerRenderer(propType, renderer, context); else context = com.jidesoft.grid.EditorContext(prop.getName); prop.setEditorContext(context); % Register a unique cell renderer so that each property can be modified seperately %renderer = com.jidesoft.grid.CellRendererManager.getRenderer(propType, prop.getEditorContext); renderer = com.jidesoft.grid.ContextSensitiveCellRenderer; com.jidesoft.grid.CellRendererManager.registerRenderer(propType, renderer, context); renderer.setBackground(java.awt.Color.white); renderer.setHorizontalAlignment(direction); %renderer.setHorizontalTextPosition(direction); end % Update the property's cell editor try editor.setHorizontalAlignment(direction); catch, end try editor.getTextField.setHorizontalAlignment(direction); catch, end try editor.getComboBox.setHorizontalAlignment(direction); catch, end % Set limits on unsigned int values try if strcmpi(propTypeStr,'uint32') %pause(0.01); editor.setMinInclusive(java.lang.Integer(0)); editor.setMinExclusive(java.lang.Integer(-1)); editor.setMaxExclusive(java.lang.Integer(intmax)); editor.setMaxInclusive(java.lang.Integer(intmax)); end catch % ignore end com.jidesoft.grid.CellEditorManager.registerEditor(propType, editor, context); end % alignProp % Property updated callback function function propUpdatedCallback(prop, eventData, propName, fileData) try if strcmpi(char(eventData.getPropertyName),'parent'), return; end; catch, end % Retrieve the containing figure handle %hFig = findall(0, '-depth',1, 'Tag','fpropertiesGUI'); hFig = get(0,'CurrentFigure'); %gcf; if isempty(hFig) hPropsPane = findall(0,'Tag','hpropertiesGUI'); if isempty(hPropsPane), return; end hFig = ancestor(hPropsPane,'figure'); %=get(hPropsPane,'Parent'); end if isempty(hFig), return; end % Get the props data from the figure's ApplicationData propsList = getappdata(hFig, 'propsList'); propsPane = getappdata(hFig, 'jPropsPane'); data = getappdata(hFig, 'mirror'); % Bail out if arriving from tableDataUpdatedCallback try s = dbstack; if strcmpi(s(2).name, 'tableDataUpdatedCallback') return; end catch % ignore end % Get the updated property value propValue = get(prop,'Value'); if isjava(propValue) if isa(propValue,'java.util.Date') sdf = java.text.SimpleDateFormat('MM-dd-yyyy'); propValue = datenum(sdf.format(propValue).char); %#ok<NASGU> elseif isa(propValue,'java.awt.Color') propValue = propValue.getColorComponents([])'; %#ok<NASGU> else propValue = char(propValue); %#ok<NASGU> end end % Get the actual recursive propName propName = getRecursivePropName(prop, propName); % Find if the original item was a cell array and the mirror accordingly items = strread(propName,'%s','delimiter','.'); if ~isempty(data) cpy = data; for idx = 1 : length(items) % This is for dealing with structs with multiple levels... [flag, index] = CheckStringForBrackets(items{idx}); if flag cpy = cpy(index); else if isfield(cpy,items{idx}) cpy = cpy.(items{idx}); else return end end end if nargin == 4 if iscell(cpy) && iscell(fileData) %%&& length(fileData)==1 % if mirror and filedata are cells then update the data -> otherwise overright. propValue=UpdateCellArray(cpy,fileData); end else if iscell(cpy) propValue = UpdateCellArray(cpy, propValue); end end end % Check for loading from file and long string which has been truncated if nargin == 4 propValue = checkCharFieldForAbreviation(propValue,fileData); if ~isempty(propValue) && strcmp(propValue(1),'[') && ~isempty(strfind(propValue,' struct array]')) propValue = fileData; end if isempty(propValue) % a struct propValue = fileData; end end % For items with .(N) in the struct -> remove from path for eval propName = regexprep(propName,'\.(','('); % Update the mirror with the updated field value %data.(propName) = propValue; % croaks on multiple sub-fields eval(['data.' propName ' = propValue;']); % Update the local mirror setappdata(hFig, 'mirror',data); % Update the display checkProps(propsList, hFig); try propsPane.repaint; catch; end end % propUpdatedCallback function selectedValue = UpdateCellArray(originalData,selectedValue) if length(originalData)==length(selectedValue) || ~iscell(selectedValue) index=find(strcmp(originalData,selectedValue)==1); if iscell(originalData{end}) originalData{end}={index}; else if index~=1 % If it's not first index then we can save it originalData{end+1} = {index}; end end selectedValue=originalData; else selectedValue=originalData; end end % UpdateCellArray % <OK> button callback function function btOK_Callback(btOK, eventData) %#ok<INUSD> global test_data % Store the current data-info struct mirror in the global struct hFig = ancestor(btOK, 'figure'); test_data = getappdata(hFig, 'mirror'); setappdata(0,'isParamsGUIApproved',true); % Close the window try close(hFig); catch delete(hFig); % force-close end end % btOK_Callback % Check whether all mandatory fields have been filled, update background color accordingly function checkProps(propsList, hContainer, isInit) if nargin < 3, isInit = false; end okEnabled = 'on'; try propsArray = propsList.toArray(); catch, return; end for propsIdx = 1 : length(propsArray) isOk = checkProp(propsArray(propsIdx)); if ~isOk || isInit, okEnabled = 'off'; end end % Update the <OK> button's editability state accordingly btOK = findall(hContainer, 'Tag','btOK'); set(btOK, 'Enable',okEnabled); set(findall(get(hContainer,'parent'), 'tag','btApply'), 'Enable',okEnabled); set(findall(get(hContainer,'parent'), 'tag','btRevert'), 'Enable',okEnabled); try; drawnow; pause(0.01); end % Update the figure title to indicate dirty-ness (if the figure is visible) hFig = ancestor(hContainer,'figure'); if strcmpi(get(hFig,'Visible'),'on') sTitle = regexprep(get(hFig,'Name'), '\*$',''); set(hFig,'Name',[sTitle '*']); end end % checkProps function isOk = checkProp(prop) isOk = true; oldWarn = warning('off','MATLAB:hg:JavaSetHGProperty'); warning off MATLAB:hg:PossibleDeprecatedJavaSetHGProperty propName = getPropName(prop); renderer = com.jidesoft.grid.CellRendererManager.getRenderer(get(prop,'Type'), get(prop,'EditorContext')); warning(oldWarn); mandatoryFields = {}; % TODO - add the mandatory field-names here if any(strcmpi(propName, mandatoryFields)) && isempty(get(prop,'Value')) propColor = java.awt.Color.yellow; isOk = false; elseif ~prop.isEditable %propColor = java.awt.Color.gray; %propColor = renderer.getBackground(); propColor = java.awt.Color.white; else propColor = java.awt.Color.white; end renderer.setBackground(propColor); end % checkProp % Return java.lang.Class instance corresponding to the Matlab type function jclass = javaclass(mtype, ndims) % Input arguments: % mtype: % the MatLab name of the type for which to return the java.lang.Class % instance % ndims: % the number of dimensions of the MatLab data type % % See also: class % Copyright 2009-2010 Levente Hunyadi % Downloaded from: http://www.UndocumentedMatlab.com/files/javaclass.m validateattributes(mtype, {'char'}, {'nonempty','row'}); if nargin < 2 ndims = 0; else validateattributes(ndims, {'numeric'}, {'nonnegative','integer','scalar'}); end if ndims == 1 && strcmp(mtype, 'char'); % a character vector converts into a string jclassname = 'java.lang.String'; elseif ndims > 0 jclassname = javaarrayclass(mtype, ndims); else % The static property .class applied to a Java type returns a string in % MatLab rather than an instance of java.lang.Class. For this reason, % use a string and java.lang.Class.forName to instantiate a % java.lang.Class object; the syntax java.lang.Boolean.class will not do so switch mtype case 'logical' % logical vaule (true or false) jclassname = 'java.lang.Boolean'; case 'char' % a singe character jclassname = 'java.lang.Character'; case {'int8','uint8'} % 8-bit signed and unsigned integer jclassname = 'java.lang.Byte'; case {'int16','uint16'} % 16-bit signed and unsigned integer jclassname = 'java.lang.Short'; case {'int32','uint32'} % 32-bit signed and unsigned integer jclassname = 'java.lang.Integer'; case {'int64','uint64'} % 64-bit signed and unsigned integer jclassname = 'java.lang.Long'; case 'single' % single-precision floating-point number jclassname = 'java.lang.Float'; case 'double' % double-precision floating-point number jclassname = 'java.lang.Double'; case 'cellstr' % a single cell or a character array jclassname = 'java.lang.String'; otherwise jclassname = mtype; %error('java:javaclass:InvalidArgumentValue', ... % 'MatLab type "%s" is not recognized or supported in Java.', mtype); end end % Note: When querying a java.lang.Class object by name with the method % jclass = java.lang.Class.forName(jclassname); % MatLab generates an error. For the Class.forName method to work, MatLab % requires class loader to be specified explicitly. jclass = java.lang.Class.forName(jclassname, true, java.lang.Thread.currentThread().getContextClassLoader()); end % javaclass % Return the type qualifier for a multidimensional Java array function jclassname = javaarrayclass(mtype, ndims) switch mtype case 'logical' % logical array of true and false values jclassid = 'Z'; case 'char' % character array jclassid = 'C'; case {'int8','uint8'} % 8-bit signed and unsigned integer array jclassid = 'B'; case {'int16','uint16'} % 16-bit signed and unsigned integer array jclassid = 'S'; case {'int32','uint32'} % 32-bit signed and unsigned integer array jclassid = 'I'; case {'int64','uint64'} % 64-bit signed and unsigned integer array jclassid = 'J'; case 'single' % single-precision floating-point number array jclassid = 'F'; case 'double' % double-precision floating-point number array jclassid = 'D'; case 'cellstr' % cell array of strings jclassid = 'Ljava.lang.String;'; otherwise jclassid = ['L' mtype ';']; %error('java:javaclass:InvalidArgumentValue', ... % 'MatLab type "%s" is not recognized or supported in Java.', mtype); end jclassname = [repmat('[',1,ndims), jclassid]; end % javaarrayclass % Set up the uitree context (right-click) menu function showGridContextMenu(hFig, grid, clickX, clickY) % Prepare the context menu (note the use of HTML labels) import javax.swing.* row = grid.rowAtPoint(java.awt.Point(clickX, clickY)); selectedProp = grid.getPropertyTableModel.getPropertyAt(row); if ~isempty(selectedProp) branchName = char(selectedProp.getName); else branchName = 'branch'; end menuItem1 = JMenuItem(['Save ' branchName '...']); menuItem2 = JMenuItem(['Load ' branchName '...']); % Set the menu items' callbacks set(handle(menuItem1,'CallbackProperties'),'ActionPerformedCallback',@(obj,event)fileIO_Callback(grid,selectedProp,'save',hFig)); set(handle(menuItem2,'CallbackProperties'),'ActionPerformedCallback',@(obj,event)fileIO_Callback(grid,selectedProp,'load',hFig)); % Add all menu items to the context menu (with internal separator) jmenu = JPopupMenu; jmenu.add(menuItem1); jmenu.addSeparator; jmenu.add(menuItem2); % Display the context-menu jmenu.show(grid, clickX, clickY); jmenu.repaint; end % setGridContextMenu function fileIO_Callback(grid, selectedProp, mode, hFig, filename) persistent lastdir mirrorData = getappdata(hFig, 'mirror'); if nargin == 4 % interactive filename = []; end % Initialize the persistent variable with the current Dir if not populated. if isempty(lastdir); lastdir = pwd; end switch mode case 'save' filename = saveBranch_Callback(grid, selectedProp, lastdir, mirrorData, hFig, filename); case 'load' filename = loadBranchCallback(grid, selectedProp, lastdir, mirrorData, filename); case {'update', 'select'} % hidden calling method runtimeUpdateBranch(grid,filename,mirrorData,selectedProp); return otherwise error('propertiesGUI:fileIOCallback:invalidMethod', 'invalid calling method to propertiesGUI'); % setappdata(hFig, 'mirror',mirrorData); end % Check that the save/load wsa processed if ischar(filename) filePath = fileparts(filename); if ~isempty(filePath) lastdir = filePath; end end end % fileIO_Callback function filename = loadBranchCallback(grid, selectedProp, lastdir, mirrorData, filename) if isempty(filename) [filename, pathname] = uigetfile({'*.branch','Branch files (*.branch)'}, 'Load a file', lastdir); if filename == 0 return end filename = fullfile(pathname, filename); else selectedProp = findUserProvidedProp(grid, selectedProp); end propName = char(selectedProp.getName); propName = checkFieldName(propName); data = load(filename, '-mat'); fnames = fieldnames(data); index = strcmpi(fnames,propName); % If a match was found then it's okay to proceed if any(index) % Remove any children selectedProp.removeAllChildren(); % Make a new list newList = preparePropsList(data, true); % Conver the list to an array newArray = newList.toArray(); updatedProp = newArray(1); isStruct = false; propValue = selectedProp.getValue; if ~isempty(propValue) && strcmp(propValue(1),'[') && ~isempty(strfind(propValue,' struct array]')) isStruct = true; end % If individual value update it. TODO: Bug when it is a cell array.... if isStruct == false && ~isempty(propValue) selectedProp.setValue (updatedProp.getValue) propName = checkFieldName(char(updatedProp.getName)); if iscell(data.(fnames{index})) && ischar(data.(fnames{index}){end}) && ismember(data.(fnames{index})(end),data.(fnames{index})(1:end-1)) data.(fnames{index})(end) = []; end propUpdatedCallback(selectedProp, [], propName, data.(fnames{index})); else % Add children to the original property. for ii=1:updatedProp.getChildrenCount childProp = updatedProp.getChildAt(ii-1); propName = checkFieldName(char(childProp.getName)); [flag, sIndex] = CheckStringForBrackets(propName); if flag % propUpdatedCallback(childProp, [], propName, data.(fnames{index}).(propName)); else propUpdatedCallback(childProp, [], propName, data.(fnames{index}).(propName)); end selectedProp.addChild(childProp); end end else errMsg = 'The selected branch does not match the data in the data file'; %error('propertieGUI:load:branchName', errMsg); errordlg(errMsg, 'Load error'); end end % runtime update item in branch (undocumented - for easier testing) function runtimeUpdateBranch(grid, selectedProp, mirrorData, newData) userStr = strread(selectedProp,'%s','delimiter','.'); if length(userStr)~= 1 mirrorData = findMirrorDataLevel(mirrorData, userStr); end selectedProp = findUserProvidedProp(grid, selectedProp); if ~isempty(selectedProp.getValue) propName = checkFieldName(char(selectedProp.getName)); if iscell(newData) && length(newData)==1 && isnumeric(newData{1}) % user specifying index to select. propData = mirrorData.(propName); if iscell(mirrorData.(propName)) userSelection = propData{newData{1}}; else userSelection = newData; end if any(ismember(propData,userSelection)) selectedProp.setValue (userSelection); propUpdatedCallback(selectedProp, [], propName, propData); end end end end % runtimeUpdateBranch % Save callback and subfunctions function filename = saveBranch_Callback(grid, selectedProp, lastdir, mirrorData, hFig, filename) % Interactive use runtimeCall = isempty(filename); if runtimeCall [filename, pathname] = uiputfile ({'*.branch','Branch files (*.branch)'}, 'Save as', lastdir); if filename == 0 return end filename = fullfile(pathname, filename); else % from commandline if isempty(selectedProp) % user wants to save everything. selectedProp = grid; else userStr = strread(selectedProp,'%s','delimiter','.'); if length(userStr)~= 1 mirrorData = findMirrorDataLevel(mirrorData, userStr); end selectedProp = findUserProvidedProp(grid, selectedProp); end end if ~isempty(selectedProp.getName) fieldname = checkFieldName(selectedProp.getName); data.(fieldname) = selfBuildStruct(selectedProp); fieldname = {fieldname}; else [rootProps, data] = buildFullStruct(hFig); % (grid,mirrorData) fieldname = fieldnames(data); selectedProp = rootProps{1}; end % option to save combo boxes as well... if nargin >= 4 for fieldIdx = 1 : length(fieldname) if fieldIdx>1 % This only happens when loading to replace the full data selectedProp = rootProps{fieldIdx}; end dataNames = fieldnames(mirrorData); match = strcmpi(dataNames,fieldname{fieldIdx}); % This sub function will add all the extra items if any(match) % This looks in the mirrorData to update the output with cell array items. data.(fieldname{fieldIdx}) = addOptionsToOutput(data.(fieldname{fieldIdx}), mirrorData.(dataNames{match}), selectedProp); % Update the original var names (case sensitive) data = updateOriginalVarNames(data, mirrorData); %data is used in the save command. else propName = getRecursivePropName(selectedProp, fieldname{fieldIdx}); items = strread(propName,'%s','delimiter','.'); for idx = 1 : length(items)-1 if strcmp(items{idx}(1),'(') && strcmp(items{idx}(end),')') index = str2double(items{idx}(2:end-1)); mirrorData = mirrorData(index); else mirrorData = mirrorData.(items{idx}); end end data.(fieldname{fieldIdx}) = addOptionsToOutput(data.(fieldname{fieldIdx}), mirrorData.(items{end}), selectedProp); % Update the original var names (case sensitive) data = updateOriginalVarNames(data, mirrorData); %data is used in the save command. end end end % Save the data to file save(filename, '-struct', 'data') end % Descent through the mirror data to find the matching variable for the user requested data function mirrorData = findMirrorDataLevel(mirrorData, userStr) if length(userStr)==1 return else [flag, index] = CheckStringForBrackets(userStr{1}); if flag mirrorData = findMirrorDataLevel(mirrorData(index), userStr(2:end)); else mirrorData = mirrorData.(userStr{1}); mirrorData = findMirrorDataLevel(mirrorData, userStr(2:end)); end end end % findMirrorDataLevel % Search for the user specified property to load or to save function selectedProp = findUserProvidedProp(grid, selectedProp) index = 0; % Loop through the properties to find the matching branch strItems = strread(selectedProp, '%s', 'delimiter', '.'); while true incProp = grid.getPropertyTableModel.getPropertyAt(index); if isempty(incProp) error('propertiesGUI:InvalidBranch', 'User provied property name which was invalid') end % Search the full user defined string for the item to be saved. selectedProp = searchForPropName(incProp, strItems); if ~isempty(selectedProp); break; end index = index + 1; end end % findUserProvidedProp % Sub function for searching down through the user provided string when A.B.C provided. function selectedProp = searchForPropName(parentNode, userString) selectedProp = []; nodeName = char(parentNode.getName); % if strcmp(nodeName(1),'(') && strcmp(nodeName(end),')') if strcmpi(userString{1},checkFieldName(nodeName)) % ? shoudl this be case sensitive? if length(userString) == 1 selectedProp = parentNode; else for jj=1:parentNode.getChildrenCount selectedProp = searchForPropName(parentNode.getChildAt(jj-1), userString(2:end)); if ~isempty(selectedProp) break end end end end end % searchForPropName % Build full struct function [rootProps, output] = buildFullStruct(hFig) % (grid,mirrorData) %{ % This fails if some of the top-level props are expanded (open) index = 0; rootProps = {}; while true incProp = grid.getPropertyTableModel.getPropertyAt(index); if isempty(incProp); break; end % Search the full user defined string for the item to be saved. propName = checkFieldName(incProp.getName); if isfield(mirrorData,propName) output.(propName) = selfBuildStruct(incProp); rootProps{end+1} = incProp; end index = index + 1; end %} propsList = getappdata(hFig, 'propsList'); rootProps = cell(propsList.toArray)'; for propIdx = 1 : numel(rootProps) thisProp = rootProps{propIdx}; propName = checkFieldName(thisProp.getName); output.(propName) = selfBuildStruct(thisProp); end end % buildFullStruct % Build the structure for saving from the selected Prop function output = selfBuildStruct(selectedProp) % Self calling loop to build the output structure. propValue = selectedProp.getValue; % If property empty then the selectedProp is a struct. isStruct = isempty(propValue); nStructs = 1; % Check if it's an array of structs M = 1; if ~isempty(propValue) && strcmp(propValue(1),'[') && ~isempty(strfind(propValue,' struct array]')) isStruct = true; nStructs = selectedProp.getChildrenCount; xIndex = strfind(propValue,'x'); %spIndex = strfind(propValue,' '); M=str2double(propValue(2:xIndex-1)); %N=str2double(propValue(xIndex+1:spIndex(1)-1)); end if isStruct output=struct; % Extract out each child for ii=1:nStructs; if nStructs>1 structLoopProp = selectedProp.getChildAt(ii-1); else structLoopProp = selectedProp; end for jj=1:structLoopProp.getChildrenCount child = structLoopProp.getChildAt(jj-1); fieldname = checkFieldName(child.getName); if M==1 output(1,ii).(fieldname) = selfBuildStruct(child); else output(ii,1).(fieldname) = selfBuildStruct(child); end end end else switch class(propValue) case 'java.io.File' output = char(propValue); otherwise output = propValue; end end end % selfBuildStruct % Replace any ' ' with an '_' in the output fieldname (see also getFieldLabel() above) function fieldname = checkFieldName(fieldname) fieldname = char(fieldname); fieldname = regexprep(fieldname, ' \((.*)\)', '__$1'); fieldname = strrep(fieldname, ' ', '_'); fieldname(1) = upper(fieldname(1)); end % checkFieldName % Function to add the extra options (when popupmenu) to the output function output = addOptionsToOutput(output, mirrorData, selectedProp) if isstruct(output) && isstruct(mirrorData) outputFields = fieldnames(output); mirrorFields = fieldnames(mirrorData); for ii=1:length(output) if length(output)>1 structLoopProp = selectedProp.getChildAt(ii-1); else structLoopProp = selectedProp; end for jj=1:numel(outputFields) childProp = structLoopProp.getChildAt(jj-1); % sanity check this??????childProp.getName mirrorIndex = strcmpi(mirrorFields,outputFields{jj}); if any(mirrorIndex) mirrorField = mirrorFields{mirrorIndex}; if isfield(mirrorData(ii), mirrorField) if ismember('arrayData',fieldnames(get(childProp))) arrayData = get(childProp,'ArrayData'); output(ii).(outputFields{jj}) = arrayData; else if iscell(mirrorData(ii).(mirrorField)) % If original was a cell -> save originals as extra items in the cell array. output(ii).(outputFields{jj}) = UpdateCellArray(mirrorData(ii).(outputFields{jj}),output(ii).(outputFields{jj})); % selectedIndex = find(strcmp(mirrorData.(mirrorField),output.(outputFields{ii})))==1; % % output.(outputFields{ii}) = {mirrorData.(mirrorField){:} {selectedIndex}}; elseif isstruct(mirrorData(ii).(mirrorField)) output(ii).(outputFields{jj}) = addOptionsToOutput(output(ii).(outputFields{jj}),mirrorData(ii).(mirrorField), childProp); else output(ii).(outputFields{jj}) = checkCharFieldForAbreviation(output(ii).(outputFields{jj}),mirrorData(ii).(mirrorField)); end end end end end end else if ismember('arrayData',fieldnames(get(selectedProp))) arrayData = get(selectedProp,'ArrayData'); output = arrayData; else if iscell(mirrorData) output = UpdateCellArray(mirrorData,output); else output = checkCharFieldForAbreviation(output,mirrorData); end end end end % addOptionsToOutput % Check to see if a char was truncated on GUI building (>50) function output = checkCharFieldForAbreviation(output,mirrorData) % This is to replace the ... with the original data if ischar(output) && ... % Is it a char which has been truncated? length(output) == 53 && ... length(mirrorData) > 50 && ... strcmp(output(end-2:end),'...') && ... strcmp(output(1:50),mirrorData(1:50)) output = mirrorData; end end % checkCharFieldForAbreviation % Loop through the structure and replace any in case sensitive names function output = updateOriginalVarNames(output, mirrorData) outputFields = fieldnames(output); for jj=1:length(output) if isempty(outputFields) output = mirrorData; else mirrorFields = fieldnames(mirrorData); for ii=1:numel(outputFields) mirrorIndex = strcmpi(mirrorFields,outputFields{ii}); if any(mirrorIndex) mirrorField = mirrorFields{mirrorIndex}; if ~strcmp(mirrorField, outputFields{ii}) output(jj).(mirrorField) = output(jj).(outputFields{ii}); if jj==length(output) output = rmfield(output,outputFields{ii}); end end if isstruct(output(jj).(mirrorField)) output(jj).(mirrorField) = updateOriginalVarNames(output(jj).(mirrorField), mirrorData(jj).(mirrorField)); end end end end end end % updateOriginalVarNames function [flag, index] = CheckStringForBrackets(str) index = []; flag = strcmp(str(1),'(') && strcmp(str(end),')'); if flag index = max(str2num(regexprep(str,'[()]',''))); % this assumes it's always (1,N) or (N,1) end end % CheckStringForBrackets
github
ISET/iset3d-v3-master
struct2node.m
.m
iset3d-v3-master/external/struct2node.m
830
utf_8
e7539fd43efc352edd218b41a877e376
function root = struct2node(S,name) %STRUCT2NODE returns a parallel uitreenode object for a struct % ROOT = STRUCT2NODE(S) returns a uitreenode object. % ROOT = STRUCT2NODE(S,NAME) returns a uitreenode object with the given % name. assert(isscalar(S)&&isstruct(S),'function only defined for scalar structs') if nargin==1 name = inputname(1); end if isempty(name),name='Node';end root = uitreenode('v0',name,name,[],false); cellfun(@(name)buildNode(root,S,name,S.name),fieldnames(S)) function buildNode(parentNode,S,name,value) if ~isscalar(S) arrayfun(@(X)buildNode(parentNode,X,name),S) return end val = S.(name); isLeaf = ~isstruct(val); childNode = uitreenode(parentNode,'Text',name,isLeaf); if ~isLeaf cellfun(@(x)buildNode(childNode,val,x,x),fieldnames(val)) end parentNode.add(childNode);
github
ISET/iset3d-v3-master
unix2dos.m
.m
iset3d-v3-master/external/unix2dos.m
1,768
utf_8
bb3eaa9c87bc6c8c51341a8d847d9494
function unix2dos(filein,dos2unix) % UNIX2DOS(FILEIN,DOS2UNIX) % % converts text file FILEIN from unix LF format to DOS CRLF format % if the optional DOS2UNIX parameter is set to true, the conversion is % done the other way, i.e. DOS to UNIX format % % example % unix2dos('c:\temp\myfile.txt',true) % converts the file myfile.txt in the directory c:\temp\ from DOS (CR/LF) to UNIX (LF) % % unix2dos('c:\temp\myfile.txt') % converts the file myfile.txt in the directory c:\temp\ from UNIX (LF) to DOS (CR/LF) % % Added to iset3d as some of the data written by the spectral version of % pbrt inadvertently has line-endings wrong when the native windows version % is used. % % % History: From Mathworks file Exchange % Enhanced & integrated into iset3d -- D. Cardinal, March, 2021 % if nargin<2 dos2unix=false; end LF=char(10);CR=char(13); [fid,fm]=fopen(filein,'r'); if fid<0 error([fm ' Could not open file ' filein '. Does not exist, is in use, or is read-only.']) end fcontent=fread(fid,'uint8'); fcontentLeft = fcontent; fcontentLeft(1) = []; fcontentLeft(end+1) = 0; fContentCR = find(fcontent==CR); fContentLF = find(fcontentLeft==LF); fcontentCRLF = intersect(fContentCR, fContentLF); fcontent(fcontentCRLF) = []; if ~dos2unix fcontent=strrep(char(row(fcontent)),LF,[CR LF]); % replace LF with CR,LF end fclose(fid); % don't use frewind here because new write may be smaller and don't want to leave stuff at the end [fid,fm]=fopen(filein,'w'); if fid<0 error([fm ' Could not open file ' filein '. Does not exist, is in use, or is read-only.']) end fwrite(fid,fcontent,'uint8'); fclose(fid); function y=row(x); %ROW Converts an array into a row vector % function y=row(x); % converts x into a row vector y=x(:).';
github
jcorbino/mole-master
tfi.m
.m
mole-master/mole_MATLAB/tfi.m
1,378
utf_8
dd3f11c74046fee428b36d49c0df5b7a
% https://en.wikipedia.org/wiki/Transfinite_interpolation function [X, Y] = tfi(grid_name, m, n, plot_grid) % Returns X and Y which are both m by n matrices that contains the physical % coordinates % % Parameters: % grid_name : String with the name of the grid folder % m : Number of nodes along the horizontal axis % n : Number of nodes along the vertical axis % plot_grid : If defined -> grid will be plotted assert(m > 4 && n > 4, 'm and n must be greater than 4') addpath(['grids/' grid_name]) % Logical grid xi = linspace(0, 1, m); eta = linspace(0, 1, n); % Allocate space for physical grid X = zeros(m, n); Y = zeros(m, n); for i = 1 : m u = xi(i); for j = 1 : n v = eta(j); % Transfinite interpolation XY = (1-v)*bottom(u)+v*top(u)+(1-u)*left(v)+u*right(v)-... (u*v*top(1)+u*(1-v)*bottom(1)+v*(1-u)*top(0)+(1-u)*(1-v)*bottom(0)); X(i, j) = XY(1); Y(i, j) = XY(2); end end if plot_grid figure mesh(X, Y, zeros(m, n), 'Marker', '.', 'MarkerSize', 10, 'EdgeColor', 'b') title(['Physical grid. m = ' num2str(m) ', n = ' num2str(n)]) set(gcf, 'color', 'w') axis equal axis off view([0 90]) end end
github
jcorbino/mole-master
ttm.m
.m
mole-master/mole_MATLAB/ttm.m
2,709
utf_8
a6c0e55170571a775b8675bb6734f3d7
% https://www.sciencedirect.com/science/article/pii/0022247X78902172?via%3Dihub function [X, Y] = ttm(grid_name, m, n, iters, plot_grid) % Returns X and Y which are both m by n matrices that contains the physical % coordinates % % Parameters: % grid_name : String with the name of the grid folder % m : Number of nodes along the horizontal axis % n : Number of nodes along the vertical axis % plot_grid : If defined -> grid will be plotted assert(m > 4 && n > 4, 'm and n must be greater than 4') addpath(['grids/' grid_name]) % Error tolerance for iterative method tol = 10^-6; % Preallocation X = zeros(m, n); Y = zeros(m, n); alpha = zeros(m, n); beta = zeros(m, n); gamma = zeros(m, n); % BCs for i = 1 : m xi = (i-1)/(m-1); XY = top(xi); X(i, end) = XY(1); Y(i, end) = XY(2); XY = bottom(xi); X(i, 1) = XY(1); Y(i, 1) = XY(2); end for j = 1 : n eta = (j-1)/(n-1); XY = left(eta); X(1, j) = XY(1); Y(1, j) = XY(2); XY = right(eta); X(end, j) = XY(1); Y(end, j) = XY(2); end newX = X; newY = Y; errX = zeros(1, iters); errY = zeros(1, iters); % SOR for t = 1 : iters i = 2 : m-1; j = 2 : n-1; alpha(i, j) = 0.25*((X(i, j+1)-X(i, j-1)).^2+(Y(i, j+1)-Y(i, j-1)).^2); beta(i, j) = 0.0625*((X(i+1, j)-X(i-1, j)).*(X(i, j+1)-X(i, j-1))+(Y(i+1, j)... -Y(i-1, j)).*(Y(i, j+1)-Y(i, j-1))); gamma(i, j) = 0.25*((X(i+1, j)-X(i-1, j)).^2+(Y(i+1, j)-Y(i-1, j)).^2); newX(i, j) = ((-0.5)./(alpha(i, j)+gamma(i, j)+1e-10)).*(2*beta(i, j)... .*(X(i+1, j+1)-X(i-1, j+1)-X(i+1, j-1)+X(i-1, j-1))-alpha(i, j)... .*(X(i+1, j)+X(i-1, j))-gamma(i, j).*(X(i, j+1)+X(i, j-1))); newY(i, j) = ((-0.5)./(alpha(i, j)+gamma(i, j)+1e-10)).*(2*beta(i, j)... .*(Y(i+1, j+1)-Y(i-1, j+1)-Y(i+1, j-1)+Y(i-1, j-1))-alpha(i, j)... .*(Y(i+1, j)+Y(i-1, j))-gamma(i, j).*(Y(i, j+1)+Y(i, j-1))); errX(1, t) = max(max(abs(newX-X))); errY(1, t) = max(max(abs(newY-Y))); % Update X = newX; Y = newY; if errX(t) < tol && errY(t) < tol break end end if plot_grid figure mesh(X, Y, zeros(m, n), 'Marker', '.', 'MarkerSize', 10, 'EdgeColor', 'b') title(['Physical grid. m = ' num2str(m) ', n = ' num2str(n)]) set(gcf, 'color', 'w') axis equal axis off view([0 90]) end end
github
jcorbino/mole-master
test_curl.m
.m
mole-master/examples_MATLAB/test_curl.m
1,530
utf_8
7aa2465d04817eb7f4d8a59bb33ead8b
% This file does not uses the curl2D(...) function provided by the library. % It just tests the 2D mimetic divergence applied to an auxiliary vector % field to obtain the equivalent curl. The proper way to solve problems % that involve the curl operator is by calling the function curl2D(...) clc close all addpath('../mole_MATLAB') order = 2; west = -10; east = 10; south = -10; north = 10; m = 20; n = 20; dx = (east-west)/m; dy = (north-south)/n; xaxis = west : (dx/2) : east; yaxis = south : (dy/2) : north; [X, Y] = meshgrid(xaxis(1:2:end), yaxis(1:2:end)); F = zeros(2*m*n+m+n, 1); k = 1; for j = 2 : 2 : 2*n+1 for i = 1 : 2 : 2*m+1 F(k) = Q(xaxis(i), yaxis(j)); % Important! k = k + 1; end end for j = 1 : 2 : 2*n+1 for i = 2 : 2 : 2*m+1 F(k) = -P(xaxis(i), yaxis(j)); % Important! k = k + 1; end end curl = div2D(order, m, dx, n, dy)*F; % F is F* in https://doi.org/10.1016/j.cam.2019.06.042 curl = reshape(curl, m+2, n+2); curl = curl(2:end-1, 2:end-1); % Vector field U = P(X, Y); V = Q(X, Y); quiver3(X(2:end, 2:end), Y(2:end, 2:end), zeros(m, n), U(2:end, 2:end), V(2:end, 2:end), curl); % Remember that by default, quiver will scale the length of the arrows! title('Mimetic-curl'); xlabel('x') ylabel('y') zlabel('z') set(gcf, 'color', 'w') view(0, 90) axis tight % This P and Q will produce a scalar curl = 2 function U = P(~, Y) U = -Y; end function V = Q(X, ~) V = X; end
github
jcorbino/mole-master
richards.m
.m
mole-master/examples_MATLAB/richards.m
2,342
utf_8
0925d9ff80524af89a1669f7f48f23c8
% Solves the highly nonlinear Richard's equation in 1D using the mixed form % approach and Newton's method to find the roots F(x) = 0 function richards clc close all addpath('../mole_MATLAB'); % Spatial and temporal discretization k = 4; m = 60; a = 0; b = 40; dx = (b-a)/m; t = 360; dt = 1; n = t/dt; % Problem's parameters (from Michael Celia's paper on Unsaturated Flow) alpha = 1.611e+6; theta_s = 0.287; theta_r = 0.075; theta_g = theta_s - theta_r; beta = 3.96; K_s = 0.00944; A = 1.175e+6; gamma = 4.74; ic = -61.5; bot_bc = -20; top_bc = -61.5; % Get mimetic operators D = div(k, m, dx); G = grad(k, m, dx); I = interpol(m, 0.5); K_psi = @(psi) (K_s.* A)./(A + abs(psi).^gamma); theta_psi = @(psi) ((alpha.*theta_g)./(alpha + abs(psi).^beta)) + theta_r; psi_init = ones(m, 1)*ic; psi_old = [ic; psi_init; ic]; %v = VideoWriter('richards1D_Corbino.avi', 'Uncompressed AVI'); %v.FrameRate = 30; %open(v); ff = figure(1); % Time integration loop for i = 1 : n init_guess = ones(m,1)*ic; func = @F; % Find the roots using Newton's method sol = fsolve(@(psi) func(psi), init_guess, optimoptions('fsolve',... 'Display', 'off')); psi_old = [bot_bc; sol; top_bc]; % Plot results plot([0 dx/2:dx:b-dx/2 b], psi_old, 'b'); ff.GraphicsSmoothing = 'on'; title(['Richards Eqn. (Mixed form) solved with MOLE,' ' Time = '... num2str(dt*i) '\newline']) axis([0 40 -70 -10]) xlabel('Depth') ylabel('Pressure head') set(gcf, 'color', 'w') legend('U') drawnow %M(k) = getframe(gcf); end %writeVideo(v, M) %close(v) function fval = F(psi) psi_new = [bot_bc;psi;top_bc]; K = I * K_psi(psi_new); theta_t = (theta_psi(psi_new) - theta_psi(psi_old)) / dt; d1 = - D * diag(K) * G * psi_new; d1 = [bot_bc ; d1(2:end-1) ; top_bc]; Dz = + D * K; Dz = [bot_bc ; Dz(2:end-1) ; top_bc]; fval = theta_t + d1 + Dz; fval = fval(2:end-1); end end
github
smart-media-lab/An-Ant-Colony-Optimization-Algorithm-For-Image-Edge-Detection-master
edge_CEC_2008_main.m
.m
An-Ant-Colony-Optimization-Algorithm-For-Image-Edge-Detection-master/edge_CEC_2008_main.m
12,126
utf_8
6a8bf236907d87135addee0723242305
function edge_CEC_2008_main % % This is a demo program of image edge detection using ant colony, based on % the paper, "An Ant Colony Optimization Algorithm For Image Edge % Detection," IEEE Congress on Evolutionary Computation (CEC), pp. 751-756, Hongkong, % Jun. 2008. % % % Input: % gray image with a square size % % Output: % four edge map images, which are obtained by the method using four functions, % respectively. % close all; clear all; clc; % image loading filename = 'camera128'; img = double(imread([filename '.bmp']))./255; [nrow, ncol] = size(img); %visiblity function initialization, see equation (4) for nMethod = 1:4; %Four kernel functions used in the paper, see equations (7)-(10) %E: exponential; F: flat; G: gaussian; S:Sine; T:Turkey; W:Wave fprintf('Welcome to demo program of image edge detection using ant colony.\nPlease wait......\n'); v = zeros(size(img)); v_norm = 0; for rr =1:nrow for cc=1:ncol %defination of clique temp1 = [rr-2 cc-1; rr-2 cc+1; rr-1 cc-2; rr-1 cc-1; rr-1 cc; rr-1 cc+1; rr-1 cc+2; rr cc-1]; temp2 = [rr+2 cc+1; rr+2 cc-1; rr+1 cc+2; rr+1 cc+1; rr+1 cc; rr+1 cc-1; rr+1 cc-2; rr cc+1]; temp0 = find(temp1(:,1)>=1 & temp1(:,1)<=nrow & temp1(:,2)>=1 & temp1(:,2)<=ncol & temp2(:,1)>=1 & temp2(:,1)<=nrow & temp2(:,2)>=1 & temp2(:,2)<=ncol); temp11 = temp1(temp0, :); temp22 = temp2(temp0, :); temp00 = zeros(size(temp11,1)); for kk = 1:size(temp11,1) temp00(kk) = abs(img(temp11(kk,1), temp11(kk,2))-img(temp22(kk,1), temp22(kk,2))); end if size(temp11,1) == 0 v(rr, cc) = 0; v_norm = v_norm + v(rr, cc); else lambda = 10; switch nMethod case 1%'F' temp00 = lambda .* temp00; case 2%'Q' temp00 = lambda .* temp00.^2; case 3%'S' temp00 = sin(pi .* temp00./2./lambda); case 4%'W' temp00 = sin(pi.*temp00./lambda).*pi.*temp00./lambda; end v(rr, cc) = sum(sum(temp00.^2)); v_norm = v_norm + v(rr, cc); end end end v = v./v_norm; %do normalization v = v.*100; % pheromone function initialization p = 0.0001 .* ones(size(img)); %paramete setting, see Section IV in CEC paper alpha = 1; %equation (4) beta = 0.1; %equation (4) rho = 0.1; %equation (11) phi = 0.05; %equation (12), i.e., (9) in IEEE-CIM-06 ant_total_num = round(sqrt(nrow*ncol)); ant_pos_idx = zeros(ant_total_num, 2); % record the location of ant % initialize the positions of ants rand('state', sum(clock)); temp = rand(ant_total_num, 2); ant_pos_idx(:,1) = round(1 + (nrow-1) * temp(:,1)); %row index ant_pos_idx(:,2) = round(1 + (ncol-1) * temp(:,2)); %column index search_clique_mode = '8'; %Figure 1 % define the memory length, the positions in ant's memory are % non-admissible positions for the next movement if nrow*ncol == 128*128 A = 40; memory_length = round(rand(1).*(1.15*A-0.85*A)+0.85*A); % memory length elseif nrow*ncol == 256*256 A = 30; memory_length = round(rand(1).*(1.15*A-0.85*A)+0.85*A); % memory length elseif nrow*ncol == 512*512 A = 20; memory_length = round(rand(1).*(1.15*A-0.85*A)+0.85*A); % memory length end % record the positions in ant's memory, convert 2D position-index (row, col) into % 1D position-index ant_memory = zeros(ant_total_num, memory_length); % System setup if nrow*ncol == 128*128 total_step_num = 300; % the numbe of iterations elseif nrow*ncol == 256*256 total_step_num = 900; elseif nrow*ncol == 512*512 total_step_num = 1500; end total_iteration_num = 3; for iteration_idx = 1: total_iteration_num %record the positions where ant have reached in the last 'memory_length' iterations delta_p = zeros(nrow, ncol); for step_idx = 1: total_step_num delta_p_current = zeros(nrow, ncol); for ant_idx = 1:ant_total_num ant_current_row_idx = ant_pos_idx(ant_idx,1); ant_current_col_idx = ant_pos_idx(ant_idx,2); % find the neighborhood of current position if search_clique_mode == '4' rr = ant_current_row_idx; cc = ant_current_col_idx; ant_search_range_temp = [rr-1 cc; rr cc+1; rr+1 cc; rr cc-1]; elseif search_clique_mode == '8' rr = ant_current_row_idx; cc = ant_current_col_idx; ant_search_range_temp = [rr-1 cc-1; rr-1 cc; rr-1 cc+1; rr cc-1; rr cc+1; rr+1 cc-1; rr+1 cc; rr+1 cc+1]; end %remove the positions our of the image's range temp = find(ant_search_range_temp(:,1)>=1 & ant_search_range_temp(:,1)<=nrow & ant_search_range_temp(:,2)>=1 & ant_search_range_temp(:,2)<=ncol); ant_search_range = ant_search_range_temp(temp, :); %calculate the transit prob. to the neighborhood of current %position ant_transit_prob_v = zeros(size(ant_search_range,1),1); ant_transit_prob_p = zeros(size(ant_search_range,1),1); for kk = 1:size(ant_search_range,1) temp = (ant_search_range(kk,1)-1)*ncol + ant_search_range(kk,2); if length(find(ant_memory(ant_idx,:)==temp))==0 %not in ant's memory ant_transit_prob_v(kk) = v(ant_search_range(kk,1), ant_search_range(kk,2)); ant_transit_prob_p(kk) = p(ant_search_range(kk,1), ant_search_range(kk,2)); else %in ant's memory ant_transit_prob_v(kk) = 0; ant_transit_prob_p(kk) = 0; end end % if all neighborhood are in memory, then the permissible search range is RE-calculated. if (sum(sum(ant_transit_prob_v))==0) | (sum(sum(ant_transit_prob_p))==0) for kk = 1:size(ant_search_range,1) temp = (ant_search_range(kk,1)-1)*ncol + ant_search_range(kk,2); ant_transit_prob_v(kk) = v(ant_search_range(kk,1), ant_search_range(kk,2)); ant_transit_prob_p(kk) = p(ant_search_range(kk,1), ant_search_range(kk,2)); end end ant_transit_prob = (ant_transit_prob_v.^alpha) .* (ant_transit_prob_p.^beta) ./ (sum(sum((ant_transit_prob_v.^alpha) .* (ant_transit_prob_p.^beta)))); % generate a random number to determine the next position. rand('state', sum(100*clock)); temp = find(cumsum(ant_transit_prob)>=rand(1), 1); ant_next_row_idx = ant_search_range(temp,1); ant_next_col_idx = ant_search_range(temp,2); if length(ant_next_row_idx) == 0 ant_next_row_idx = ant_current_row_idx; ant_next_col_idx = ant_current_col_idx; end ant_pos_idx(ant_idx,1) = ant_next_row_idx; ant_pos_idx(ant_idx,2) = ant_next_col_idx; %record the delta_p_current delta_p_current(ant_pos_idx(ant_idx,1), ant_pos_idx(ant_idx,2)) = 1; % record the new position into ant's memory if step_idx <= memory_length ant_memory(ant_idx,step_idx) = (ant_pos_idx(ant_idx,1)-1)*ncol + ant_pos_idx(ant_idx,2); elseif step_idx > memory_length ant_memory(ant_idx,:) = circshift(ant_memory(ant_idx,:),[0 -1]); ant_memory(ant_idx,end) = (ant_pos_idx(ant_idx,1)-1)*ncol + ant_pos_idx(ant_idx,2); end %update the pheromone function (10) in IEEE-CIM-06 p = ((1-rho).*p + rho.*delta_p_current.*v).*delta_p_current + p.*(abs(1-delta_p_current)); end % end of ant_idx % update the pheromone function see equation (9) in IEEE-CIM-06 delta_p = (delta_p + (delta_p_current>0))>0; p = (1-phi).*p; %equation (9) in IEEE-CIM-06 end % end of step_idx end % end of iteration_idx % generate edge map matrix % It uses pheromone function to determine edge T = func_seperate_two_class(p); %eq. (13)-(21), Calculate the threshold to seperate the edge map into two class fprintf('Done!\n'); imwrite(uint8(abs((p>=T).*255-255)), gray(256), [filename '_edge_aco_' num2str(nMethod) '.bmp'], 'bmp'); end % end of nMethod %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Inner Function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function level = func_seperate_two_class(I) % ISODATA Compute global image threshold using iterative isodata method. % LEVEL = ISODATA(I) computes a global threshold (LEVEL) that can be % used to convert an intensity image to a binary image with IM2BW. LEVEL % is a normalized intensity value that lies in the range [0, 1]. % This iterative technique for choosing a threshold was developed by Ridler and Calvard . % The histogram is initially segmented into two parts using a starting threshold value such as 0 = 2B-1, % half the maximum dynamic range. % The sample mean (mf,0) of the gray values associated with the foreground pixels and the sample mean (mb,0) % of the gray values associated with the background pixels are computed. A new threshold value 1 is now computed % as the average of these two sample means. The process is repeated, based upon the new threshold, % until the threshold value does not change any more. % % Reference :T.W. Ridler, S. Calvard, Picture thresholding using an iterative selection method, % IEEE Trans. System, Man and Cybernetics, SMC-8 (1978) 630-632. % Convert all N-D arrays into a single column. Convert to uint8 for % fastest histogram computation. I = I(:); % STEP 1: Compute mean intensity of image from histogram, set T=mean(I) [counts, N]=hist(I,256); i=1; mu=cumsum(counts); T(i)=(sum(N.*counts))/mu(end); % STEP 2: compute Mean above T (MAT) and Mean below T (MBT) using T from % step 1 mu2=cumsum(counts(N<=T(i))); MBT=sum(N(N<=T(i)).*counts(N<=T(i)))/mu2(end); mu3=cumsum(counts(N>T(i))); MAT=sum(N(N>T(i)).*counts(N>T(i)))/mu3(end); i=i+1; T(i)=(MAT+MBT)/2; % STEP 3 to n: repeat step 2 if T(i)~=T(i-1) Threshold=T(i); while abs(T(i)-T(i-1))>=1 mu2=cumsum(counts(N<=T(i))); MBT=sum(N(N<=T(i)).*counts(N<=T(i)))/mu2(end); mu3=cumsum(counts(N>T(i))); MAT=sum(N(N>T(i)).*counts(N>T(i)))/mu3(end); i=i+1; T(i)=(MAT+MBT)/2; Threshold=T(i); end % Normalize the threshold to the range [i, 1]. level = Threshold;
github
peterspat/handeyecalibration-master
SplashScreen.m
.m
handeyecalibration-master/app/deps/SplashScreen/SplashScreen-v1p1/SplashScreen.m
18,934
utf_8
7da473200120c9274129af47f5c0e359
classdef SplashScreen < hgsetget %SplashScreen create a splashscreen % % s = SplashScreen(title,imagefile) creates a splashscreen using % the specified image. The title is the name of the window as shown % in the task-bar. Use "delete(s)" to remove it. Note that images % must be in PNG, GIF or JPEG format. Use the addText method to add % text to your splashscreen % % Examples: % s = SplashScreen( 'Splashscreen', 'example_splash.png', ... % 'ProgressBar', 'on', ... % 'ProgressPosition', 5, ... % 'ProgressRatio', 0.4 ) % s.addText( 30, 50, 'My Cool App', 'FontSize', 30, 'Color', [0 0 0.6] ) % s.addText( 30, 80, 'v1.0', 'FontSize', 20, 'Color', [0.2 0.2 0.5] ) % s.addText( 300, 270, 'Loading...', 'FontSize', 20, 'Color', 'white' ) % delete( s ) % % See also: SplashScreen/addText % Copyright 2008-2011 The MathWorks, Inc. % Revision: 1.1 %% Public properties properties Visible = 'on' % Is the splash-screen visible on-screen [on|off] Border = 'on' % Is the edge pixel darkened to form a border [on|off] ProgressBar = 'off' % Is the progress bar visible [on|off] ProgressPosition = 10% Height (in pixels) above the bottom of the window for the progress bar ProgressRatio = 0 % The ratio shown on the progress bar (in range 0 to 1) Tag = '' % User tag for this object end % Public properties %% Read-only properties properties ( GetAccess = public, SetAccess = private ) Width = 0 % Width of the window Height = 0 % Height of the window end % Read-only properties %% Private properties properties ( Access = private ) Icon = [] BufferedImage = [] OriginalImage = [] Label = [] Frame = [] end % Read-only properties %% Public methods methods function obj = SplashScreen( title, imagename, varargin ) % Construct a new splash-screen object if nargin<2 error('SplashScreen:BadSyntax', 'Syntax error. You must supply both a window title and imagename.' ); end % First try to load the image as an icon fullname = iMakeFullName( imagename ); if exist(fullname,'file')~=2 % Try on the path fullname = which( imagename ); if isempty( fullname ) error('SplashScreen:BadFile', 'Image ''%s'' could not be found.', imagename ); end end % Create the interface obj.createInterfaceComponents( title, fullname ); obj.updateAll(); % Set any user-specified properties for ii=1:2:nargin-2 param = varargin{ii}; value = varargin{ii+1}; obj.(param) = value; end % If the user hasn't overridden the default, finish by putting % it onscreen if strcmpi(obj.Visible,'on') obj.Frame.setVisible(true); end end % SplashScreen function addText( obj, x, y, text, varargin ) %addText Add some text to the background image % % S.addText(X,Y,STR,...) adds some text to the splashscreen S % showing the string STR. The text is located at pixel % coordinates [X,Y]. Additional options can be set using % parameter value pairs and include: % 'Color' the font color (e.g. 'r' or [r g b]) % 'FontSize' the text size (in points) % 'FontName' the name of the font to sue (default 'Arial') % 'FontAngle' 'normal' or 'italic' % 'FontWeight' 'normal' or 'bold' % 'Shadow' 'on' or 'off' (default 'on') % % Examples: % s = SplashScreen( 'Splashscreen', 'example_splash.png' ); % s.addText( 30, 50, 'My Cool App', 'FontSize', 30, 'Color', [0 0 0.6] ) % % See also: SplashScreen % We write into the original image so that the text is % permanent gfx = obj.OriginalImage.getGraphics(); % Set the font size etc [font,color,shadow] = parseFontArguments( varargin{:} ); gfx.setFont( font ); % Switch on anti-aliasing gfx.setRenderingHint( java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON ); % Draw the text semi-transparent as a shadow if shadow gfx.setPaint( java.awt.Color.black ); ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.3 ); gfx.setComposite( ac ); gfx.drawString( text, x+1, y+2 ); ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.5 ); gfx.setComposite( ac ); gfx.drawString( text, x, y+1 ); ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.7 ); gfx.setComposite( ac ); gfx.drawString( text, x+1, y+1 ); end % Now the text itself gfx.setPaint( color ); ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 1.0 ); gfx.setComposite( ac ); gfx.drawString( text, x, y ); % Now update everything else obj.updateAll(); end % addText function delete(obj) %delete destroy this object and close all graphical components if ~isempty(obj.Frame) dispose(obj.Frame); end end % delete end % Public methods %% Data-access methods methods function val = get.Width(obj) if isempty(obj.Icon) val = 0; else val = obj.Icon.getIconWidth(); end end % get.Width function val = get.Height(obj) if isempty(obj.Icon) val = 0; else val = obj.Icon.getIconHeight(); end end % get.Height function set.Visible(obj,val) if ~ischar( val ) || ~any( strcmpi( {'on','off'}, val ) ) error( 'SplashScreen:BadValue', 'Property ''ProgressBar'' must be ''on'' or ''off''' ); end obj.Visible = lower( val ); obj.Frame.setVisible( strcmpi(val,'ON') ); %#ok<MCSUP> end % set.Visible function set.Border(obj,val) if ~ischar( val ) || ~any( strcmpi( {'on','off'}, val ) ) error( 'SplashScreen:BadValue', 'Property ''Border'' must be ''on'' or ''off''' ); end obj.Border = val; obj.updateAll(); end % set.Border function set.ProgressBar(obj,val) if ~ischar( val ) || ~any( strcmpi( {'on','off'}, val ) ) error( 'SplashScreen:BadValue', 'Property ''ProgressBar'' must be ''on'' or ''off''' ); end obj.ProgressBar = val; obj.updateProgressBar(); end % set.ProgressBar function set.ProgressRatio(obj,val) if ~isnumeric( val ) || ~isscalar( val ) || val<0 || val > 1 error( 'SplashScreen:BadValue', 'Property ''ProgressRatio'' must be a scalar between 0 and 1' ); end obj.ProgressRatio = val; obj.updateProgressBar(); end % set.ProgressRatio function set.ProgressPosition(obj,val) if ~isnumeric( val ) || ~isscalar( val ) || val<1 || val > obj.Height %#ok<MCSUP> error( 'SplashScreen:BadValue', 'Property ''ProgressPosition'' must be a vertical position inside the window' ); end obj.ProgressPosition = val; obj.updateAll(); end % set.ProgressPosition function set.Tag(obj,val) if ~ischar( val ) error( 'SplashScreen:BadValue', 'Property ''Tag'' must be a character array' ); end obj.Tag = val; end % set.Tag end % Data-access methods %% Private methods methods ( Access = private ) function createInterfaceComponents( obj, title, imageFile ) import javax.swing.*; % Load the image jImFile = java.io.File( imageFile ); try obj.OriginalImage = javax.imageio.ImageIO.read( jImFile ); catch err error('SplashScreen:BadFile', 'Image ''%s'' could not be loaded.', imageFile ); end % Read it again into the copy we'll draw on obj.BufferedImage = javax.imageio.ImageIO.read( jImFile ); % Create the icon obj.Icon = ImageIcon( obj.BufferedImage ); % Create the frame and fill it with the image obj.Frame = JFrame( title ); obj.Frame.setUndecorated( true ); obj.Label = JLabel( obj.Icon ); p = obj.Frame.getContentPane(); p.add( obj.Label ); % Resize and reposition the window obj.Frame.setSize( obj.Icon.getIconWidth(), obj.Icon.getIconHeight() ); pos = get(0,'MonitorPositions'); x0 = pos(1,1) + (pos(1,3)-obj.Icon.getIconWidth())/2; y0 = pos(1,2) + (pos(1,4)-obj.Icon.getIconHeight())/2; obj.Frame.setLocation( x0, y0 ); end % createInterfaceComponents function updateAll( obj ) % Update the entire image % Copy in the original w = obj.Frame.getWidth(); h = obj.Frame.getHeight(); gfx = obj.BufferedImage.getGraphics(); gfx.drawImage( obj.OriginalImage, 0, 0, w, h, 0, 0, w, h, [] ); % Maybe draw a border if strcmpi( obj.Border, 'on' ) % Switch on anti-aliasing gfx.setRenderingHint( java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON ); % Draw a semi-transparent rectangle for the background ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.8 ); gfx.setComposite( ac ); gfx.setPaint( java.awt.Color.black ); gfx.drawRect( 0, 0, w-1, h-1 ); end obj.updateProgressBar(); end % updateAll function updateProgressBar( obj ) % Update the progressbar and other bits % First paint over the progressbar area with the original image gfx = obj.BufferedImage.getGraphics(); border = 10; size = 6; w = obj.Frame.getWidth(); h = obj.Frame.getHeight(); py = obj.ProgressPosition; x1 = 1; y1 = h-py-size-1; x2 = w-2; y2 = h-py; gfx.drawImage( obj.OriginalImage, x1, y1, x2, y2, x1, y1, x2, y2, [] ); if strcmpi( obj.ProgressBar, 'on' ) % Draw the progress bar over the image % Switch on anti-aliasing gfx.setRenderingHint( java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON ); % Draw a semi-transparent rectangle for the background ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.25 ); gfx.setComposite( ac ); gfx.setPaint( java.awt.Color.black ); gfx.fillRoundRect( border, h-py-size, w-2*border, size, size, size ); % Now draw the foreground bit progWidth = (w-2*border-2) * obj.ProgressRatio; ac = java.awt.AlphaComposite.getInstance( java.awt.AlphaComposite.SRC_OVER, 0.5 ); gfx.setComposite( ac ); gfx.setPaint( java.awt.Color.white ); gfx.fillRoundRect( border+1, h-py-size+1, progWidth, size-2, size, size ); end % Update the on-screen image obj.Frame.repaint(); end % updateProgressBar end % Private methods end % classdef %-------------------------------------------------------------------------% function filename = iMakeFullName( filename ) % Absolute paths start with one of: % 'X:' (Windows) % '\\' (UNC) % '/' (Unix/Linux/Mac) if ~strcmp(filename(2),':') ... && ~strcmp(filename(1:2),'\\') ... && ~strcmpi(filename(1),'/') % Relative path, so add current working directory filename = fullfile( pwd(), filename ); end end % iMakeFullName function [font,color,shadow] = parseFontArguments( varargin ) % Create a java font object based on some optional inputs fontName = 'Arial'; fontSize = 12; fontWeight = java.awt.Font.PLAIN; fontAngle = 0; color = java.awt.Color.red; shadow = true; if nargin params = varargin(1:2:end); values = varargin(2:2:end); if numel( params ) ~= numel( values ) error( 'UIExtras:SplashScreen:BadSyntax', 'Optional arguments must be supplied as parameter-value pairs.' ); end for ii=1:numel( params ) switch upper( params{ii} ) case 'FONTSIZE' fontSize = values{ii}; case 'FONTNAME' fontName = values{ii}; case 'FONTWEIGHT' switch upper( values{ii} ) case 'NORMAL' fontWeight = java.awt.Font.PLAIN; case 'BOLD' fontWeight = java.awt.Font.PLAIN; otherwise error( 'UIExtras:SplashScreen:BadParameterValue', 'Unsupported FontWeight: %s.', values{ii} ); end case 'FONTANGLE' switch upper( values{ii} ) case 'NORMAL' fontAngle = 0; case 'ITALIC' fontAngle = java.awt.Font.ITALIC; otherwise error( 'UIExtras:SplashScreen:BadParameterValue', 'Unsupported FontAngle: %s.', values{ii} ); end case 'COLOR' rgb = iInterpretColor( values{ii} ); color = java.awt.Color( rgb(1), rgb(2), rgb(3) ); case 'SHADOW' if ~ischar( values{ii} ) || ~ismember( upper( values{ii} ), {'ON','OFF'} ) error( 'UIExtras:SplashScreen:BadParameter', 'Option ''Shadow'' must be ''on'' or ''off''.' ); end shadow = strcmpi( values{ii}, 'on' ); otherwise error( 'UIExtras:SplashScreen:BadParameter', 'Unsupported optional parameter: %s.', params{ii} ); end end end font = java.awt.Font( fontName, fontWeight+fontAngle, fontSize ); end % parseFontArguments function col = iInterpretColor(str) %interpretColor Interpret a color as an RGB triple % % rgb = uiextras.interpretColor(col) interprets the input color COL and % returns the equivalent RGB triple. COL can be one of: % * RGB triple of floating point numbers in the range 0 to 1 % * RGB triple of UINT8 numbers in the range 0 to 255 % * single character: 'r','g','b','m','y','c','k','w' % * string: one of 'red','green','blue','magenta','yellow','cyan','black' % 'white' % * HTML-style string (e.g. '#FF23E0') % % Examples: % >> uiextras.interpretColor( 'r' ) % ans = % 1 0 0 % >> uiextras.interpretColor( 'cyan' ) % ans = % 0 1 1 % >> uiextras.interpretColor( '#FF23E0' ) % ans = % 1.0000 0.1373 0.8784 % % See also: ColorSpec % Copyright 2005-2010 The MathWorks Ltd. % $Revision: 327 $ % $Date: 2010-08-26 09:53:11 +0100 (Thu, 26 Aug 2010) $ if ischar( str ) str = strtrim(str); str = dequote(str); if str(1)=='#' % HTML-style string if numel(str)==4 col = [hex2dec( str(2) ), hex2dec( str(3) ), hex2dec( str(4) )]/15; elseif numel(str)==7 col = [hex2dec( str(2:3) ), hex2dec( str(4:5) ), hex2dec( str(6:7) )]/255; else error( 'UIExtras:interpretColor:BadColor', 'Invalid HTML color %s', str ); end elseif all( ismember( str, '1234567890.,; []' ) ) % Try the '[0 0 1]' thing first col = str2num( str ); %#ok<ST2NM> if numel(col) == 3 % Conversion worked, so just check for silly values col(col<0) = 0; col(col>1) = 1; end else % that didn't work, so try the name switch upper(str) case {'R','RED'} col = [1 0 0]; case {'G','GREEN'} col = [0 1 0]; case {'B','BLUE'} col = [0 0 1]; case {'C','CYAN'} col = [0 1 1]; case {'Y','YELLOW'} col = [1 1 0]; case {'M','MAGENTA'} col = [1 0 1]; case {'K','BLACK'} col = [0 0 0]; case {'W','WHITE'} col = [1 1 1]; case {'N','NONE'} col = [nan nan nan]; otherwise % Failed error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) ); end end elseif isfloat(str) || isdouble(str) % Floating point, so should be a triple in range 0 to 1 if numel(str)==3 col = double( str ); col(col<0) = 0; col(col>1) = 1; else error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) ); end elseif isa(str,'uint8') % UINT8, so range is implicit if numel(str)==3 col = double( str )/255; col(col<0) = 0; col(col>1) = 1; else error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) ); end else error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) ); end end % iInterpretColor function str = dequote(str) str(str=='''') = []; str(str=='"') = []; str(str=='[') = []; str(str==']') = []; end % dequote
github
peterspat/handeyecalibration-master
getAllSections.m
.m
handeyecalibration-master/app/configuration/getAllSections.m
246
utf_8
6819ab110aa72dac5bcdf49133860aaf
% Read all section from ini file % fileDir: File path to *.ini function [ sections ] = getAllSections( fileDir ) if ~isempty(fileDir) sections = readConfig(fileDir, 'Sections'); else fprintf('File dir %s is empty!', fileDir); end end
github
peterspat/handeyecalibration-master
readConfig.m
.m
handeyecalibration-master/app/configuration/readConfig.m
427
utf_8
02bc150af09c0b5e5b120f900661adc0
% Read an ini file % fileDir: File path % sectionName: Section to read, 'Sections' reads all sections function [ sectionData ] = readConfig( fileDir, sectionName ) if ~isempty(fileDir) && ~isempty(sectionName) I = INI('File', fileDir); I.read(); sectionData = I.get(char(sectionName)); else fprintf('Please specify a valid file path: %s or a valid section name: %s', fileDir, sectionName); end end
github
peterspat/handeyecalibration-master
checkNameProperty.m
.m
handeyecalibration-master/app/configuration/checkNameProperty.m
270
utf_8
289bd240736649cbc4e7f2870c0b4fc6
% Check if struct contains a name property % testStruct: Struct to test % default: Default name function [ structName ] = checkNameProperty( testStruct, default ) if isfield(testStruct, 'name') structName = testStruct.name; else structName = default; end end
github
peterspat/handeyecalibration-master
writeConfig.m
.m
handeyecalibration-master/app/configuration/writeConfig.m
487
utf_8
84358b69c9351b3729088603eb949c40
% Write data to an ini file % fileDir: File path % sectionName: Section(s) to write % sectionData: Data of section(s) function [ ] = writeConfig( fileDir, sectionName, sectionData ) if ~isempty(sectionName) && ~isempty(sectionData) && ~isempty(fileDir) I = INI(); for i = 1:length(sectionName) I.add(char(sectionName(i)), sectionData{i}); end I.write(fileDir); else error('Dims of section names and data are different or file path is empty'); end end
github
peterspat/handeyecalibration-master
startSimulation.m
.m
handeyecalibration-master/app/simulation/startSimulation.m
192
utf_8
c8e03cd345265f420af0a45e9ffa0322
% Start simulation % simCon: Struct with simulation vars function [] = startSimulation( simCon ) ret = simCon.vrep.simxStartSimulation(simCon.clientID, simCon.vrep.simx_opmode_oneshot); end
github
peterspat/handeyecalibration-master
getSimTcpPose.m
.m
handeyecalibration-master/app/simulation/getSimTcpPose.m
543
utf_8
4dee1682a2320fd172fb81906a0c8fe5
% Get current TCP pose from simulation % simCon: Struct with simulation vars function [res, tcpPose] = getSimTcpPose(simCon) [errTcp, positionTcp] = simCon.vrep.simxGetObjectPosition(simCon.clientID, simCon.tcpHandle, simCon.baseHandle,... simCon.vrep.simx_opmode_streaming); [errTcpOrient, orientationTcp] = simCon.vrep.simxGetObjectOrientation(simCon.clientID, simCon.tcpHandle,... -1, simCon.vrep.simx_opmode_streaming); res = ~(errTcp && errTcpOrient); if res tcpPose = convertSimData(orientationTcp, positionTcp); end end
github
peterspat/handeyecalibration-master
initialiseSimHandles.m
.m
handeyecalibration-master/app/simulation/initialiseSimHandles.m
1,603
utf_8
c3e9ffc4d915a66369d50fea7910b5e3
% Initialize simulation handles % simCon: Struct with simulation vars function [err, simCon] = initialiseSimHandles(simCon) % Error handling? [errVisionHandle, simCon.visionHandle] = simCon.vrep.simxGetObjectHandle(simCon.clientID, 'Vision_sensor#', simCon.vrep.simx_opmode_blocking); [errBaseHandle, simCon.baseHandle] = simCon.vrep.simxGetObjectHandle(simCon.clientID, 'base_dummy#', simCon.vrep.simx_opmode_blocking); [errTcpHandle, simCon.tcpHandle] = simCon.vrep.simxGetObjectHandle(simCon.clientID, 'tcp_dummy#', simCon.vrep.simx_opmode_blocking); [errGridHandle, simCon.gridHandle] = simCon.vrep.simxGetObjectHandle(simCon.clientID, 'grid_dummy#', simCon.vrep.simx_opmode_blocking); [errCameraHandle, simCon.cameraHandle] = simCon.vrep.simxGetObjectHandle(simCon.clientID, 'camera_dummy#', simCon.vrep.simx_opmode_blocking); % call these actions cause they trhow an error at first call simCon.vrep.simxGetObjectPosition(simCon.clientID, simCon.tcpHandle, simCon.baseHandle, simCon.vrep.simx_opmode_streaming); simCon.vrep.simxGetObjectOrientation(simCon.clientID, simCon.tcpHandle, -1, simCon.vrep.simx_opmode_streaming); simCon.vrep.simxGetObjectOrientation(simCon.clientID, simCon.cameraHandle, simCon.gridHandle, simCon.vrep.simx_opmode_streaming); simCon.vrep.simxGetObjectPosition(simCon.clientID, simCon.cameraHandle, simCon.gridHandle, simCon.vrep.simx_opmode_streaming); simCon.vrep.simxGetVisionSensorImage2(simCon.clientID, simCon.visionHandle, 0, simCon.vrep.simx_opmode_streaming); err = ~(errBaseHandle &&errVisionHandle && errTcpHandle && errGridHandle && errCameraHandle); end
github
peterspat/handeyecalibration-master
stopSimulation.m
.m
handeyecalibration-master/app/simulation/stopSimulation.m
343
utf_8
c426226268561c2826a09a585232e1e1
% Stop simulatin % Disconnect % simCon: Struct with simulation vars function [] = stopSimulation( simCon ) simCon.vrep.simxStopSimulation(simCon.clientID, simCon.vrep.simx_opmode_oneshot); %close connection simCon.vrep.simxGetPingTime(simCon.clientID); %make sure the last command could be sent simCon.vrep.simxFinish(simCon.clientID); end
github
peterspat/handeyecalibration-master
setTcpPose.m
.m
handeyecalibration-master/app/simulation/setTcpPose.m
587
utf_8
60b3e44bf5bbdf0d52b04e64bb6e9926
% Set a TCP pose in simulation % simCon: Struct with simulation vars % tcpPose: TCP pose to simulate function [res] = setTcpPose( simCon, tcpPose ) errSetTcpOrientation = simCon.vrep.simxSetObjectOrientation(simCon.clientID, simCon.tcpHandle, simCon.baseHandle, deg2rad(tcpPose(4:6)), simCon.vrep.simx_opmode_oneshot); errSetTcpPos = simCon.vrep.simxSetObjectPosition(simCon.clientID, simCon.tcpHandle, simCon.baseHandle, tcpPose(1:3), simCon.vrep.simx_opmode_oneshot); res = 1;%errSetTcpPos && errSetTcpOrientation; %checking if sim arrived ???? pause(1); end
github
peterspat/handeyecalibration-master
convertSimData.m
.m
handeyecalibration-master/app/simulation/convertSimData.m
879
utf_8
1e857a4885b9f376895f1bc006f35668
% Create a 4x4 hom matrix with converted orientaion for MATLAB % Orientation has to be in ZYX % simPosition: Simulated position of tcp % simOrientation: Simulated orientation of tcp function [ tcpPose ] = convertSimData(simPosition, simOrientation) rotationX = [ 1 0 0; 0 cos(simOrientation(1)) -sin(simOrientation(1)); 0 sin(simOrientation(1)) cos(simOrientation(1))]; rotationY = [ cos(simOrientation(2)) 0 sin(simOrientation(2)) 0 1 0; -sin(simOrientation(2)) 0 cos(simOrientation(2))]; rotationZ = [ cos(simOrientation(3)) -sin(simOrientation(3)) 0; sin(simOrientation(3)) cos(simOrientation(3)) 0; 0 0 1]; rotm = rotationX * rotationY * rotationZ; tcpPose = rotm2tform(rotm); tcpPose(1,4) = simPosition(1); tcpPose(2,4) = simPosition(2); tcpPose(3,4) = simPosition(3); end
github
peterspat/handeyecalibration-master
connectToSimulation.m
.m
handeyecalibration-master/app/simulation/connectToSimulation.m
226
utf_8
e786f52bdbd44cd550dfcdfd3b9d89de
% Connect to simulation using API function [simCon] = connectToSimulation() simCon.vrep = remApi('remoteApi'); simCon.vrep.simxFinish(-1); simCon.clientID = simCon.vrep.simxStart('127.0.0.1', 19997, true, true, 5000, 5); end
github
peterspat/handeyecalibration-master
takePictureSimulation.m
.m
handeyecalibration-master/app/simulation/takePictureSimulation.m
928
utf_8
bf4fbec845910aa4ffcc93e2bf31d62f
% Capture a picture from simulated camera % simCon: Struct with simulation vars % imageNumber: Number to enumerate images % filePath: Path to store images function [res, imgPath, imgName] = takePictureSimulation(simCon, imageNumber, filePath ) %Error? [err, ~, image] = simCon.vrep.simxGetVisionSensorImage2(simCon.clientID,... simCon.visionHandle, 0, simCon.vrep.simx_opmode_streaming); if (imageNumber < 10) path = [filePath '\capture_0' int2str(imageNumber) '.png']; else path = [filePath '\capture_' int2str(imageNumber) '.png']; end [imgPath, imgName, ext] = fileparts(path); imgName = [imgName ext]; imgPath = [imgPath '\' imgName]; if ~err && ~isempty(image) imwrite(image, path); res = 1; else res = 1; end imgName = cellstr(imgName); imgPath = cellstr(imgPath); end
github
peterspat/handeyecalibration-master
rpyToRotationMatrix.m
.m
handeyecalibration-master/app/utils/rpyToRotationMatrix.m
496
utf_8
94cceeb29ec6b80214caa8497a521f36
% Create a 3x3 matrix from RPY % angleRoll: Roll in deg % anglePitch: Pitch in deg % angleYaw: Yaw in deg function matrix = rpyToRotationMatrix( angleRoll, anglePitch, angleYaw ) rz = [cosd(angleYaw) -sind(angleYaw) 0 ; sind(angleYaw) cosd(angleYaw) 0; 0 0 1]; ry = [ cosd(anglePitch) 0 sind(anglePitch); 0 1 0; -sind(anglePitch) 0 cosd(anglePitch) ]; rx = [ 1 0 0; 0 cosd(angleRoll) -sind(angleRoll); 0 sind(angleRoll) cosd(angleRoll)]; matrix = rz*ry*rx; end
github
peterspat/handeyecalibration-master
rotationMatrixToRPY.m
.m
handeyecalibration-master/app/utils/rotationMatrixToRPY.m
300
utf_8
44b80f2dc7353e596c69aa72098cba5e
% Convert a 3x3 matrix to RPY % homMatrix: 3x3 matrix function [ roll, pitch, yaw ] = rotationMatrixToRPY( homMatrix ) %roll, pitch, yaw in degrees quat = rotm2quat(homMatrix(1:3, 1:3)); [yaw, pitch, roll] = quat2angle(quat); yaw = rad2deg(yaw); pitch = rad2deg(pitch); roll = rad2deg(roll); end
github
peterspat/handeyecalibration-master
intrinsicCalib.m
.m
handeyecalibration-master/app/calibration/intrinsicCalib.m
2,491
utf_8
75cc9a9a60fa7069a5df7a94df8802bb
% Computes intrinsic calibration based on input images % calibImgPaths: Pathvector to input images % tileSize: Checkerboard tile size % untes: Calibration units (m or mm) function [cameraParams, imagesUsed, correctedPoses, estimationErrors] = intrinsicCalib(calibImgPaths, tileSize, units) % Detect checkerboards in images [imagePoints, boardSize, imagesUsed] = detectCheckerboardPoints(calibImgPaths, 'showProgressBar', 1); calibImgPaths = calibImgPaths(imagesUsed); %checken!!! % Generate world coordinates of the corners of the squares % in units worldPoints = generateCheckerboardPoints(boardSize, tileSize); % Load one image to get size img = imread(calibImgPaths{1}); imgSize = size(img); % Calibrate the camera [cameraParams, imagesUsedErrors, estimationErrors] = estimateCameraParameters(imagePoints, worldPoints, ... 'EstimateSkew', true, 'EstimateTangentialDistortion', true, ... 'NumRadialDistortionCoefficients', 3, 'WorldUnits', units, ... 'InitialIntrinsicMatrix', [], 'InitialRadialDistortion', [], 'ImageSize', imgSize(1:2)); % Remove all images depending on errors j = 1; for i = 1:length(imagesUsed) if (imagesUsed(i)) if (imagesUsedErrors(j) == 0) imagesUsed(i) = 0; end j = j + 1; end end total = size(imagesUsedErrors, 1); h = waitbar(0, ['Adjusting extrinsics for image: 1 of ' num2str(total)],... 'Name', 'Undistorting image origins'); % Undistort image origins for i = 1:total waitbar(i/total, h, ['Adjusting extrinsics for image: ' num2str(i) ' of ' num2str(total)]); if imagesUsedErrors(i) orgImg = imread(calibImgPaths{i}); [img, newOrigin] = undistortImage(orgImg, cameraParams, 'OutputView', 'full'); [imagePoints(:,:,i), ~] = detectCheckerboardPoints(img); imagePoints(:,:,i) = [imagePoints(:,1, i) + newOrigin(1), ... imagePoints(:,2,i) + newOrigin(2)]; % Save new calibration data [correctedOrientationMatrix, correctedTranslationVector] = extrinsics(... imagePoints(:,:,i), worldPoints, cameraParams); correctedPoses.correctedOrientationMatrix(:,:,i) = correctedOrientationMatrix; correctedPoses.correctedTranslationVector(:,:,i) = correctedTranslationVector; end end delete(h); end
github
peterspat/handeyecalibration-master
handEyeCalibrationTSAI.m
.m
handeyecalibration-master/app/calibration/handEyeCalibrationTSAI.m
1,874
utf_8
d0a4277e76eeafc8fcac1275700d304e
% Computes hand eye calibration with Wengert and Lazax implementation % Removes all poses based on reject images by intrinsic calibration % cartCalibPoses: Cartesian calibration poses % correctedPoeses: Corrected cartesian calibration poses % imagesUsed: Mask (vector) with rejected and accepted images function [ handEyeWengert, handEyeLazax ] = handEyeCalibrationTSAI( cartCalibPoses, correctedPoses, imagesUsed) % Set counter j = 1; for i = 1:size(cartCalibPoses, 1) if imagesUsed(i) % Convert to hom matrix pose = cartCalibPoses(j,:); X = pose(1); Y = pose(2); Z = pose(3); Roll = pose(4); Pitch = pose(5); Yaw = pose(6); rotationMatrix = rpyToRotationMatrix(Roll, Pitch, Yaw); tform = rotm2tform(rotationMatrix); tform(1,4) = X; tform(2,4) = Y; tform(3,4) = Z; tcpPoseInBaseCoords(:,:,j) = tform; j = j + 1; end end % Set counter j = 1; for i = 1:size(imagesUsed) if imagesUsed(i) % Convert to hom matrix gridPoseInCameraCoordsCorrected(:,:,j) = rotm2tform(inv(correctedPoses.correctedOrientationMatrix(:,:,j))); gridPoseInCameraCoordsCorrected(1,4,j) = correctedPoses.correctedTranslationVector(:,1,j); gridPoseInCameraCoordsCorrected(2,4,j) = correctedPoses.correctedTranslationVector(:,2,j); gridPoseInCameraCoordsCorrected(3,4,j) = correctedPoses.correctedTranslationVector(:,3,j); cameraPoseInGridCoordsCorrected(:,:,j) = inv(gridPoseInCameraCoordsCorrected(:,:,j)); j = j + 1; end end % Compute hand eye calibration handEyeWengert = TSAIleastSquareCalibration(tcpPoseInBaseCoords, gridPoseInCameraCoordsCorrected); handEyeLazax = HandEye(tcpPoseInBaseCoords, cameraPoseInGridCoordsCorrected); end
github
peterspat/handeyecalibration-master
skew.m
.m
handeyecalibration-master/app/calibration/hand_eye_lazax/skew.m
313
utf_8
1ffb7c9e3ac57fd105e333a17e4fffdc
% skew - returns skew matrix of a 3x1 vector. % cross(V,U) = skew(V)*U % % S = skew(V) % % 0 -Vz Vy % S = Vz 0 -Vx % -Vy Vx 0 % % See also: cross function S = skew(V) S = [ 0 -V(3) V(2) V(3) 0 -V(1) -V(2) V(1) 0 ]; return
github
peterspat/handeyecalibration-master
transl.m
.m
handeyecalibration-master/app/calibration/hand_eye_lazax/transl.m
781
utf_8
ff802c2504225549449b1ebf4ec39c92
%TRANSL Translational transform % % T= TRANSL(X, Y, Z) % T= TRANSL( [X Y Z] ) % % [X Y Z]' = TRANSL(T) % % [X Y Z] = TRANSL(TG) % % Returns a homogeneous transformation representing a % translation of X, Y and Z. % % The third form returns the translational part of a % homogenous transform as a 3-element column vector. % % The fourth form returns a matrix of the X, Y and Z elements % extracted from a Cartesian trajectory matrix TG. % % See also ROTX, ROTY, ROTZ, ROTVEC. % Copyright (C) Peter Corke 1990 function r = transl(x, y, z) if nargin == 1, if ishomog(x), r = x(1:3,4); elseif numcols(x) == 16, r = x(:,13:15); else t = x(1:3); r = [eye(3) t; 0 0 0 1]; end elseif nargin == 3, t = [x; y; z]; r = [eye(3) t; 0 0 0 1]; end
github
peterspat/handeyecalibration-master
ishomog.m
.m
handeyecalibration-master/app/calibration/hand_eye_lazax/ishomog.m
120
utf_8
9e91b52f6191f56268e36e6b17c5c26f
%ISHOMOG test if argument is a homogeneous transformation (4x4) function h = ishomog(tr) h = all(size(tr) == [4 4]);
github
peterspat/handeyecalibration-master
HandEye.m
.m
handeyecalibration-master/app/calibration/hand_eye_lazax/HandEye.m
3,686
utf_8
4a3056c97c55081a586cefacff970721
% handEye - performs hand/eye calibration % % gHc = handEye(bHg, wHc) % % bHg - pose of gripper relative to the robot base.. % (Gripper center is at: g0 = Hbg * [0;0;0;1] ) % Matrix dimensions are 4x4xM, where M is .. % .. number of camera positions. % Algorithm gives a non-singular solution when .. % .. at least 3 positions are given % Hbg(:,:,i) is i-th homogeneous transformation matrix % wHc - pose of camera relative to the world .. % (relative to the calibration block) % Dimension: size(Hwc) = size(Hbg) % gHc - 4x4 homogeneous transformation from gripper to camera % , that is the camera position relative to the gripper. % Focal point of the camera is positioned, .. % .. relative to the gripper, at % f = gHc*[0;0;0;1]; % % References: R.Tsai, R.K.Lenz "A new Technique for Fully Autonomous % and Efficient 3D Robotics Hand/Eye calibration", IEEE % trans. on robotics and Automaion, Vol.5, No.3, June 1989 % % Notation: wHc - pose of camera frame (c) in the world (w) coordinate system % .. If a point coordinates in camera frame (cP) are known % .. wP = wHc * cP % .. we get the point coordinates (wP) in world coord.sys. % .. Also refered to as transformation from camera to world % function gHc = handEye(bHg, wHc) M = size(bHg,3); K = (M*M-M)/2; % Number of unique camera position pairs A = zeros(3*K,3); % will store: skew(Pgij+Pcij) B = zeros(3*K,1); % will store: Pcij - Pgij k = 0; % Now convert from wHc notation to Hc notation used in Tsai paper. Hg = bHg; % Hc = cHw = inv(wHc); We do it in a loop because wHc is given, not cHw Hc = zeros(4,4,M); for i = 1:M, Hc(:,:,i) = inv(wHc(:,:,i)); end; for i = 1:M, for j = i+1:M; Hgij = inv(Hg(:,:,j))*Hg(:,:,i); % Transformation from i-th to j-th gripper pose Pgij = 2*rot2quat(Hgij); % ... and the corresponding quaternion Hcij = Hc(:,:,j)*inv(Hc(:,:,i)); % Transformation from i-th to j-th camera pose Pcij = 2*rot2quat(Hcij); % ... and the corresponding quaternion k = k+1; % Form linear system of equations A((3*k-3)+(1:3), 1:3) = skew(Pgij+Pcij); % left-hand side B((3*k-3)+(1:3)) = Pcij - Pgij; % right-hand side end; end; % Rotation from camera to gripper is obtained from the set of equations: % skew(Pgij+Pcij) * Pcg_ = Pcij - Pgij % Gripper with camera is first moved to M different poses, then the gripper % .. and camera poses are obtained for all poses. The above equation uses % .. invariances present between each pair of i-th and j-th pose. Pcg_ = A \ B; % Solve the equation A*Pcg_ = B % Obtained non-unit quaternin is scaled back to unit value that % .. designates camera-gripper rotation Pcg = 2 * Pcg_ / sqrt(1 + Pcg_'*Pcg_); Rcg = quat2rot(Pcg/2); % Rotation matrix % Calculate translational component k = 0; for i = 1:M, for j = i+1:M; Hgij = inv(Hg(:,:,j))*Hg(:,:,i); % Transformation from i-th to j-th gripper pose Hcij = Hc(:,:,j)*inv(Hc(:,:,i)); % Transformation from i-th to j-th camera pose k = k+1; % Form linear system of equations A((3*k-3)+(1:3), 1:3) = Hgij(1:3,1:3)-eye(3); % left-hand side B((3*k-3)+(1:3)) = Rcg(1:3,1:3)*Hcij(1:3,4) - Hgij(1:3,4); % right-hand side end; end; Tcg = A \ B; gHc = transl(Tcg) * Rcg; % incorporate translation with rotation return
github
peterspat/handeyecalibration-master
rot2quat.m
.m
handeyecalibration-master/app/calibration/hand_eye_lazax/rot2quat.m
559
utf_8
17bdf7e834443b999dad81f1941d8c5b
% rot2quat - converts a rotation matrix (3x3) to a unit quaternion(3x1) % % q = rot2quat(R) % % R - 3x3 rotation matrix, or 4x4 homogeneous matrix % q - 3x1 unit quaternion % q = sin(theta/2) * v % teta - rotation angle % v - unit rotation axis, |v| = 1 % % % See also: quat2rot, rotx, roty, rotz, transl, rotvec function q = rot2quat(R) w4 = 2*sqrt( 1 + trace(R(1:3,1:3)) ); % can this be imaginary? q = [ ( R(3,2) - R(2,3) ) / w4; ( R(1,3) - R(3,1) ) / w4; ( R(2,1) - R(1,2) ) / w4; ]; return
github
peterspat/handeyecalibration-master
numcols.m
.m
handeyecalibration-master/app/calibration/hand_eye_lazax/numcols.m
108
utf_8
065bc5186f4187d9937109be1e3194f6
% % NUMCOLS(m) % % Return the number of columns in the matrix m % function c = numcols(m) [x,c] = size(m);
github
peterspat/handeyecalibration-master
quat2rot.m
.m
handeyecalibration-master/app/calibration/hand_eye_lazax/quat2rot.m
641
utf_8
f35d0832ae79ccda637f8f65f5d4705d
% quat2rot - a unit quaternion(3x1) to converts a rotation matrix (3x3) % % R = quat2rot(q) % % q - 3x1 unit quaternion % R - 4x4 homogeneous rotation matrix (translation component is zero) % q = sin(theta/2) * v % teta - rotation angle % v - unit rotation axis, |v| = 1 % % See also: rot2quat, rotx, roty, rotz, transl, rotvec function R = quat2rot(q) p = q'*q; if( p > 1 ), disp('Warning: quat2rot: quaternion greater than 1'); end w = sqrt(1 - p); % w = cos(theta/2) R = eye(4); R(1:3,1:3) = 2*q*q' + 2*w*skew(q) + eye(3) - 2*diag([p p p]); return
github
peterspat/handeyecalibration-master
crossprod.m
.m
handeyecalibration-master/app/calibration/handy_eye_wengert/crossprod.m
785
utf_8
5003fcd4c9985c427422dada94d1cadb
%Defines the crossproduct as defined in hartley and zisserman % [e2]x = as defined on p554 = [ 0,-e3,e2; % e3,0,-e1; % -e2.e1.0 ] % %Author: Christian Wengert, % Institute of Computer Vision % Swiss Federale Institute of Technology, Zurich (ETHZ) % [email protected] % www.vision.ee.ethz.ch/~cwengert/ % %Input: a A Vector (3x1) % %Output: ax The matrix [a]x as defined above % %Syntax: ax = crossprod(a) function ax = crossprod(a) if(size(a,1) ~= 3 & size(a,2) ~= 1) error ('crossprod::Please specify an valid argument.'); end ax = [ 0,-a(3,1),a(2,1);a(3,1),0,-a(1,1);-a(2,1),a(1,1),0 ];
github
peterspat/handeyecalibration-master
TSAIleastSquareCalibration.m
.m
handeyecalibration-master/app/calibration/handy_eye_wengert/TSAIleastSquareCalibration.m
3,251
utf_8
3494e4560a73c011d5d50c374452a10d
%This computes the hand-eye calibration using Tsai and Lenz' method %see the paper "A New Technique for Fully Autonomous and Efficient 3D %Robotics Hand-Eye Calibration, Tsai, R.Y. and Lenz, R.K" for further %details % %Input: %Hmarker2world a 4x4xNumber_of_Views Matrix of the form % Hmarker2world(:,:,i) = [Ri_3x3 ti_3x1;[ 0 0 0 1]] % with % i = number of the view, % Ri_3x3 the rotation matrix % ti_3x1 the translation vector. % Defining the transformation of the robot hand / marker % to the robot base / external tracking device %Hgrid2cam a 4x4xNumber_of_Views Matrix (like above) % Defining the transformation of the grid to the camera % %Output: %Hcam2marker_ The transformation from the camera to the marker / % robot arm %err The residuals from the least square processes % %Christian Wengert %Computer Vision Laboratory %ETH Zurich %Sternwartstrasse 7 %CH-8092 Zurich %www.vision.ee.ethz.ch/cwengert %[email protected] function [Hcam2marker_, err] = TSAIleastSquareCalibration(Hmarker2world, Hgrid2cam) A = []; n = size(Hgrid2cam,3); for i=1:n-1 %we have n-1 linearly independent relations between the views %Transformations between views Hgij(:,:,i) = inv(Hmarker2world(:,:,i+1))*Hmarker2world(:,:,i); Hcij(:,:,i) = Hgrid2cam(:,:,i+1)*inv(Hgrid2cam(:,:,i)); %turn it into angle axis representation (rodrigues formula: P is %the eigenvector of the rotation matrix with eigenvalue 1 rgij = rodrigues(Hgij(1:3,1:3,i)); rcij = rodrigues(Hcij(1:3,1:3,i)); theta_gij = norm(rgij); theta_cij = norm(rcij); rngij = rgij/theta_gij; rncij = rcij/theta_cij; %Tsai uses a modified version of this Pgij = 2*sin(theta_gij/2)*rngij; Pcij = 2*sin(theta_cij/2)*rncij; %Now we know that %skew(Pgij+Pcij)*x = Pcij-Pgij which is equivalent to Ax = b %So we need to construct vector b and matrix A to solve this %overdetermined system. (Note we need >=3 Views to have at least 2 %linearly independent inter-view relations. A(3*(i-1)+1:i*3,1:3) = crossprod(Pgij+Pcij); b(3*(i-1)+1:i*3) = Pcij-Pgij; end %Computing Rotation Pcg_prime = pinv(A)*b'; %Computing residus err = A*Pcg_prime-b'; residus_TSAI_rotation = sqrt(sum((err'*err))/(n-1)); Pcg = 2*Pcg_prime/(sqrt(1+norm(Pcg_prime)^2)); Rcg = (1-norm(Pcg)*norm(Pcg)/2)*eye(3)+0.5*(Pcg*Pcg'+sqrt(4-norm(Pcg)*norm(Pcg))*crossprod(Pcg)); A = []; b = []; %Computing Translation for i=1:n-1 A(3*(i-1)+1:i*3,1:3) = (Hgij(1:3,1:3,i) - eye(3)); b(3*(i-1)+1:i*3) = Rcg*Hcij(1:3,4,i) - Hgij(1:3,4,i); end Tcg = pinv(A)*b'; %Computing residus err = A*Tcg-b'; residus_TSAI_translation = sqrt(sum((err'*err))/(n-1)); %Estimated transformation Hcam2marker_ = [Rcg Tcg;[0 0 0 1]]; if(nargout==2) err = [residus_TSAI_rotation;residus_TSAI_translation]; end
github
peterspat/handeyecalibration-master
rosConnection.m
.m
handeyecalibration-master/app/robot/rosConnection.m
713
utf_8
d3bb04ea30dbdd628f7b9a6253c35d27
% Connect to ROS % masterIp: IP of rosmaster % localhosIp: Local IP % nodeName: Name of connecting node function [ rosCon ] = rosConnection(masterIp, localhosIp, nodeName) %ROS simple MATLAB connection % Start rosshutdown; rosinit(masterIp, 'NodeHost',localhosIp,'NodeName',nodeName); % Init Subscribers / Publishers and store them rosCon.subCartLWR1 = rossubscriber('/robots/lwr1/get_cartesian','geometry_msgs/Pose'); rosCon.pubCartLWR1 = rospublisher('/robots/lwr1/set_cartesian','geometry_msgs/Pose'); rosCon.subJointsLWR1 = rossubscriber('/robots/lwr1/get_joint','sensor_msgs/JointState'); [rosCon.pubJointsLWR1, rosCon.jointsLWR1] = rospublisher('/robots/lwr1/set_joint','sensor_msgs/JointState'); end
github
peterspat/handeyecalibration-master
moveRobotToJointAngles.m
.m
handeyecalibration-master/app/robot/moveRobotToJointAngles.m
555
utf_8
c556560501b466ee015284ab2a8e4896
% Move robot to joint angles using ROS % rosCon: Struct with ROS vars % jointAngles: Robot joint angles % vel: Robot velocity function [ res ] = moveRobotToJointAngles( rosCon, jointAngles, vel) res = 1; if length(jointAngles) == 7 rosCon.jointsLWR1.Position = jointAngles; rosCon.jointsLWR1.Velocity = [vel; vel; vel; vel; vel; vel; vel;]; else res = 0; end if isfield(rosCon, 'pubJointsLWR1') && res send(rosCon.pubJointsLWR1, rosCon.jointsLWR1); reachedRobotJointAngles(rosCon, jointAngles, 0.0017); else res = 0; end end
github
peterspat/handeyecalibration-master
takePictureRobot.m
.m
handeyecalibration-master/app/robot/takePictureRobot.m
616
utf_8
bd202700e1c3c0956695317d2312ba4a
% Capture a picture from a camera mounted on the robot % shutterSpeed: Speed of shutter % gain: Camera gain % imagePath: Path to store image function [imgPath, imgName] = takePictureRobot(shutterSpeed, gain, imagePath) % shutterSpeed [ms], gain [db], metadata [struct] metadata.sequence.saveDir = imagePath; url = 'http://localhost/capture?shutter='; url = [url num2str(shutterSpeed) '&gain=' num2str(gain)]; options = weboptions('MediaType','application/json'); ret = webwrite(url, metadata, options); imgName = ret(strfind(ret,'capture_'):end); imgPath = strcat(metadata.sequence.saveDir,'\',imgName ,'.png'); end
github
peterspat/handeyecalibration-master
getOrientationFromRPY.m
.m
handeyecalibration-master/app/robot/getOrientationFromRPY.m
460
utf_8
93e47455e67491680f25f42a2d5c9363
% Compute orientation for ROS quaternion from RPY in degrees % rollDegrees: Roll in deg % pitchDegrees: Pitch in deg % yawDegrees: Yaw in deg function orientation = getOrientationFromRPY(rollDegrees, pitchDegrees, yawDegrees) quat = angle2quat(deg2rad(yawDegrees),deg2rad(pitchDegrees),deg2rad(rollDegrees)); orientation=rosmessage('geometry_msgs/Quaternion'); orientation.X=quat(2); orientation.Y=quat(3); orientation.Z=quat(4); orientation.W=quat(1); end
github
peterspat/handeyecalibration-master
reachedRobotJointAngles.m
.m
handeyecalibration-master/app/robot/reachedRobotJointAngles.m
596
utf_8
ebb33ab452857b51860cd22d3c6e3be6
% Check if robot has reached target joint angels % rosCon: Struct with ROS vars % targetJointAngles: Joint angles to reach % precision: Succes stopping condition (err <= precision) function [ res ] = reachedRobotJointAngles( rosCon, targetJointAngles, precision ) res = 0; robotPose = getRobotPose(rosCon); if length(robotPose.Joints) == length(targetJointAngles) while ~res robotPose = getRobotPose(rosCon); diff = abs(robotPose.Joints - transpose(targetJointAngles)) <= precision; res = sum(diff) == length(targetJointAngles); pause(1); end end end
github
peterspat/handeyecalibration-master
moveRobotToCartPose.m
.m
handeyecalibration-master/app/robot/moveRobotToCartPose.m
434
utf_8
731d8009f0816c5b59c86779c037f022
% Move the robot to a cart pose using ROS % rosCon: Struct with ROS vars % pose: Cartesian poose function [res] = moveRobotToCartPose( rosCon, pose ) res = 1; cartLWR1.Position.X = pose(1); cartLWR1.Position.Y = pose(2); cartLWR1.Position.Z = pose(3); cartLWR1.Orientation = getOrientationFromRPY(pose(4), pose(5), pose(6)); if exist('rosCon.pubCartLWR1', 'var') send(rosCon.pubCartLWR1,cartLWR1); else res = 0; end end
github
peterspat/handeyecalibration-master
getRPYFromROSPose.m
.m
handeyecalibration-master/app/robot/getRPYFromROSPose.m
281
utf_8
436d5deb21db9e297099619a0ee21f7d
% Compute RPY from ROS pose % pose: ROS pose function [roll, pitch, yaw] = getRPYFromROSPose(pose) [yaw, pitch, roll] = quat2angle([pose.Orientation.W pose.Orientation.X pose.Orientation.Y pose.Orientation.Z]); roll = rad2deg(roll); pitch = rad2deg(pitch); yaw = rad2deg(yaw); end
github
peterspat/handeyecalibration-master
getRobotPose.m
.m
handeyecalibration-master/app/robot/getRobotPose.m
458
utf_8
043a4de9c7da9da2615236930ce1cdc9
% Get current robot pose from ROS % Store joint angles and cart pose function [ robotPose ] = getRobotPose( rosCon ) cartLWR1 = receive(rosCon.subCartLWR1); jointsLWR1 = receive(rosCon.subJointsLWR1); [roll, pitch, yaw] = getRPYFromROSPose(cartLWR1); % Store cart pose as a vector robotPose.Cart = [cartLWR1.Position.X, cartLWR1.Position.Y, cartLWR1.Position.Z,... roll, pitch, yaw]; robotPose.Joints = jointsLWR1.Position; end
github
panji530/Maximizing-rigidity-revisited-master
getAngleCos.m
.m
Maximizing-rigidity-revisited-master/getAngleCos.m
978
utf_8
9b3f7e48885380519b2a1e9a38ceb781
% This work was done while the first author was in the University of Adelaide. Copyright reserved. function C = getAngleCos(m, NgIdx) % compute the negative cosine of angles between legs % Inputs: m -- 2D image coordinates % NgIdx -- index of neighbors of each point % KK -- intrinsic camera matrix % Output: C -- matrix containing the consine of angles % Author: Pan Ji, University of Adelaide F = length(m); % number of frames N = length(m(1).m); % number of points %Sn = size(NgIdx,2); C = struct([]); for f = 1:F tmp_C = eye(N,N); X = m(f).m; % normalised image coordinates of the current frame X_bar = [X;ones(1,N)]; % add an all-one row for i = 1:N NgX = X_bar(:,NgIdx(i,:)); NormOfNgX = sqrt(sum(NgX.^2)); Xi = X_bar(:,i); tmp_C(i,NgIdx(i,:)) = -(Xi'*NgX)./(norm(Xi).*NormOfNgX); end tmp_C = makeSymmetricMat(tmp_C); tmp_C = tmp_C-diag(diag(tmp_C))+eye(N); C(f).c = sparse(tmp_C); end end
github
panji530/Maximizing-rigidity-revisited-master
RegisterToGTH.m
.m
Maximizing-rigidity-revisited-master/RegisterToGTH.m
567
utf_8
f48500aa470477f5eddef5ca30181246
% reference reconstruction to ground truth function [Q,alpha,signo]=RegisterToGTH(Q,Qg) % Author: Ajad Chhatkuli et al. Qx=Q(1,:); Qy=Q(2,:); Qz=Q(3,:); px=Qg(1,:); py=Qg(2,:); pz=Qg(3,:); signo=1; alpha=(inv(Qx(:)'*Qx(:)+Qy(:)'*Qy(:)+Qz(:)'*Qz(:))*(Qx(:)'*px(:)+Qy(:)'*py(:)+Qz(:)'*pz(:))); Qx=alpha.*Qx;Qy=alpha.*Qy;Qz=alpha.*Qz; error1=sqrt((norm(pz-Qz)^2+norm(px-Qx)^2+norm(py-Qy)^2)/length(px)); error2=sqrt((norm(pz+Qz)^2+norm(px+Qx)^2+norm(py+Qy)^2)/length(px)); if(error2<error1) signo=-1; Qx=-Qx;Qy=-Qy;Qz=-Qz; end Q(1,:)=Qx; Q(2,:)=Qy; Q(3,:)=Qz; end
github
panji530/Maximizing-rigidity-revisited-master
getNeighborsVis.m
.m
Maximizing-rigidity-revisited-master/getNeighborsVis.m
634
utf_8
91baff8a3ed1c9356de06d69f642ecde
% This work was done while the first author was in the University of Adelaide. Copyright reserved. function [ IDX,dist_sort ] = getNeighborsVis( m, Ng, visb, opt ) % Author: Ajad Chhatkuli et al. % Modified by Pan Ji if(nargin<4) opt = 'cityblock'; end % get triangulation using pdist functions: Ng number of neighbors N = length(m(1).m); distmat = zeros(size(m(1).m,2),size(m(1).m,2),length(m)); for k =1: length(m) distmat(:,:,k) = pdist2(m(k).m',m(k).m',opt); distmat(~visb(:,k),:,k) = -1; end dist = max(distmat,[],3); [dist_sort, IDX] = sort(dist,2); IDX = IDX(:,1:Ng); dist_sort = dist_sort(:,1:Ng); end
github
roschkoenig/NMDAR-Ab_Encephalitis-master
plotshaded.m
.m
NMDAR-Ab_Encephalitis-master/Mouse IgG Model/Scripts/Other Tools/plotshaded.m
872
utf_8
879e9c099db8e6ea9d0607f55c81054b
% This functions was made by Jakob Voigts and is taken from: % http://jvoigts.scripts.mit.edu/blog/nice-shaded-plots/ function varargout = plotshaded(x,y,fstr); % x: x coordinates % y: either just one y vector, or 2xN or 3xN matrix of y-data % fstr: format ('r' or 'b--' etc) % % example % x=[-10:.1:10];plotshaded(x,[sin(x.*1.1)+1;sin(x*.9)-1],'r'); if size(y,1)>size(y,2) y=y'; end; if size(y,1)==1 % just plot one line plot(x,y,fstr); end; if size(y,1)==2 %plot shaded area px=[x,fliplr(x)]; % make closed patch py=[y(1,:), fliplr(y(2,:))]; patch(px,py,1,'FaceColor',fstr,'EdgeColor','none'); end; if size(y,1)==3 % also draw mean px=[x,fliplr(x)]; py=[y(1,:), fliplr(y(3,:))]; varargout{2} = patch(px,py,1,'FaceColor',fstr,'EdgeColor','none'); varargout{1} = plot(x,y(2,:),fstr); end; alpha(.2); % make patch transparent
github
matteomaspero/Manual-gold-FM-localisation-master
distinguishable_colors.m
.m
Manual-gold-FM-localisation-master/utils/distinguishable_colors.m
5,753
utf_8
57960cf5d13cead2f1e291d1288bccb2
function colors = distinguishable_colors(n_colors,bg,func) % DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct % % When plotting a set of lines, you may want to distinguish them by color. % By default, Matlab chooses a small set of colors and cycles among them, % and so if you have more than a few lines there will be confusion about % which line is which. To fix this problem, one would want to be able to % pick a much larger set of distinct colors, where the number of colors % equals or exceeds the number of lines you want to plot. Because our % ability to distinguish among colors has limits, one should choose these % colors to be "maximally perceptually distinguishable." % % This function generates a set of colors which are distinguishable % by reference to the "Lab" color space, which more closely matches % human color perception than RGB. Given an initial large list of possible % colors, it iteratively chooses the entry in the list that is farthest (in % Lab space) from all previously-chosen entries. While this "greedy" % algorithm does not yield a global maximum, it is simple and efficient. % Moreover, the sequence of colors is consistent no matter how many you % request, which facilitates the users' ability to learn the color order % and avoids major changes in the appearance of plots when adding or % removing lines. % % Syntax: % colors = distinguishable_colors(n_colors) % Specify the number of colors you want as a scalar, n_colors. This will % generate an n_colors-by-3 matrix, each row representing an RGB % color triple. If you don't precisely know how many you will need in % advance, there is no harm (other than execution time) in specifying % slightly more than you think you will need. % % colors = distinguishable_colors(n_colors,bg) % This syntax allows you to specify the background color, to make sure that % your colors are also distinguishable from the background. Default value % is white. bg may be specified as an RGB triple or as one of the standard % "ColorSpec" strings. You can even specify multiple colors: % bg = {'w','k'} % or % bg = [1 1 1; 0 0 0] % will only produce colors that are distinguishable from both white and % black. % % colors = distinguishable_colors(n_colors,bg,rgb2labfunc) % By default, distinguishable_colors uses the image processing toolbox's % color conversion functions makecform and applycform. Alternatively, you % can supply your own color conversion function. % % Example: % c = distinguishable_colors(25); % figure % image(reshape(c,[1 size(c)])) % % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); % Copyright 2010-2011 by Timothy E. Holy % Parse the inputs if (nargin < 2) bg = [1 1 1]; % default white background else if iscell(bg) % User specified a list of colors as a cell aray bgc = bg; for i = 1:length(bgc) bgc{i} = parsecolor(bgc{i}); end bg = cat(1,bgc{:}); else % User specified a numeric array of colors (n-by-3) bg = parsecolor(bg); end end % Generate a sizable number of RGB triples. This represents our space of % possible choices. By starting in RGB space, we ensure that all of the % colors can be generated by the monitor. n_grid = 30; % number of grid divisions along each axis in RGB space x = linspace(0,1,n_grid); [R,G,B] = ndgrid(x,x,x); rgb = [R(:) G(:) B(:)]; if (n_colors > size(rgb,1)/3) error('You can''t readily distinguish that many colors'); end % Convert to Lab color space, which more closely represents human % perception if (nargin > 2) lab = func(rgb); bglab = func(bg); else C = makecform('srgb2lab'); lab = applycform(rgb,C); bglab = applycform(bg,C); end % If the user specified multiple background colors, compute distances % from the candidate colors to the background colors mindist2 = inf(size(rgb,1),1); for i = 1:size(bglab,1)-1 dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color end % Iteratively pick the color that maximizes the distance to the nearest % already-picked color colors = zeros(n_colors,3); lastlab = bglab(end,:); % initialize by making the "previous" color equal to background for i = 1:n_colors dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors colors(i,:) = rgb(index,:); % save for output lastlab = lab(index,:); % prepare for next iteration end end function c = parsecolor(s) if ischar(s) c = colorstr2rgb(s); elseif isnumeric(s) && size(s,2) == 3 c = s; else error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.'); end end function c = colorstr2rgb(c) % Convert a color string to an RGB value. % This is cribbed from Matlab's whitebg function. % Why don't they make this a stand-alone function? rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0]; cspec = 'rgbwcmyk'; k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end if k~=3 || length(c)==1, c = rgbspec(k,:); elseif length(c)>2, if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') c = [0 0 1]; else error('MATLAB:UnknownColorString', 'Unknown color string.'); end end end
github
lequangduong/gimbalcontrol-master
GimbalModelCode.m
.m
gimbalcontrol-master/GimbalModelCode.m
12,002
utf_8
685127edcd54aaa01fca004e75ec7784
%% =============== Declaration ================= clc;clear;close all % ========= Notation of all joint angles is theta 1, 2, 3 gimbal.param.n = 3; gimbal.param.theta = sym('theta_',[gimbal.param.n 1],'real'); gimbal.param.u = sym('u_' ,[gimbal.param.n 1],'real'); % === q = theta; %This variable is equivalent gimbal.param.q = sym('q_' ,[gimbal.param.n 1],'real'); gimbal.param.Dq = sym('Dq_' ,[gimbal.param.n 1],'real'); gimbal.param.DDq = sym('DDq_',[gimbal.param.n 1],'real'); % === reference parameter gimbal.param.us = sym('us_' ,[gimbal.param.n 1],'real'); gimbal.param.qs = sym('qs_' ,[gimbal.param.n 1],'real'); gimbal.param.Dqs = sym('Dqs_' ,[gimbal.param.n 1],'real'); gimbal.param.DDqs = sym('DDqs_',[gimbal.param.n 1],'real'); % ======================== drone.sym.pos = [sym('X','real'); sym('Y','real'); sym('Z','real')]; drone.sym.acc = [sym('DDX','real'); sym('DDY','real'); sym('DDZ','real')]; % acceleration drone.sym.dir = [sym('phi','real'); sym('theta','real'); sym('psi','real')]; %roll - pitch - yaw obj.sym.pos = [sym('x','real'); sym('y','real'); sym('z','real')]; %% =============== Read data of Gimbal motor in Exel Table ==================%% data = getData(gimbal.param.n); %% ===================== Calculation of Transformation matrix =============== % gimbal.sym.kin = forwardkinematics(data.sym,gimbal.param,drone.sym); gimbal.num.kin = forwardkinematics(data.num,gimbal.param,drone.sym); % Not use drone.num because rot function didn't catch matrix of time gimbal.invkin = @inversekinematics; gimbal.sym.dyn = robotdynamics(data.sym,gimbal.param,gimbal.sym.kin,drone.sym); gimbal.num.dyn = robotdynamics(data.num,gimbal.param,gimbal.num.kin,drone.sym); save('variable.mat') %% ======== FUNCTION and CLASS ============%% function gimbal_dynamics = robotdynamics(data,gimbal_param,gimbal_kin,drone_sym) % The forward dynamics problem was constructed all with base frame % coordinate system % n = gimbal_param.n; q = gimbal_param.q; Dq = gimbal_param.Dq; DDq = gimbal_param.DDq; m = data.m; g = data.g; R = gimbal_kin.R; T = gimbal_kin.T; omega = gimbal_kin.o; rC = cell(1,n); I = cell(1,n); for i=1:n rC_i = T{i} * [data.rC{i};1]; rC{i} = rC_i(1:3); I{i} = data.I{i}; end % Jacobi matrix J_T = cell(i,n); J_R = cell(1,n); for i = 1:n J_T{i} = jacobian(rC{i},q); J_R{i} = jacobian(omega{i},Dq); end M = zeros(n); for i = 1:n M = M + m(i)*J_T{i}'*J_T{i} + J_R{i}'*R{i}*I{i}*R{i}'*J_R{i}; end gimbal_dynamics.M = M; In = eye(n); C = diffmat(M,q)*kron(In,Dq) - 1/2*(diffmat(M,q)*kron(Dq,In))'; gimbal_dynamics.C = C; PI = 0; for i = 1:n PI = PI - m(i)*g'*rC{i}; end gimbal_dynamics.PI = PI; G = jacobian(PI,q)'; gimbal_dynamics.G = G; if isa(data.l,'double') % Handle function %gimbal_dynamics.fM = matlabFunction(M); %gimbal_dynamics.fC = matlabFunction(C); %gimbal_dynamics.fG = matlabFunction(G); %======================= W = 0; for i=1:n F = -m(i).*drone_sym.acc; W = W + F'*rC{i}; end QF = simplify(jacobian(W,q))'; gimbal_dynamics.QF = QF; %gimbal_dynamics.fQF = matlabFunction(QF); u = gimbal_param.u; Qu = u; Q = Qu+QF; % === Get approximate vallue ==== M = vpa(simplify(M),5); C = vpa(simplify(C),5); G = vpa(simplify(G),5); Q = vpa(simplify(Q),5); L = M*DDq + C*Dq + G - QF; % = u gimbal_dynamics.L = L; L = vpa(L,5); gimbal_dynamics.fL = matlabFunction(L); Fxu = [Dq; M^-1*(C*Dq - G + Q)]; gimbal_dynamics.Fxu = Fxu; gimbal_dynamics.fxu = matlabFunction(Fxu); Fxu = vpa(Fxu,5); Hxu = q; gimbal_dynamics.Hxu = Hxu; % ==== Linearization ====== x = [q;Dq]; xs = [gimbal_param.qs;gimbal_param.Dqs]; us = gimbal_param.us; % ------------ gimbal_dynamics.A = subs(jacobian(Fxu,x),[x;u],[xs;us]); A = vpa(gimbal_dynamics.A,5); gimbal_dynamics.fA = matlabFunction(A); % ------------ gimbal_dynamics.B = subs(jacobian(Fxu,u),[x;u],[xs;us]); gimbal_dynamics.fB = matlabFunction(gimbal_dynamics.B); % ------------ gimbal_dynamics.C = subs(jacobian(Hxu,x),[x;u],[xs;us]); gimbal_dynamics.fC = matlabFunction(gimbal_dynamics.C); % ------------ gimbal_dynamics.D = subs(jacobian(Hxu,u),[x;u],[xs;us]); gimbal_dynamics.fD = matlabFunction(gimbal_dynamics.D); end end function theta = inversekinematics( obj, drone, gimbal, initGuess ) % ========== SOLVING BY NUMERIC METHOD =================== N = size(obj.num.pos,2); % 3_O3P = 3_T_f*f_O3P = 3_T_f*(f_O3O + f_OP) % = f_T_3^-1 * (-f_d_3 + Pf) Pf = [obj.sym.pos;1]; P3 = gimbal.num.kin.Tf{3}^-1*(-gimbal.num.kin.Tf{3}(:,4) + Pf); %syms droneX droneY droneZ objX objY objZ real theta_1 = zeros(1,N); theta_2 = zeros(1,N); theta_3 = zeros(1,N); for i =1:N % theta_1 = yaw P3 = simplify(expand(subs(P3,gimbal.param.q(2),theta_2(i)))); % Equations: P3(2:3) = [0;0] eqs = P3(2:3); eqs_i = (subs(eqs, drone.sym.pos, drone.num.pos(:,i))); eqs_i = (subs(eqs_i, drone.sym.dir, drone.num.dir(:,i) )); eqs_i = (subs(eqs_i, obj.sym.pos, obj.num.pos(:,i))); eqs_i = vpa(subs(eqs_i)); if i>1 sol = vpasolve(eqs_i, [gimbal.param.q(1); gimbal.param.q(3)], [theta_1(i-1); theta_3(i-1)]); else sol = vpasolve(eqs_i, [gimbal.param.q(1); gimbal.param.q(3)], initGuess); end theta_1(i) = sol.q_1; theta_3(i) = sol.q_3; end theta = [theta_1; theta_2; theta_3]; end function gimbal_kinematics = forwardkinematics(data,gimbal,drone) % Input: % data - struct of Gimbal parameter % q - vector of link angles % drone- struct determine position and direction of Drone q = gimbal.q; Dq = gimbal.Dq; l = data.l; b = data.b; h = data.h; n = size(q,1); % Rotation matrix R = cell(1,n*10+n); %This variable use row cell to store all rotation matrix R{10} = rot('z', q(1)); R{21} = rot('x', q(2)); R{32} = rot('y', q(3)); % Direct vectors of origins in stable state: theta = [0 0 0]' d0{10} = [-l(1) 0 h(1)]'; % = _O0O1_0 d0{21} = [l(2) -b(2) 0]'; % = _O1O2_1 d0{32} = [l(3) b(3) h(3)]'; % = _O2O3_2 % Direct vectors of origins after rotations d = cell(1, n*10+n); % Transformation matrix T = cell(1, n*10+n); for i = 1:n d{i*10+i-1} = R{i*10+i-1}*d0{i*10+i-1}; T{i*10+i-1} = transf(R{i*10+i-1},d{i*10+i-1}); %_i-1_T_i end i = 1; T{i} = simplify( T{i*10+i-1} ); %_T_1 = _0_T_1 R{i} = T{i}(1:3,1:3); d{i} = T{i}(3,1:3); for i = 2:n T{i} = simplify( T{i-1} * T{i*10+i-1} ); %_T_i = _0_T_i-1 * _i-1_T_i R{i} = T{i}(1:3,1:3); d{i} = T{i}(3,1:3); end T = T(1:3); R = R(1:3); gimbal_kinematics.T = T; gimbal_kinematics.R = R; %=============== % Transpose from Gimbal Frame through Quad Frame to Global Fram % f_T_0 % R0 = %R0 = rot('z', drone.dir(3))*rot('y', drone.dir(2))*rot('x', drone.dir(1)) * rot('x',sym('pi')); R0 = rot('x', drone.dir(1))*rot('y', drone.dir(2))*rot('z', drone.dir(3)) * rot('x',sym('pi')); d0 = drone.pos; %Not calculate the distance from origin of quad to origin of Gimbal T0 = transf(R0,d0); %f_T_0 Tf = cell(1,n+1); Rf = cell(1,n+1); for i=1:n Tf{i} = T0*T{i}; Rf{i} = Tf{i}(1:3,1:3); end Tf{4} = T0; Rf{4} = R0; gimbal_kinematics.Tf = Tf; gimbal_kinematics.Rf = Rf; %============== OMEGA =========== o = cell(1,n); of = cell(1,n); for i = 1:n Rd = difftime(R{i},q,Dq); Rdf = difftime(Rf{i},q,Dq); o{i} = invskew( simplify( Rd * R{i}' ) ); of{i} = invskew( simplify( Rdf * Rf{i}' ) ); end gimbal_kinematics.o = o; gimbal_kinematics.of = of; end function data = getData(n) datafile = 'Gimbal_Model_Data_Table.xlsx'; range1 = 'B3:D5'; %Kinematics Data Table range2 = 'B3:K5'; % Dynamics Data Table [~,~,Params_Kin_Sym] = xlsread(datafile, 1, range1); [~,~,Params_Dyn_Sym] = xlsread(datafile, 2, range2); [~,~,Params_Kin_Num] = xlsread(datafile, 3, range1); [~,~,Params_Dyn_Num] = xlsread(datafile, 4, range2); % === SYMBOLIC VALUE === data.sym.l = sym(Params_Kin_Sym(1:n,1)','real'); data.sym.b = sym(Params_Kin_Sym(1:n,2)','real'); data.sym.h = sym(Params_Kin_Sym(1:n,3)','real'); data.sym.g = [0 0 -sym('g','real')]'; %OXYZ data.sym.m = sym(Params_Dyn_Sym(1:n,4)','real'); % === NUMERIC VALUE === data.num.l = [Params_Kin_Num{1:n,1}]; data.num.b = [Params_Kin_Num{1:n,2}]; data.num.h = [Params_Kin_Num{1:n,3}]; data.num.g = [0 0 -9.81]'; %OXYZ data.num.m = [Params_Dyn_Num{1:n,4}]; rC = cell(1,n); I = cell(1,n); % === SYMBOLIC VALUE === for i=1:n rC{i} = sym(Params_Dyn_Sym(i,1:3)','real'); Ii = sym(Params_Dyn_Sym(i,5:10),'real'); I{i} = [Ii(1) Ii(4) Ii(6);... Ii(4) Ii(2) Ii(5);... Ii(6) Ii(5) Ii(3)]; end data.sym.rC = rC; data.sym.I = I; % === NUMERIC VALUE === for i=1:n rC{i} = [Params_Dyn_Num{i,1:3}]'; Ii = [Params_Dyn_Num{i,5:10}]; I{i} = [Ii(1) Ii(4) Ii(6);... Ii(4) Ii(2) Ii(5);... Ii(6) Ii(5) Ii(3)]; end data.num.rC = rC; data.num.I = I; end function T = transf(R, d) T = [R,d;0,0,0,1]; end function R = rot(axis, phi) if axis == 'x' u = [1; 0; 0]; elseif axis == 'y' u = [0; 1; 0]; elseif axis == 'z' u = [0; 0; 1]; else error('Invalid axis'); end R = eye(3)*cos(phi)+u*u'*(1-cos(phi))+skew(u)*sin(phi); end function mat_hat = skew(vec) if size(vec,1) ~= 3 error('Vector must be 3x1'); end mat_hat(1,2) = -vec(3); mat_hat(1,3) = vec(2); mat_hat(2,3) = -vec(1); mat_hat(2,1) = vec(3); mat_hat(3,1) = -vec(2); mat_hat(3,2) = vec(1); end function vec = invskew(mat) vec = mat(:,1); if size(mat,1) ~= 3 && size(mat,2) ~= 3 error('matrix must be 3x3'); end vec(1) = mat(3,2); vec(2) = mat(1,3); vec(3) = mat(2,1); end function dA_x = diffmat (A, x) [m,p] = size(A); n = size(x,1); dA_x = sym('dA_x',[m n*p]); for i = 1:p dA_x(:, (i-1)*n+1 :i*n ) = jacobian(A(:,i),x); end end function dA_t = difftime (A, x, xd) % This function is using to find diff(A,t) if x = x(t) = xd % x is symbolic variable in the matrix A % x is not symbolic function of time % so we can't find diff(A,t) % This function will substitute x(t) to x variable in A % and find diff(A,t) % finally, substitute xd to diff(x,t) in A n = size(x, 1); if size(x,2) ~= 1 error('Vector must be 3x1') end syms t real xt = sym('xt_',[n,1]); for i = 1:n xt(i) = sym(['xt_',char(48+i),'(t)']); % Turn of the warning of sym('x(t)') [~,warningID] = lastwarn; warning('off',warningID); end A = subs(A,x,xt); Ad = diff(A,t); Ad = subs(Ad,diff(xt,t),xd); dA_t = subs(Ad,xt,x); end
github
lequangduong/gimbalcontrol-master
main.m
.m
gimbalcontrol-master/main.m
19,011
utf_8
d7529a0a63127dd14d75555e1bd8060e
clc;clear;close all load('variable.mat') %% ============ SCHEME variable.mat ==================== % gimble % - param % -- n -> Number of DoF % -- stime -> sample time % -- t -> time % -- tf -> time finite % -- theta -> {theta_1; theta_2; theta_3] % -- q -> [q_1; q_2; q_3] % -- Dq -> [Dq_1; Dq_2; Dq_3] % -- DDq -> [DDq_1; DDq_2; DDq_3] % star ~ reference % -- us -> [us_1; us_2; us_3] % -- qs -> [qs_1; qs_2; qs_3] % -- Dqs -> [Dqs_1; Dqs_2; Dqs_3] % -- DDqs -> [DDqs_1; DDqs_2; DDqs_3] % - sym -> symbolic % -- kin -> kinematics % --- R -> R O0x0y0z0 % --- Rf -> R OXYZ (f) % --- T -> T O0x0y0z0 % --- Tf -> T OXYZ (f) % --- o -> omega O0x0y0z0 % --- of -> omega OXYZ (f) % - num -> numeric % -- kin -> kinematics % --- R -> R O0x0y0z0 % --- Rf -> R OXYZ (f) % --- T -> T O0x0y0z0 % --- Tf -> T OXYZ (f) % --- o -> omega O0x0y0z0 % --- of -> omega OXYZ (f) % - sym -> symbolic % -- dyn -> dynamics % --- M -> M matrix % --- C -> C matrix % --- G -> G matrix % - num -> numeric % -- dyn -> dynamics % --- M -> M matrix % --- fM -> M handle function % --- C -> C matrix % --- fC -> C handle function % --- G -> G matrix % --- fG -> G handle function % drone % - sym -> symbolic % -- pos -> [X; Y; Z] position of drone %% ============ INPUT drone and target ============= n = 3; gimbal.param.n = n; gimbal.param.stime = 0.01; gimbal.param.tf = 10; gimbal.param.t = 0:gimbal.param.stime:gimbal.param.tf; % ====== Quadcopter / Drone ========== t = gimbal.param.t; tf = gimbal.param.tf; drone.num.pos = [0.02*t.^2; % X 0.2*t; % Y 0.2*sin(10*t/tf*pi-pi/2)+3 %Z ]; drone.num.acc = [0.04*t; % X 0*t; % Y -(10/tf*pi)^2*0.2*sin(10*t/tf*pi-pi/2)+2 %Z ]; drone.num.dir = [pi/18*sin(t/tf*pi-pi/2); % ROLL pi/18*sin(t/tf*pi-pi/2); % PITCH pi/6*sin(t/tf*pi); % YAW Must begin at 0 ]; % ====== Target ======= obj.num.pos = [0.02*t.^2+0.5; % X 0.2*t+0.6; % Y 0*t %Z ]; %% ===================== Controller ===================== % Input simulink % reference vallue - star qs = double(gimbal.invkin( obj, drone, gimbal, [0; -pi/2] )); Dqs = [0 diff(qs(1,:))./diff(t); 0 diff(qs(2,:))./diff(t); 0 diff(qs(3,:))./diff(t)]; DDqs = [0 diff(Dqs(1,:))./diff(t); 0 diff(Dqs(2,:))./diff(t); 0 diff(Dqs(3,:))./diff(t)]; DDX = drone.num.acc(1,:); DDY = drone.num.acc(2,:); DDZ = drone.num.acc(3,:); xs = [qs; Dqs]; us = gimbal.num.dyn.fL(DDX,DDY,DDZ,DDqs(1,:),DDqs(2,:),DDqs(3,:),Dqs(1,:),Dqs(2,:),Dqs(3,:),qs(1,:),qs(2,:),qs(3,:)); % initial value q0 = zeros(3,1); Dq0 = zeros(3,1); DDq0 = zeros(3,1); x0 = [q0; Dq0]; Dx0 = [Dq0; DDq0]; %% LQG - MPC Controller controller.param.stime = gimbal.param.stime; controller.param.Q0 = 1; controller.param.R0 = 1; controller.param.wd = randn(2*n,1)*0; controller.param.vd = randn(n,1)*0; controller.ref.x = xs; controller.ref.u = us; controller.init.x = x0; controller.init.Dx = Dx0; % MPC constrain controller.param.umax = 6; % kg*m/s^2 * m controller.param.umin = -6; controller.param.T = 10; % number of step discreted linear system controller.param.Nc = 8; % number of step predicted (horizontal) % Delay controller.param.tDelay = 4; % ~ tDelay * stime/T % ~ 4*0.01/10 = 0.004(s) % tDelay must less than Nc [u_lqr, y_lqr, x_lqr] = lqg_solve(controller,gimbal,drone); [u_mpc, y_mpc, x_mpc] = mpc_solve(controller,gimbal,drone); plot_output(gimbal.param.stime, tf, x_lqr, x_mpc, xs, u_lqr, u_mpc, us); %% =================== Simulation ======================== T = 10; ts = 0:gimbal.param.stime:tf; t = 0:gimbal.param.stime/T:tf; input.theta = [ts', xs(1:3,:)']; %input.theta = [t', x_mpc(1:3,:)']; input.targetposition = [ts', obj.num.pos']; input.quadposition = [ts' drone.num.pos']; input.quadrotation = [ts' (drone.num.dir)'];%RPY2XYZ input.quadposition_line = drone.num.pos'; input.targetposition_line = obj.num.pos'; open Kinematics.slx %open Dynamics.slx %% =================== FUNCTION ============= function [u, y, xhat] = lqg_solve(controller,gimbal,drone) xs = controller.ref.x; us = controller.ref.u; x0 = controller.init.x; Dx0 = controller.init.Dx; stime = controller.param.stime; Q0 = controller.param.Q0; R0 = controller.param.R0; wd = controller.param.wd; vd = controller.param.vd; T = controller.param.T; tDelay = controller.param.tDelay; if(tDelay > T) error('tDelay time must less than T'); end DDX = drone.num.acc(1,:); DDY = drone.num.acc(2,:); DDZ = drone.num.acc(3,:); n = size(xs,1)/2; %Number of DOF N = size(xs,2); %Number of points of linearization P = T*(N-1); % Example -> Cach chia discrete system % *.........*.........*........* (P = 30, N = 4, T = 10) % 0 0.01 0.02 0.03 % * . . . . . . . . . * % 0 0.001 0.002 0.003 0.004 0.005 0.006 0.007 0.008 0.009 0.01 % * . . . . . . . . . * %0.01 0.011 0.012 0.013 0.014 0.015 0.016 0.017 0.018 0.019 0.02 Dxs = [zeros(2*n,1) diff(xs,1,2)./stime]; % estimate states xhat = zeros(2*n, P); Dxhat = zeros(2*n, P); %model state xmod = zeros(2*n, P); Dxmod = zeros(2*n, P); %control input u = zeros(n, P); % initialization xhat(:,1) = x0; xmod(:,1) = x0; Dxhat(:,1) = Dx0; Dxmod(:,1) = Dx0; % % Make system C = gimbal.num.dyn.fC(); D = gimbal.num.dyn.fD(); y = C*xhat+D*u; % initial measured output ys = C*xs+D*us; Q = Q0*(C'*C); R = R0*eye(n); %qk = 200; qk = 1; Qk = [qk 0 0; % QN use for kalman 0 qk 0; 0 0 qk]; for k = 1:(N-1) A = gimbal.num.dyn.fA(DDX(k),DDY(k),DDZ(k),xs(4,k),xs(5,k),xs(6,k),xs(1,k),xs(2,k),xs(3,k),us(1,k),us(2,k),us(3,k)); B = gimbal.num.dyn.fB(xs(2,k),xs(3,k)); sys = ss(A,B,C,D); K = lqr(sys,Q,R); %% LQG state-estimator % x_hat_dot = (A-LC-BK)x_hat + Ly % u = Kx -> u for i=1:T p = (k-1)*T+i; % % Check delay output % if tDelay = 3 (~0.003 second) % 1 2 3 4 (p) % * . . . % 0 0.001 0.002 0.003 (second) % yDelay yDelay if mod(p+tDelay-1,tDelay)==0 yDelay = y(:,p); end if tDelay ==0 yDelay = y(:,p); end %Linearization Equation of us, xs, Dxs usk_i= us(:,k) + (us(:,k+1) - us(:,k))/T * (i-1); xsk_i = xs(:,k) + (xs(:,k+1) - xs(:,k))/T * (i-1); ysk_i = ys(:,k) + (ys(:,k+1) - ys(:,k))/T * (i-1); Dxsk_iadd1 = Dxs(:,k) + (Dxs(:,k+1) - Dxs(:,k))/T *(i); % LQG controller [~,L,~] = kalman(sys,Qk,R); u(:,p) = usk_i - K*xhat(:,p) + K*xsk_i; %y(:,p) Dxhat(:,p+1) = Dxsk_iadd1 + (A - L*C - B*K)*(xhat(:,p) - xsk_i) + L*(yDelay - ysk_i); xhat(:,p+1) = Dxhat(:,p+1)*(stime/T) + xhat(:,p); % Gimbal model Dxmod(:,p+1) = gimbal.num.dyn.fxu(DDX(k),DDY(k),DDZ(k),... xmod(4,p),xmod(5,p),xmod(6,p),... xmod(1,p),xmod(2,p),xmod(3,p),... u(1,p),u(2,p),u(3,p)); xmod(:,p+1) = Dxmod(:,p+1)*(stime/T) + xmod(:,p) + wd; y(:,p+1) = C*xmod(:,p+1) + vd; end end end function [u, y, xhat] = mpc_solve(controller,gimbal,drone) xs = controller.ref.x; us = controller.ref.u; x0 = controller.init.x; Dx0 = controller.init.Dx; stime = controller.param.stime; Q0 = controller.param.Q0; R0 = controller.param.R0; wd = controller.param.wd; vd = controller.param.vd; umax = controller.param.umax; umin = controller.param.umin; T = controller.param.T; Nc = controller.param.Nc; if(Nc > T) error('Nc must less than T'); end tDelay = controller.param.tDelay; if(tDelay > Nc) error('tDelay time must less than Nc'); end DDX = drone.num.acc(1,:); DDY = drone.num.acc(2,:); DDZ = drone.num.acc(3,:); n = size(xs,1)/2; %Number of DOF N = size(xs,2); %Number of points of linearization P = T*(N-1); % Example -> Cach chia discrete system % *.........*.........*........* (P = 30, N = 4, T = 10) % 0 0.01 0.02 0.03 % * . . . . . . . . . * % 0 0.001 0.002 0.003 0.004 0.005 0.006 0.007 0.008 0.009 0.01 % * . . . . . . . . . * %0.01 0.011 0.012 0.013 0.014 0.015 0.016 0.017 0.018 0.019 0.02 Dxs = [zeros(2*n,1) diff(xs,1,2)./stime]; % estimate states xhat = zeros(2*n, P); Dxhat = zeros(2*n, P); %model state xmod = zeros(2*n, P); Dxmod = zeros(2*n, P); %control input u = zeros(n, P); % initialization xhat(:,1) = x0; xmod(:,1) = x0; Dxhat(:,1) = Dx0; Dxmod(:,1) = Dx0; % % Make system C = gimbal.num.dyn.fC(); D = gimbal.num.dyn.fD(); y = C*xhat+D*u; % initial measured output ys = C*xs+D*us; Q0 = Q0*(C'*C); R0 = R0*eye(n); %qk = 200; qk = 1; Qk = [qk 0 0; % QN use for kalman 0 qk 0; 0 0 qk]; DeluPredicted = zeros(Nc,n); for k = 1:(N-1) A = gimbal.num.dyn.fA(DDX(k),DDY(k),DDZ(k),xs(4,k),xs(5,k),xs(6,k),xs(1,k),xs(2,k),xs(3,k),us(1,k),us(2,k),us(3,k)); B = gimbal.num.dyn.fB(xs(2,k),xs(3,k)); sys = ss(A,B,C,D); sysd = c2d(sys,stime/T,'zoh'); A = sysd.A; B = sysd.B; % w.Q = Q*sys.C'*sys.C; % w.R = R*eye(3); % w.Nc = Nc; % constraint checking horizon %% Discrete system %Ac*u(k) <= b0 + Bx*x(k) %input constraint umin < u < umax Delumax = zeros(n,1);Delumin = zeros(n,1); for i=1:3 Delumax(i) = umax-max(us(i,k),us(i,k+1)); %just constant Delumin(i) = umin-min(us(i,k),us(i,k+1)); end R_kal = R0*eye(n); Ac = [eye(Nc*n); -eye(Nc*n)]; %b0 = []; %b0 = [ones(Nc*n,1).*[umax;umax]; -ones(Nc*n,1).*[umin; umin]]; b0 = repmat(Delumax,Nc,1); b0 = [b0; -repmat(Delumin,Nc,1)]; %Bx = 0; Q = []; % Q using Lyapunov Equation K = -dlqr(A,B,Q0,R0); Q_ = dlyap((A+B*K)',Q0+K'*R0*K); for i=1:Nc-1 Q = blkdiag(Q,Q0); end Q = blkdiag(Q,Q_); R = []; for i=1:Nc R = blkdiag(R,R0); end %M_ = []; M_ = zeros((2*n)*Nc, 2*n); for i=1:Nc %M_ = [M_; A^i]; rol = (i-1)*2*n+1:i*2*n; % rol change M_(rol, 1:2*n) = A^i; end %C_ = []; C_ = convolution(A, B, n, Nc); H = C_'*Q*C_ + R; F = C_'*Q*M_; %G = M_'*Q*M_+Q0; % % unconstrain % % u(k) = -[1 0 0 0]*H^-1*F*x(k) = K_N*x(k) % K_mpc = -H^-1*F; % K_mpc = K_mpc(1:n,:); % Delx = xhat(:,k)-xs(:,k); % Delu = K_mpc*Delx; for i=1:T p = (k-1)*T+i; % % Check delay output % if tDelay = 3 (~0.003 second) % 1 2 3 4 (p) % * . . . % 0 0.001 0.002 0.003 (second) % yDelay yDelay if mod(p+tDelay-1,tDelay)==0 yDelay = y(:,p); end if tDelay ==0 yDelay = y(:,p); end %Linearization Equation of us, xs, Dxs usk_i= us(:,k) + (us(:,k+1) - us(:,k))/T * (i-1); xsk_i = xs(:,k) + (xs(:,k+1) - xs(:,k))/T * (i-1); ysk_i = ys(:,k) + (ys(:,k+1) - ys(:,k))/T * (i-1); Dxsk_iadd1 = Dxs(:,k) + (Dxs(:,k+1) - Dxs(:,k))/T *(i); % Constrain %uPredicted = quadprog(H,F*x(:,i),Ac,b0+Bx*x(:,i)); Delx = xhat(:,p) - xsk_i; options = optimoptions('quadprog','Display','off'); uPredicted = quadprog(H,F*Delx,Ac,b0,[],[],[],[],[],options); %Bx = 0 % Turn of the warning of quadprog function [~,warningID] = lastwarn; warning('off',warningID); if isempty(uPredicted) if size(DeluPredicted,1) > 1 DeluPredicted = DeluPredicted(2:end,:); end else for j=1:Nc DeluPredicted(j,:)= uPredicted(n*(j-1)+1:n*j)'; end end Delu = DeluPredicted(1,:)'; % Estimation K = lqr(sys,Q0,R0); A = sys.A; B = sys.B; C = sys.C; [~,L,~] = kalman(sys,Qk,R_kal); u(:,p) = usk_i + Delu; % check sign y(:,p) Dxhat(:,p+1) = Dxsk_iadd1 + (A - L*C - B*K)*(xhat(:,p) - xsk_i) + L*(yDelay - ysk_i); xhat(:,p+1) = Dxhat(:,p+1)*(stime/T) + xhat(:,p); % Gimbal model Dxmod(:,p+1) = gimbal.num.dyn.fxu(DDX(k),DDY(k),DDZ(k),... xmod(4,p),xmod(5,p),xmod(6,p),... xmod(1,p),xmod(2,p),xmod(3,p),... u(1,p),u(2,p),u(3,p)); xmod(:,p+1) = Dxmod(:,p+1)*(stime/T) + xmod(:,p) + wd; y(:,p+1) = C*xmod(:,p+1) + vd; end end end function C_ = convolution(A, B, n, Nc) %C_=[]; C_ = zeros(2*n*Nc, n*Nc); for j=1:Nc % col_i = []; col_j = zeros(2*n*Nc, n); for i=1:Nc rol = (i-1)*2*n+1:i*2*n; % rol change if j>i %col_i = [col_i; zeros(size(B))]; col_j(rol, 1:n) = zeros(size(B)); else %col_i = [col_i; A^(i-j)*B]; col_j(rol, 1:n) = A^(i-j)*B; end end rol = 1:2*n*Nc; % rol change col = (j-1)*n+1 :j*n; C_(rol, col) = col_j; % C_ = [C_ col_j]; end end function plot_output(stime, tf, x_lqr, x_mpc, xs, u_lqr, u_mpc, us) T = 10; n = 3; t = 0:stime/T:tf; ts = 0:stime:tf; % plot x for p=1:2*n figure(p) subplot(3,2,1) plot(ts,xs(p,:),t,x_lqr(p,:)) legend(['x^*(',char(p+48),')'],['x(',char(p+48),')']) xlabel('t (s)') ylabel('rad') title(['Response of x_',char(p+48),' with lqr']) subplot(3,2,2) plot(ts,xs(p,:),t,x_mpc(p,:)) legend(['x^*(',char(p+48),')'],['x(',char(p+48),')']) xlabel('t (s)') ylabel('rad') title(['Response of x_',char(p+48),' with mpc']) % zoom in t = 0 -> 0.5 (s) subplot(3,2,3) plot(ts(1:50),xs(p,1:50),t(1:500),x_lqr(p,1:500)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of x_',char(p+48),' with lqr',' (zoom t < 0.5s)']) subplot(3,2,4) plot(ts(1:50),xs(p,1:50),t(1:500),x_mpc(p,1:500)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of x_',char(p+48),' with mpc',' (zoom t < 0.5s)']) % zoom in t = 0.5 -> 10 (s) subplot(3,2,5) plot(ts(51:end),xs(p,51:end),t(501:end),x_lqr(p,501:end)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of x_',char(p+48),' with lqr',' (zoom t > 0.5s)']) subplot(3,2,6) plot(ts(51:end),xs(p,51:end),t(501:end),x_mpc(p,501:end)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of x_',char(p+48),' with mpc',' (zoom t > 0.5s)']) end % plot u for p=1:n figure(p+2*n) subplot(3,2,1) plot(ts,us(p,:),t(1:end-1),u_lqr(p,:)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of u_',char(p+48),' with lqr']) subplot(3,2,2) plot(ts,us(p,:),t(1:end-1),u_mpc(p,:)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of u_',char(p+48),' with mpc']) % zoom in t = 0 -> 0.5 (s) subplot(3,2,3) plot(ts(1:50),us(p,1:50),t(1:500),u_lqr(p,1:500)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of u_',char(p+48),' with lqr',' (zoom t < 0.5s)']) subplot(3,2,4) plot(ts(1:50),us(p,1:50),t(1:500),u_mpc(p,1:500)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of u_',char(p+48),' with mpc',' (zoom t < 0.5s)']) % zoom in t = 0.5 -> 10 (s) subplot(3,2,5) plot(ts(51:end),us(p,51:end),t(501:end-1),u_lqr(p,501:end)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of u_',char(p+48),' with lqr',' (zoom t > 0.5s)']) subplot(3,2,6) plot(ts(51:end),us(p,51:end),t(501:end-1),u_mpc(p,501:end)) legend(['u^*(',char(p+48),')'],['u(',char(p+48),')']) xlabel('t (s)') ylabel('Nm') title(['Response of u_',char(p+48),' with mpc',' (zoom t > 0.5s)']) end end
github
ylucet/CCA-master
plq_dom_test.m
.m
CCA-master/tests/plq_dom_test.m
819
utf_8
1f5e7cb8f3611c4ae041590a04bb1780
function tests = plq_dom_test() tests = functiontests(localfunctions); end function b = test1(testCase) b=true; %full domains p=[inf 1 0 0];I=plq_dom(p); b=b & isequal(I,[-inf,inf]); p=[0,0,-1,0;inf,0,1,0];I=plq_dom(p); b=b & isequal(I,[-inf,inf]); %left bounded p=[0,0,0,inf;1,0,0,0;inf,1,0,0];I=plq_dom(p); b=b & isequal(I,[0,inf]); p=[0,0,0,inf;inf,1,0,0];I=plq_dom(p); b=b & isequal(I,[0,inf]); %right bounded p=[0,0,0,2;1,0,0,0;inf,0,0,inf];I=plq_dom(p); b=b & isequal(I,[-inf,1]); %left & right bounded p=[0,0,0,inf;1,0,0,0;inf,0,0,inf];I=plq_dom(p); b=b & isequal(I,[0,1]); %singleton p=[0,0,0,1];I=plq_dom(p); b=b & isequal(I,[0,0]); assert(b) end function [b] = runTestFile(testCase) b = true; b = checkForFail(testWrapper(test1,'test1'), b); assert(b) end
github
ylucet/CCA-master
plq_isConvex_test.m
.m
CCA-master/tests/plq_isConvex_test.m
1,238
utf_8
a57d12c698b2ddd5c1565a7989902260
function tests = plq_isConvex_test() tests = functiontests(localfunctions); end function b = testAbs(testCase) %abs function p = [0,0,-1,0;inf,0,1,0]; b = plq_isConvex(p); assert(b) end function b = testQuartic(testCase) function y=f(x), y=x.^4;end function dy=df(x), dy=4*x.^3;end x=linspace(-2,2,4)'; p=plq_build(x,@f,@df,true,false,'soqs','bounded'); b = plq_isConvex(p); assert(b) end function [b] = testInd(testCase) % The function I_[-1,1]. p = [-1,0,0,inf; 1,0,0,0; inf,0,0,inf]; b = plq_isConvex(p); assert(b) end function [b] = testPL(testCase) p = [0,0,-1,0; 1,0,0,0; inf,0,1,-1]; b = plq_isConvex(p); assert(b) end function [b] = testPLQ1(testCase) b = false; % A PLQ function: % x<-1: y=(x+1)^2 % -1<x<1: y=0 % 1<x: y=(x-1)^2 p = [-1,1,2,1; 1,0,0,0; inf,1,-2,1]; b = plq_isConvex(p); assert(b) end function b = testPLQ2(testCase) % A PLQ function: % x in [-1,1]: 0 % otherwise: x^2 - 1 p = [-1,1,0,-1; 1,0,0,0; inf,1,0,-1]; b = plq_isConvex(p); assert(b) end function b = testFullDomain(testCase) p = [inf,1,0,0]; b = plq_isConvex(p); assert(b) end function b = testIndicator(testCase) p = [2,0,0,1]; b = plq_isConvex(p); assert(b) end
github
ylucet/CCA-master
plq_build_test.m
.m
CCA-master/tests/plq_build_test.m
6,169
utf_8
a2dc3cf6e53b7a7334edbba2621ec953
function tests = plq_build_test() tests = functiontests(localfunctions); end % unit tests ========================================================== %1st order model function [b] = testexp(testCase) x=linspace(0,4)'; plqf = plq_build(x,@exp,@exp); y=plq_eval(plqf,x); b = norm(y-exp(x))<1E-8; assert(all(all(b))); end function [b] = testlinear(testCase) function y=f(x),y=2*x+1; end; function dy=df(x),dy=2*ones(size(x)); end; x=linspace(-2,2,5)'; plqf = plq_build(x,@f,@df); y=plq_eval(plqf,x); b = norm(y-f(x))<1E-8; assert(all(all(b))); end function [b] = testpartiallylinear(testCase) function y=f(x),i=find(x>0);y=zeros(size(x));y(i)=x(i).^2;end function y=df(x),i=find(x>0);y=zeros(size(x));y(i)=2*x(i);end x=linspace(-2,2,5)'; plqf = plq_build(x,@f,@df); y=plq_eval(plqf,x); b = norm(y-f(x))<1E-8; assert(all(all(b))); end function [b] = testconjexp(testCase) function y=f(x),i1=find(x<0);i2=find(x==0);i3=find(x>0);y(i1)=inf*ones(size(i1));y(i2)=0;y(i3)=x(i3).*log(x(i3))-x(i3);end function y=df(x),i1=find(x<=0);i2=find(x>0);y(i1)=inf*ones(size(i1));y(i2)=log(x(i2));end x=linspace(0,20,3)'; plqf = plq_build(x,@f,@df); y = plq_eval(plqf,x); yy=f(x); i=find(x==0); yy(i)=inf*ones(size(i));%plq evaluates inf at 0 i=isinf(y); ii=isinf(yy);%need to test inf values separately b = (norm(y(~i)'-yy(~ii))<1E-8) & all(y(i)'==yy(i)); assert(all(all(b))); end function [b] = testconjexp_d(testCase) function y=f(x),i1=find(x<0);i2=find(x==0);i3=find(x>0);y(i1)=inf*ones(size(i1));y(i2)=0;y(i3)=x(i3).*log(x(i3))-x(i3);end function y=df(x),i1=find(x<=0);i2=find(x>0);y(i1)=inf*ones(size(i1));y(i2)=log(x(i2));end x=linspace(0,20,3)'; y=f(x); dy=df(x); plqf = plq_build_d(x,y,dy); y = plq_eval(plqf,x); yy=f(x);i=find(x==0);yy(i)=inf*ones(size(i));%plq evaluates inf at 0 i=isinf(y);ii=isinf(yy);%need to test inf values separately b = (norm(y(~i)'-yy(~ii))<1E-8); b = b & all(y(i)'==yy(i)); assert(all(all(b))); end %0th order model function [b] = testexp0(testCase) x=linspace(0,4)'; plqf = plq_build(x,@exp); y=plq_eval(plqf,x); b = norm(y-exp(x))<1E-8; assert(all(all(b))); end function [b] = testabs0(testCase) x=linspace(-4,4,5)'; plqf = plq_build(x,@abs); b = [0,0,-1,0;inf,0,1,0]==plqf; assert(all(all(b))); end function [b] = testabs0_d(testCase) x=linspace(-4,4,5)'; y=abs(x); plqf = plq_build_d(x,y); b = [0,0,-1,0;inf,0,1,0]==plqf; assert(all(all(b))); end function [b] = testx0(testCase) x=linspace(-4,4)'; function y=f(x),y=x; end; plqf = plq_build(x,@f); b = [inf,0,1,0]==plqf; assert(all(all(b))); end function [b] = testlinear0(testCase) x=linspace(-2,2,5)';function y=f(x),y=2*x+1; end; plqf = plq_build(x,@f); b = [inf,0,2,1]==plqf; assert(all(all(b))); end function [b] = testpartiallylinear0(testCase) function y=f(x),i=find(x>0);y=zeros(size(x));y(i)=x(i).^2;end x=linspace(-2,2,5)'; plqf = plq_build(x,@f); y=plq_eval(plqf,x); b = norm(y-f(x))<1E-8; assert(all(all(b))); end function [b] = testInf0(testCase) function y = f(x); ys = [inf;4/1;4/2;4/3;4/4;inf]; y = ys(double(x*4+1)); end x = 0:0.25:1.25; plqf = plq_build(x,@f,false,false,true); desired = [1/4,0,0,inf; 2/4,0,-8,6; 3/4,0,-8/3,10/3; 1,0,-4/3,7/3; inf,0,0,inf]; b = plqf - desired < 1E-6 | plqf == desired; assert(all(all(b))); end function [b] = testInf1(testCase) %function y = f(x); i=ieee(); ieee(2); y=ones(x)./x; ieee(i); endfunction %function s = df(x); i=ieee(); ieee(2); s=-ones(x)./(x.^2); ieee(i); endfunction function y = f(x); ys = [inf;4/1;4/2;4/3;4/4;inf]; y = ys(double(x*4+1)); end function dy = df(x); dys = -[inf;[4/1;4/2;4/3;4/4].^2;inf]; dy = dys(double(x*4+1)); end x = 0:0.25:1.25; plqf = plq_build(x,@f,@df,false,true); %desired = [0,0,0,inf; 1/3,0,-16,8; 0.6,0,-4,4; 6/7,0,-16/9,8/3; inf,0,-1,2]; desired = [1/4,0,0,inf; 1/3,0,-16,8; 3/5,0,-4,4; 6/7,0,-16/9,8/3; 1,0,-1,2; inf,0,0,inf]; b = plqf == desired | plqf - desired < 1E-6; assert(all(all(b))); end function [b] = testNeedEvalFptr(testCase) b = false; x = 0:0.5:3; f1 = plq_build(x, @exp, false, false); f2 = plq_build(x, @exp, false, true); b = isequal(f1, f2); assert(all(all(b))); end function [b] = testNeedEvalFunc(testCase) function y=f(x) if (size(x) ~= [1,1]) error('blah'); end; y=exp(x); end; b = false; x = 0:0.5:3; f1 = plq_build(x, @f, false, false); f2 = plq_build(x, @f, false, true); b = isequal(f1, f2); assert(all(all(b))); end function [b] = testNonconvexfctn(testCase) b=false; x=linspace(0,2*pi,4)'; result = plq_build(x,@sin,@cos); desired = []; %The desired result requires the x(i) values to be ordered. See result. end function [b] = testsoqs(testCase) function y = f(x); ys=[.0;.3;.5;.2;.6;1.2;1.3;1.0;1.0;1.0;0;-1.0];y=ys(double(x+1)); end function dy = df(x); dys = [.5;1;0;-.2;5;4;0;-.2;-.2;.3;-.9999;-1.001]; dy = dys(double(x+1)); end x=linspace(0,11,12)'; plqf = plq_build(x,@f,@df,true,false,'soqs'); desired = [0,0,0,0; .9,-.25,.5,0; 1,4.75,-8.5,4.05; 1.2,-2,5,-2.7]; b = (plqf(1:4,:) == desired) | abs(plqf(1:4,:) - desired) < 1E-6; assert(all(all(b))); end function [b] = testsoqs_noderiv(testCase) function y = f(x); ys=[.0;.3;.5;.2;.6;1.2;1.3;1.0;1.0;1.0;0;-1.0];y=ys(double(x+1)); end function dy = df(x); dys = [.5;1;0;-.2;5;4;0;-.2;-.2;.3;-.9999;-1.001]; dy = dys(double(x+1)); end x=linspace(0,11,12)'; plqf = plq_build(x,@f,false,true,false,'soqs'); desired = [0,0,0,0; .5,-.06,.36,0; 1,-.06,.36,0]; b = (plqf(1:3,:) == desired) | abs(plqf(1:3, :) - desired) < 1E-6; assert(all(all(b))); end function b = testsoqs1(testCase) function y=f(x), y=x.^4;end function dy=df(x), dy=4*x.^3;end x=linspace(-10,10,2)'; p = plq_build(x,@f,@df,false,false,'soqs','bounded'); d = [-10 0 0 inf;0 200 0 -10000;10 200 0 -10000;inf 0 0 inf]; b = plq_isEqual(p, d); assert(all(all(b))); end function b = testsoqs2(testCase) function y=f(x), y=x.^4;end function dy=df(x), dy=4*x.^3;end x=linspace(-10,10,2)'; b=false; % ierr=eval('plq_build(x,@f,@df,false,false,''soqs'',''wrongOption'');'); % b=ierr~= 0; %assert(all(all(b))) end
github
ylucet/CCA-master
plq_minPt_test.m
.m
CCA-master/tests/plq_minPt_test.m
2,092
utf_8
f65cdffb0d2e26077dfbd7d8fd1d3a99
function tests = plq_minPt_test() tests = functiontests(localfunctions); end % I = Indicator, E = Exponential, C = Conjugate, L = Linear, Q = Quadratic function b = prim(p, fmin, xmin) [fm,xm] = plq_minPt(p); b = isequal(fmin,fm) & isequal(xmin,xm); end function b = test1(testCase) p = [inf, 0, 1, 0]; fmin = -inf;xmin = []; b = prim(p,fmin,xmin); assert(b) end function b = test1b(testCase) p = [inf, 0, 0, 3]; fmin = 3;xmin = [0]; b = prim(p,fmin,xmin); assert(b) end function b = test2(testCase) p = [inf, 1, 0, 0]; fmin = 0;xmin = 0; b = prim(p,fmin,xmin); assert(b) end function b = test3(testCase) p = [0 0 -1 0;inf, 0, 1, 0];%abs fmin = 0;xmin = 0; b = prim(p,fmin,xmin); assert(b) end function b = test4(testCase) p = [-1 0 -1 -1;0 0 1 1;1 0 -1 1;inf, 0, 1, -1]; fmin = 0;xmin = [-1;1]; b = prim(p,fmin,xmin); assert(b) end function b = test5(testCase) %local + global min p =[-3 0 -0.5 -0.5;-2 0 2 7;0 0 -0.5 2;inf 0 2 2]; fmin = 1;xmin = -3; b = prim(p,fmin,xmin); assert(b) end function b = test6(testCase) p = [-1 0 0 inf;1 0 0 0;inf 0 0 inf];%I_[-1,1] fmin = 0;xmin = [1];%xmin=[-1;1]; b = prim(p,fmin,xmin); end function b = test7(testCase) p = [1 0 0 2];%I_{1} + 2 fmin = 2;xmin = [1]; b = prim(p,fmin,xmin); end function b = test8(testCase) p = [-15.495963 0. -0.6666667 -2.2597654; -5.3940994 0.0058845 -0.4842946 -0.8467499; -4.002795 0.100625 0.5377847 1.9098488; -3.8909938 -0.0993827 -1.0633951 -1.2947485; -0.3961698 0.100625 0.4930625 1.7333349; 0.9454451 -0.0993827 0.3345885 1.7019436; 4.1586957 0.100625 -0.0436042 1.8807238; 10.626398 0.0803995 0.1246192 1.5309288; inf 0. 1.8333333 -7.5478088]; xmin = -p(5,3)/2/p(5,2);fmin = plq_eval(p,xmin); b = prim(p,fmin,xmin); end function b = test9(testCase) %create a test where -b/2/a is not in interval p = [inf 1 0 0];q=[inf 0 -1 0.5]; p = plq_max(p,q);q=[inf 0 1 0.5]; p = plq_max(p,q); fmin = 0.5;xmin = 0; b = prim(p,fmin,xmin); end
github
ylucet/CCA-master
rock_test.m
.m
CCA-master/tests/rock_test.m
1,017
utf_8
a0ec30a22e9ef8f2982e5ecb0c6a59ee
function tests = rock_test() tests = functiontests(localfunctions); end % Author: Bryan Gardiner % For: Yves Lucet % Date: Summer 2008 function b = testRockBasic1(testCase) b = false; a = [1,2,4,5]; bm = [-5,-3,-1,10]; bp = [-3,-2, 1,20]; B = [a;bm;bp]; Rexp(:,:,1) = [1,0,-5,5;2,0,-3,3;4,0,-2,1;5,0,1,-11;inf,0,20,-106]; Rexp(:,:,2) = [1,0,-5,8;2,0,-3,6;4,0,-2,4;5,0,1,-8;inf,0,20,-103]; Rexp(:,:,3) = [1,0,-5,10;2,0,-3,8;4,0,-1,4;5,0,1,-4;inf,0,20,-99]; Rexp(:,:,4) = [1,0,-5,0;2,0,-3,-2;4,0,-1,-6;5,0,10,-50;inf,0,20,-100]; for k = 1:4 R(:,:,k) = plq_rock(B, k); end; b = isequal(Rexp, R); end function b = testRockDecrA(testCase) %exec("../loader.sce"); b = false; a = [ 1, 3, 7, 15]; bm = [-11,-10,-5,- 2]; bp = [-10,- 5,-3,- 1]; B = [a;bm;bp]; R0 = plq_rock(B, 2); R1 = plq_rock(B(:,end:-1:1), 2); b = isequal(R0, R1); end function testPlqRockNonIncrA(testCase) a = [1,2,2,3]; bl = [1,3,5,7]; br = [2,4,6,8]; A = [a;bl;br]; %%plq_rock(A, 4); end
github
ylucet/CCA-master
plq_check_test.m
.m
CCA-master/tests/plq_check_test.m
463
utf_8
107fd822df7f91bf0cbd3db320182676
function tests = plq_check_test() tests = functiontests(localfunctions); end function [b] = test1(testCase) p=[-1 0 0 inf;0 0 0 0; 1 0 0 1;inf 0 0 inf];%discontinuous b=~plq_check(p,2); assert(b) end function [b] = test2(testCase) p=[-1 0 0 inf;0 0 0 0; -0.5 0 0 0;inf 0 0 inf];%x nonincreasing b=~plq_check(p,1); b= b & plq_check(p,2); assert(b) end function [b] = test3(testCase) p=[0 0 -1 0;inf 0 1 0];%abs b=plq_check(p); assert(b) end
github
ylucet/CCA-master
gph_plot_test.m
.m
CCA-master/tests/gph_plot_test.m
1,841
utf_8
56cfadfcda9ffb0521109901da31f976
function tests = gph_plot_test() tests = functiontests(localfunctions); end % Unit test file for _gph_plotbounds function [b] = testPass1(testCase) fabs=[-1 0 0 1 ; -1 -1 1 1; 1 0 0 1 ]; L{1} = fabs; rect = gph_plotbounds(L); b = all(rect==[-1.2,-1.2,1.2,1.2]); assert(all(all(b))); end function [b] = testPass2(testCase) fabs=[-1 0 0 1 ; -1 -1 1 1; 1 0 0 1 ]; g=[-2 -1 -1 1 1 2; -1 -1 0 0 1 1; 1 0 0 0 0 1]; L{1} = fabs; L{2} = g; rect = gph_plotbounds(L); b = all(rect==[-2.4,-1.2,2.4,1.2]); assert(all(all(b))); end function [b] = testPass2a(testCase) h1=[-1 0 0 1; -2 -2 2 2;2 0 0 2];%2*abs h2=[-3 -2 -2 0 0 0.5;-1 -1 0 0 1 1;1 0 0 0 0 1]; L{1} = h1; L{2} = h2; rect = gph_plotbounds(L); b = all(rect==[-3.4,-2.4,1.4,2.4]); assert(all(all(b))); end function [b] = testPass1_gph_yCoord(testCase) y = gph_yCoord(-2,0,-1,1,-1);%horizontal line b = (y == -1); y = gph_yCoord(-2,0,-1,1,0);%angled line b = b & (y==-3); y = gph_yCoord(-1,0,0,0,1); b = b & (y==-inf); y = gph_yCoord(0,0,-1,1,0);%angled line b = b & (y==-1); assert(all(all(b))); end function [b] = testPass1_gph_extendGph(testCase) fabs=[-1 0 0 1 ; -1 -1 1 1; 1 0 0 1 ]; L{1} = fabs; rect = gph_plotbounds(L); b=all(rect==[-1.2,-1.2,1.2,1.2]); G=gph_extendGph(fabs,rect); b = b & all(G==[-1.2 -1 0 0 1 1.2;-1 -1 -1 1 1 1]); assert(all(all(b))); end function [b] = testPass2_gph_extendGph(testCase) f=[-1 -1 1 1;-1 0 0 1;0 0 0 0]; L{1} = f; rect = gph_plotbounds(L); b=all(rect==[-1.2,-1.2,1.2,1.2]); G=gph_extendGph(f,rect); b = b & all(G==[-1 -1 -1 1 1 1;-1.2 -1 0 0 1 1.2]); end %disable plotting %function [b] = testPass_gph_plot() % fabs=[-1 0 0 1 ; -1 -1 1 1; 1 0 0 1 ]; % while (winsid() ~= []); xdel(); end; % clf();gph_plot(fabs); % while (winsid() ~= []); xdel(); end; % return %endfunction
github
ylucet/CCA-master
epsUnique_test.m
.m
CCA-master/tests/epsUnique_test.m
766
utf_8
9fe5b12441090c3511a93dbd37640705
function tests = epsUnique_test() tests = functiontests(localfunctions); end function [b] = test1(testCase) X=[1;1;2];eps=1E-6; [Xu,ku]=epsUnique(X,eps); b=isequal(Xu,[1;2]) & isequal(ku,[1;3]); assert(b) end function [b] = test2(testCase) eps=1E-6; X=[1;1;1;1;1+eps/10;2]; [Xu,ku]=epsUnique(X,eps); b=isequal(Xu,[1;2]) & isequal(ku,[1;6]); assert(b) end function [b] = test3(testCase) eps=1E-6; X=linspace(0,eps,4)'; [Xu,ku]=epsUnique(X,eps,true); b=isequal(Xu,[0;eps]) & isequal(ku,[1;4]); assert(b) end function [b] = runTestFile(testCase) b = true; b = checkForFail(testWrapper(test1,'test1'), b); b = checkForFail(testWrapper(test2,'test2'), b); b = checkForFail(testWrapper(test3,'test3'), b); assert(b) end
github
ylucet/CCA-master
plq_max_test.m
.m
CCA-master/tests/plq_max_test.m
8,048
utf_8
32cfd6fc916d604c3ae8c439d66df850
function tests = plq_max_test() tests = functiontests(localfunctions); end %L: Linear, Q: Quadratic, I: Indicator, PW: Piecewise function [b] = testLLMax(testCase) b = false; plqf1 = [inf,0,1,0]; plqf2 = [inf,0,-1,0]; result = plq_max(plqf1,plqf2); % x=linspace(-5,5,25)'; % ymax = plq_eval(result,x); % plot2d(x,ymax); desired = [0,0,-1,0;inf,0,1,0]; b = all(result==desired); assert(all(all(b))); end function [b] = testQLMax(testCase) b = false; plqf = [inf,1,0,0]; plqg = [inf,0,0,1]; result = plq_max(plqf,plqg); % x=linspace(-5,5,25)'; % ymax = plq_eval(result,x); % plot2d(x,ymax); desired = [-1,1,0,0;1,0,0,1;inf,1,0,0]; b = all(result==desired); assert(all(all(b))); end function [b] = testQLQMax(testCase) b = false; plqf1 = [-1,1,0,0;1,0,0,1;inf,1,0,0]; plqf2 = [0,1,0,0;2,0,1,0;inf,1,0,-2]; result = plq_max(plqf1,plqf2); result = plq_clean(result); % x=linspace(-5,5,100)'; % f0=plq_eval(result,x); % f1=plq_eval(plqf1,x); % f2=plq_eval(plqf2,x); % plot2d(x,[f0,f1,f2]); % a=gca(); % Handle on axes entity % a.thickness=3; % poly1= a.children.children(3); %store polyline handle into poly1 % poly1.foreground = 2; % another way to change the style % poly1.thickness = 3; desired = [-1,1,0,0;1,0,0,1;inf,1,0,0]; b = all(result==desired); assert(all(all(b))); end function [b] = testQLQ2Max(testCase) b = false; plqf1 = [0,0,-2,0;inf,0,2,0]; plqf2 = [0,0,-1,1;inf,0,1,1]; result = plq_max(plqf1,plqf2); result = plq_clean(result); % x=linspace(-5,5,100)'; % f0=plq_eval(result,x); % f1=plq_eval(plqf1,x); % f2=plq_eval(plqf2,x); % plot2d(x,[f0,f1,f2]); % a=gca(); % Handle on axes entity % a.thickness=3; % poly1= a.children.children(3); %store polyline handle into poly1 % poly1.foreground = 2; % another way to change the style % poly1.thickness = 3; % desired = [-1,0,-2,0;0,0,-1,1;1,0,1,1;inf,0,2,0]; b = all(result==desired); assert(all(all(b))); end function [b] = testQQMax(testCase) b = false; plqf1 = [inf,1,0,0]; plqf2 = [inf,1/10,0,1]; result = plq_max(plqf1,plqf2); % x=linspace(-5,5,100)'; % f0=plq_eval(result,x); % f1=plq_eval(plqf1,x); % f2=plq_eval(plqf2,x); % plot2d(x,[f0,f1,f2]); % a=gca(); % Handle on axes entity % a.thickness=3; % poly1= a.children.children(3); %store polyline handle into poly1 % poly1.foreground = 2; % another way to change the style % poly1.thickness = 3; desired = [- 1.0540926,1,0,0;1.0540926,0.1,0,1;inf,1,0,0]; b = all(result(:,2:end)==desired(:,2:end)); assert(all(all(b))); end function [b] = testQQMaxdl(testCase) b = false; plqf1 = [inf,1,0,0]; plqf2 = [inf,1,2,-1]; result = plq_max(plqf1,plqf2); % x=linspace(-5,5,100)'; % f0=plq_eval(result,x); % f1=plq_eval(plqf1,x); % f2=plq_eval(plqf2,x); % plot2d(x,[f0,f1,f2]); % a=gca(); % Handle on axes entity % a.thickness=3; % poly1= a.children.children(3); %store polyline handle into poly1 % poly1.foreground = 2; % another way to change the style % poly1.thickness = 3; desired = [0.5,1,0,0;inf,1,2,-1]; b = all(result==desired); assert(all(all(b))); end function [b] = testQQMaxdq1(testCase) b = false; plqf1 = [inf,1,0,0]; plqf2 = [inf,-1,2,-1]; result = plq_max(plqf1, plqf2); % x=linspace(-5,5,100)'; % f0=plq_eval(result,x); % f1=plq_eval(plqf1,x); % f2=plq_eval(plqf2,x); % plot2d(x,[f0,f1,f2]); % a=gca(); % Handle on axes entity % a.thickness=3; % poly1= a.children.children(3); %store polyline handle into poly1 % poly1.foreground = 2; % another way to change the style % poly1.thickness = 3; desired = [inf,1,0,0]; b = isequal(result, desired); assert(all(all(b))); end function [b] = testQQMaxdq2(testCase) b = false; plqf1 = [inf,1,0,0]; plqf2 = [inf,-1,0,0]; result = plq_max(plqf1, plqf2); % x=linspace(-5,5,100)'; % f0=plq_eval(result,x); % f1=plq_eval(plqf1,x); % f2=plq_eval(plqf2,x); % plot2d(x,[f0,f1,f2]); % a=gca(); % Handle on axes entity % a.thickness=3; % poly1= a.children.children(3); %store polyline handle into poly1 % poly1.foreground = 2; % another way to change the style % poly1.thickness = 3; desired = [inf,1,0,0]; b = isequal(result, desired); assert(all(all(b))); end function [b] = testQLQMax1(testCase) b = false; plqf1=[1,1,0,0;3, 0, 2, -1;inf,3,-16,26]; plqf2=[-1,1,0,0;0,1,0,0;1, 0, 1, 0;inf,3, -4, 2]; result = plq_max(plqf1,plqf2); result = plq_clean(result); % x=linspace(-5,5,100)'; % f0=plq_eval(result,x); % f1=plq_eval(plqf1,x); % f2=plq_eval(plqf2,x); % plot2d(x,[f0,f1,f2]); % a=gca(); % Handle on axes entity % a.thickness=3; % poly1= a.children.children(3); %store polyline handle into poly1 % poly1.foreground = 2; % another way to change the style % poly1.thickness = 3; desired = [0,1,0,0;1,0,1,0;inf,3,-4,2]; b = all(result==desired); assert(all(all(b))); end function [b] = testII1Max(testCase) b = false; plqf1 = [5,0,0,2]; plqf2 = [5,0,0,5]; result = plq_max(plqf1,plqf2); desired = [5,0,0,5]; b = all(result==desired); assert(all(all(b))); end function [b] = testII2Max(testCase) b = false; plqf1 = [5,0,0,-5]; plqf2 = [5,0,0,-8]; result = plq_max(plqf1,plqf2); desired = [5,0,0,-5]; b = all(result==desired); assert(all(all(b))); end function [b] = testII3Max(testCase) b = false; plqf1 = [3,0,0,2]; plqf2 = [5,0,0,5]; result = plq_max(plqf1,plqf2); desired = [inf,0,0,inf]; b = all(result==desired); assert(all(all(b))); end function [b] = testII4Max(testCase) b = false; plqf1 = [5,0,0,2]; plqf2 = [3,0,0,5]; result = plq_max(plqf1,plqf2); desired = [inf,0,0,inf]; b = all(result==desired); assert(all(all(b))); end function [b] = testQIMax(testCase) b = false; plqf1 = [inf,1,0,0]; plqf2 = [2,0,0,5]; result = plq_max(plqf1,plqf2); desired = [2,0,0,5]; b = all(result==desired); assert(all(all(b))); end function [b] = testIQMax(testCase) b = false; plqf1 = [2,0,0,5]; plqf2 = [inf,1,0,0]; result = plq_max(plqf1,plqf2); desired = [2,0,0,5]; b = all(result==desired); assert(all(all(b))); end function [b] = testIQ2Max(testCase) b = false; plqf1 = [2,0,0,3]; plqf2 = [inf,1,0,0]; result = plq_max(plqf1,plqf2); desired = [2,0,0,4]; b = all(result==desired); assert(all(all(b))); end function [b] = testQI2Max(testCase) b = false; plqf1 = [inf,1,0,0]; plqf2 = [2,0,0,3]; result = plq_max(plqf1,plqf2); desired = [2,0,0,4]; b = all(result==desired); assert(all(all(b))); end function [b] = testQQ_dqBoundsOutside(testCase) b = false; p1 = [0,1,2,2; inf,0,0,inf]; p2 = [0,0,0,inf; inf,1,-2,1]; q1 = plq_lft(p1); q2 = plq_lft(p2); result = plq_max(q1,q2); % Assuming the conjugate is computed correctly. expected = [-0.5, 0.25, -1, -1; ... inf, 0.25, 1, 0]; b = all(result == expected); assert(all(all(b))); end %TODO More tests for plq_max %TODO Code Addition function again! function [b] = runTestFile(testCase) b = true; b = checkForFail(testWrapper(testLLMax,'testLLMax'), b); b = checkForFail(testWrapper(testQLMax,'testQLMax'), b); b = checkForFail(testWrapper(testQLQMax,'testQLQMax'), b); b = checkForFail(testWrapper(testQLQ2Max,'testQLQ2Max'), b); b = checkForFail(testWrapper(testQQMax,'testQQMax'), b); b = checkForFail(testWrapper(testQQMaxdl,'testQQMaxdl'), b); b = checkForFail(testWrapper(testQQMaxdq1,'testQQMaxdq1'), b); b = checkForFail(testWrapper(testQQMaxdq2,'testQQMaxdq2'), b); b = checkForFail(testWrapper(testQLQMax1,'testQLQMax1'), b); b = checkForFail(testWrapper(testII1Max,'testII1Max'), b); b = checkForFail(testWrapper(testII2Max,'testII2Max'), b); b = checkForFail(testWrapper(testII3Max,'testII3Max'), b); b = checkForFail(testWrapper(testII4Max,'testII4Max'), b); b = checkForFail(testWrapper(testQIMax,'testQIMax'), b); b = checkForFail(testWrapper(testIQMax,'testIQMax'), b); b = checkForFail(testWrapper(testIQ2Max,'testIQ2Max'), b); b = checkForFail(testWrapper(testQI2Max,'testQI2Max'), b); b = checkForFail(testWrapper(testQQ_dqBoundsOutside,'testQQ_dqBoundsOutside'), b); assert(all(all(b))); end
github
ylucet/CCA-master
plq_eval_test.m
.m
CCA-master/tests/plq_eval_test.m
1,197
utf_8
56b29d6c76bfd5148a2e5d2933802243
function tests = plq_eval_test() tests = functiontests(localfunctions); end % Test-script for plq_eval (Yves Lucet - 2006-06-21) % % unit tests ========================================================== function [b] = testXinsidex(testCase) X=[1;2;4;5;7;8;9]; plqf=[3,0.5,0,0;6,0,0,0;inf,0,1,0]; [y,k] = plq_eval(plqf,X); b = isequal(k, [1,2,3;1,3,5;2,4,7]); b = isequal(y, [0.5;2;0;0;7;8;9]) & b; assert(b); end function [b] = testXemptybeforex(testCase) X=[4;5;7;8;9]; plqf=[3,0.5,0,0;6,0,0,0;inf,0,1,0]; [y,k] = plq_eval(plqf,X); b = isequal(k, [2,3; 1,3;2,5]); b = isequal(y, [0;0;7;8;9]) & b; assert(b) end function [b] = testXallbeforex(testCase) X=[4;5;7;8;9]; plqf=[10,0.5,0,0;15,0,0,0;inf,0,1,0]; [y,k] = plq_eval(plqf,X); b = isequal(k, [1;1;5]); b = isequal(y, [8;12.5;24.5;32;40.5]) & b; assert(b) end function [b] = testXalllastx(testCase) X=[4;5;7;8;9]; plqf=[-2,0.5,0,0;1,0,0,0;inf,0,1,0]; [y,k] = plq_eval(plqf,X); b = isequal(k, [3;1;5]); b = b & isequal(y, [4;5;7;8;9]); assert(b) end function [b] = testIndicator(testCase) X=(-5:5)'; plqf=[0,0,0,1]; y = plq_eval(plqf,X); yy=inf*ones(size(X)); yy(6)=1; b = isequal(y, yy); assert(b) end
github
ylucet/CCA-master
plq_proj_test.m
.m
CCA-master/tests/plq_proj_test.m
1,122
utf_8
6e2c687000e97947354aa5350ad41526
function tests = plq_proj_test() tests = functiontests(localfunctions); end % Author: Yves Lucet % Whatsit: Test file for plq_proj function [b] = testProj(testCase) b = false; if (exist('quapro')) n=200; x=linspace(-2,2,n)';f=abs(abs(x)-1); [plqr,fr]=plq_proj(f,x,2); pr=plq_eval(plqr,x); %result validated symbolically with Maple plqd = [-sqrt(2),0,-1,-1;sqrt(2),0,0,sqrt(2)-1;inf,0,1,-1]; pd=plq_eval(plqd,x); fd = 4 - 8*sqrt(2)/3; b = all(norm(pr-pd)<1E-4) & abs(fr-fd)<1E-4; else b = true; end; assert(b) end function b=testProjNormTooHigh(testCase) %need to finish the test! b=true; if (exist('quapro')) n = 200; x = linspace(-2, 2, n)'; f = abs(abs(x) - 1); [plqr, fr] = plq_proj(f, x, 3); else %%cerror('Quapro not installed! Install it to call plq_proj'); end; assert(b) end function [b] = runTestFile(testCase) b = true; b = checkForFail(testWrapper(testProj, 'testProj'), b); b = checkForFail(errorTestWrapper(testProjNormTooHigh, 'testProjNormTooHigh'), b); assert(b) end
github
ylucet/CCA-master
plq_scalar_test.m
.m
CCA-master/tests/plq_scalar_test.m
3,865
utf_8
ce7c53d773b04e3bf179ca20dcb05878
function tests = plq_scalar_test() tests = functiontests(localfunctions); end % Unit test file for gph_scalar function [b] = testAbs(testCase) p =[0 0 -1 0; inf 0 1 0];%abs function q=plq_scalar(p,3); qq=[0 0 -3 0; inf 0 3 0]; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=[inf 0 0 0]; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[0 0 2 0; inf 0 -2 0]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = testInd(testCase) p=[-1 0 0 inf;1 0 0 0 ;inf 0 0 inf]; q=plq_scalar(p,3); qq=p; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=p; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[-1 0 0 -inf;1 0 0 0 ;inf 0 0 -inf]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = testPL(testCase) % A piecewise linear function: % x<0: y=-x % 0<x<1: y=0 % 1<x: y=x-1 G = [-1, 0, 0, 1, 1, 2; -1, -1, 0, 0, 1, 1; 1, 0, 0, 0, 0, 1]; p=plq_gph(G); q=plq_scalar(p,3); qq=[0 0 -3 0;1 0 0 0;inf 0 3 -3]; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=[inf 0 0 0]; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[0 0 2 0;1 0 0 0;inf 0 -2 2]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = testPLQ1(testCase) b = false; % A PLQ function: % x<-1: y=(x+1)^2 % -1<x<1: y=0 % 1<x: y=(x-1)^2 p=[-1 1 2 1;1 0 0 0;inf 1 -2 1]; q=plq_scalar(p,3); qq=[-1 3 6 3;1 0 0 0;inf 3 -6 3]; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=[inf 0 0 0]; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[-1 -2 -4 -2;1 0 0 0;inf -2 4 -2]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = testPLQ2(testCase) b = false; % A PLQ function: % x in [-1,1]: 0 % otherwise: x^2 - 1 p=[-1 1 0 -1;1 0 0 0;inf 1 0 -1]; q=plq_scalar(p,3); qq=[-1 3 0 -3;1 0 0 0;inf 3 0 -3]; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=[inf 0 0 0]; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[-1 -2 0 2;1 0 0 0;inf -2 0 2]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = testQuadratic(testCase) p=[inf,1,0,0]; q=plq_scalar(p,3); qq=[inf,3,0,0]; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=[inf 0 0 0]; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[inf,-2,0,0]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = testLinear(testCase) p=[inf,0,1,0]; q=plq_scalar(p,3); qq=[inf,0,3,0]; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=[inf 0 0 0]; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[inf,0,-2,0]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = testIndicatorSingleton(testCase) p=[1,0,0,2]; q=plq_scalar(p,3); qq=[1,0,0,6]; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=[1 0 0 0]; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[1,0,0,-4]; b = b & plq_isEqual(q,qq); b = b & ~(q(1)==inf); assert(b) end function [b] = testIndMinus(testCase) p=[-1 0 0 inf;1 0 0 0 ;inf 0 0 inf]; p=plq_scalar(p,-1); q=plq_scalar(p,3); qq=p; b = plq_isEqual(q,qq); q=plq_scalar(p,0); qq=p; b = b & plq_isEqual(q,qq); q=plq_scalar(p,-2); qq=[-1 0 0 inf;1 0 0 0 ;inf 0 0 inf]; b = b & plq_isEqual(q,qq); assert(b) end function [b] = runTestFile(testCase) b = true; b = checkForFail(testWrapper(testAbs,'testAbs'), b); b = checkForFail(testWrapper(testInd,'testInd'), b); b = checkForFail(testWrapper(testPL,'testPL'), b); b = checkForFail(testWrapper(testPLQ1,'testPLQ1'), b); b = checkForFail(testWrapper(testPLQ2,'testPLQ2'), b); b = checkForFail(testWrapper(testQuadratic,'testQuadratic'), b); b = checkForFail(testWrapper(testLinear,'testLinear'), b); b = checkForFail(testWrapper(testIndicatorSingleton,'testIndicatorSingleton'), b); b = checkForFail(testWrapper(testIndMinus,'testIndMinus'), b); assert(b) end
github
ylucet/CCA-master
plq_gpa_test.m
.m
CCA-master/tests/plq_gpa_test.m
1,301
utf_8
779ac07969e1615ae3c1c2fb0e2f6c31
function tests = plq_gpa_test() tests = functiontests(localfunctions); end % I = Indicator, E = Exponential, C = Conjugate, L = Linear, Q = Quadratic function [b] = testAbs(testCase) p0=[0,0,-1,0;inf,0,1,0];p1=p0; p =plq_gpa(p0,p1,0.5,1); q = [-0.2 0 -1 -0.1;0.2 2.5 0 0;inf,0,1,-0.1]; b = plq_isEqual(p,q); assert(b) end function [b] = testZero(testCase) p0=[inf,0,0,0];p1=p0; p =plq_gpa(p0,p1,0.5,1); q = [inf,0,0,0]; b = plq_isEqual(p,q); assert(b) end function [b] = testX(testCase) p0=[inf,1,0,0];p1=p0; p =plq_gpa(p0,p1,0.5,1); q = [inf,0.714285714,0,0]; b = plq_isEqual(p,q); assert(b) end function [b] = testL2I(testCase) p0=[inf,0,0,0];p1=[0,0,0,0]; p =plq_gpa(p0,p1,0.5,1); q = [inf,0.416666666666,0,0]; b = plq_isEqual(p,q); assert(b) end function [b] = testL2Q(testCase) p0=[inf,0,0,0];p1=[inf,0.5,0,0]; p =plq_gpa(p0,p1,0.5,1); q = [inf,0.15625,0,0]; b = plq_isEqual(p,q); assert(b) end function [b] = runTestFile(testCase) b = true; b = checkForFail(testWrapper(testAbs, 'testAbs'), b); b = checkForFail(testWrapper(testZero, 'testZero'), b); b = checkForFail(testWrapper(testX, 'testX'), b); b = checkForFail(testWrapper(testL2I, 'testL2I'), b); b = checkForFail(testWrapper(testL2Q, 'testL2Q'), b); assert(b) end
github
ylucet/CCA-master
gph_lft_test.m
.m
CCA-master/tests/gph_lft_test.m
3,172
utf_8
ae2eaff95ae2cab27e1d839f20556c26
function tests = gph_lft_test() tests = functiontests(localfunctions); end % Unit test file for gph_lft function b = testIsBounded(testCase) g = [-1, 0, 0, 1;-1, -1, 1, 1;1, 0, 0, 1];%abs b = all(gph_isBounded(g)==[false false]); g = [-1 -1 1 1;-1 0 0 1;inf 0 0 inf];%I_[-1,1] b = b & all(gph_isBounded(g)==[true true]); g = [-1 -1 0 1;-1 0 0 1;inf 0 0 0.5];%(x<0?-x:x^2)^* b = b & all(gph_isBounded(g)==[true false]); g = [-1 0 1 1;-1 0 0 1;0.5 0 0 inf];%(x<0?x^2:-x)^* b = b & all(gph_isBounded(g)==[false true]); assert(all(all(b))); end function [b] = testAbs(testCase) b = false; %abs function G = [-1, 0, 0, 1; ... -1, -1, 1, 1; ... 1, 0, 0, 1]; if ~gph_check(G) return; end; Gs = gph_lft(G); p = plq_gph(G); q=plq_lft(p);% I_[0,1] expected=gph_plq(q); b = all(Gs == expected); assert(all(all(b))); end function [b] = testInd(testCase) b = false; %indicator function I_[-1,1]. G = [-1, -1, 1, 1; ... -1, 0, 0, 1; ... inf, 0, 0, inf]; if ~gph_check(G) return; end; Gs = gph_lft(G); % Abs function expected = [-1, 0, 0, 1; ... -1, -1, 1, 1; ... 1, 0, 0, 1]; b = all(Gs == expected); assert(all(all(b))); end function [b] = testPL(testCase) b = false; % A piecewise linear function: % x<0: y=-x % 0<x<1: y=0 % 1<x: y=x-1 G = [-1, 0, 0, 1, 1, 2; ... -1, -1, 0, 0, 1, 1; ... 1, 0, 0, 0, 0, 1]; if ~gph_check(G) return; end; Gs = gph_lft(G); expected = [-1, -1, 0, 0, 1, 1; ... -1, 0, 0, 1, 1, 2; ... inf, 0, 0, 0, 1, inf]; b = all(Gs == expected); assert(all(all(b))); end function [b] = testPLQ1(testCase) b = false; % A PLQ function: % x<-1: y=(x+1)^2 % -1<x<1: y=0 % 1<x: y=(x-1)^2 G = [-2, -1, 1, 2; ... -2, 0, 0, 2; ... 1, 0, 0, 1]; if ~gph_check(G) return; end; % The conjugate of the PLQ function is: % x<0: y = 0.25*x^2 - x % x>0: y = 0.25*x^2 + x Gs = gph_lft(G); p = plq_gph(G);q = plq_lft(p);Ge = gph_plq(q); b = gph_isEqual(Gs,Ge); assert(all(all(b))); end function [b] = testPLQ2(testCase) b = false; % A PLQ function: % x in [-1,1]: 0 % otherwise: x^2 - 1 G = [-2, -1, -1, 1, 1, 2; ... -4, -2, 0, 0, 2, 4; ... 3, 0, 0, 0, 0, 3]; if ~gph_check(G) return; end; % The conjugate of the PLQ function is: % x<-2: y = 0.25*x^2 + 1 % -2<x<0: y = -x % 0<x<2: y = x % 2<x: y = 0.25*x^2 + 1 Gs = gph_lft(G); p = plq_gph(G);q=plq_lft(p);Ge = gph_plq(q); b = gph_isEqual(Gs,Ge); assert(all(all(b))); end function [b] = testQuadratic(testCase) p=[inf,1,0,0]; P=gph_plq(p); b=gph_check(P); Q=gph_lft(P); q=plq_lft(p); QQ=gph_plq(q); b = b & gph_isEqual(Q,QQ); assert(all(all(b))); end function [b] = testLinear(testCase) p=[inf,0,1,0];P=gph_plq(p);b=gph_check(P); Q=gph_lft(P);q=plq_lft(p);QQ=gph_plq(q); b = b & gph_isEqual(Q,QQ); assert(all(all(b))); end function [b] = testIndicatorSingleton(testCase) p=[1,0,0,2]; P=gph_plq(p); b=gph_check(P); Q=gph_lft(P); q=plq_lft(p); QQ=gph_plq(q); b = b & gph_isEqual(Q,QQ); assert(all(all(b))); end
github
ylucet/CCA-master
plq_me_test.m
.m
CCA-master/tests/plq_me_test.m
1,576
utf_8
6a393b4921d0571cb4962d44258ac6ca
function tests = plq_me_test() tests = functiontests(localfunctions); end function [b] = testMELineWrapper(testCase) b = false; lambda=1; fctn = [inf,0,1,1]; result = plq_me(fctn,lambda); desired = [inf, 0, 1, 1/2]; b = all(result==desired); assert(b); end function [b] = testMEQuadraticWrapper(testCase) b = false; lambda=1; fctn = [inf,1/2,0,0]; result = plq_me(fctn,lambda); desired = [inf, 1/4, 0, 0]; b = all(result==desired); assert(b); end function [b] = testMEIndicatorWrapper(testCase) b = false; lambda = 1; plqf = [5,0,0,1]; result = plq_me(plqf,lambda); desired = [inf,0.5,- 5, 13.5]; b = all(result==desired); assert(b); end function [b] = testMEnonconvex(testCase) b = false; lambda = 1;plqf=[-1,0,-1,-1;0,0,1,1;1,0,-1,1;inf,0,1,-1]; result = plq_me(plqf,lambda,false); desired = [-2,0,-1,-1.5;0,0.5,1,0.5;2,0.5,-1,0.5;inf,0,1,-1.5]; b = (result==desired); assert(all(all(b))); end function [b] = testMaxScale1(testCase) b = false; f = [0,-1,0,0;inf,-2,0,0]; desired = -1/2/(-2); result = plq_me_max_scale(f); b = isequal(desired, result); assert(b); end function [b] = testMaxScale2(testCase) b = false; f = [0,1,0,0;inf,0,1,0]; desired = inf; result = plq_me_max_scale(f); b = isequal(desired, result); assert(b); end function [b] = testMaxScale3(testCase) b = false; f1 = [0,-1,0,0;inf,-2,0,0]; f2 = [1,0,1,0;2,0,-1,2;inf,-3,0,0]; m1 = plq_me_max_scale(f1); m2 = plq_me_max_scale(f2); m = plq_me_max_scale(f1, f2); b = (isequal(m, 1/6) & m == min(m1, m2)); assert(b); end
github
ylucet/CCA-master
plq_prox_test.m
.m
CCA-master/tests/plq_prox_test.m
2,481
utf_8
da01606f2a2a4ed5e18e565307a726df
function tests = gph_me_test() tests = functiontests(localfunctions); end %perform all tests %p: input plq function %lambda: input real number lambda >0 function b = prim(p, lambda) m=plq_me(p,lambda); r=plq_prox(p,lambda);%monotone but nonconvex %since there is no plq_compose function %we numerically evaluate the moreau envelope %computed directly and through the proximal mapping dx=linspace(-10,10)'; dy=plq_eval(r,dx); dp=plq_eval(p,dy); dz=dp+(dx-dy).^2/(2*lambda); dm=plq_eval(m,dx); b=all((dm-dz)+1); end function b = testAbs(testCase) p=[0 0 -1 0; inf 0 1 0];lambda =2; b = prim(p,lambda); assert(all(all(b))) end function b = testPLQ0(testCase) p=[inf 1 0 0];lambda=3; b = prim(p,lambda); assert(all(all(b))) end function b = testPLQ1(testCase) % A PLQ function: % x<-1: y=(x+1)^2 % -1<x<1: y=0 % 1<x: y=(x-1)^2 p=[-1 1 2 1;1 0 0 0;inf 1 -2 1]; lambda=3; b = prim(p,lambda); assert(all(all(b))) end function b = testPL(testCase) % A piecewise linear function: % x<0: y=-x % 0<x<1: y=0 % 1<x: y=x-1 p = [0 0 -1 0;1 0 0 0;inf 0 1 -1]; lambda=20; b = prim(p,lambda); assert(all(all(b))) end function b = testPLQ2(testCase) % A PLQ function: % x in [-1,1]: 0 % otherwise: x^2 - 1 p=[-1 1 0 -1;1 0 0 0;inf 1 0 -1]; lambda=3/4; b = prim(p,lambda); assert(all(all(b))) end function b = testQuadratic(testCase) p=[inf,1,0,0]; lambda=1/10; b = prim(p,lambda); assert(all(all(b))) end function b = testLinear(testCase) p=[inf,0,1,0]; lambda=1/3; b = prim(p,lambda); assert(all(all(b))) end function b = testIndicatorSingleton(testCase) p=[1,0,0,2]; lambda=30.5; b = prim(p,lambda); assert(all(all(b))) end function b = testInd(testCase) p=[-1 0 0 inf;1 0 0 0 ;inf 0 0 inf]; lambda=10; b = prim(p,lambda); assert(all(all(b))) end function b = runTestFile(testCase) b = true; b = checkForFail(testWrapper(testPLQ0,'testPLQ0'), b); b = checkForFail(testWrapper(testAbs,'testAbs'), b); b = checkForFail(testWrapper(testPL,'testPL'), b); b = checkForFail(testWrapper(testPLQ1,'testPLQ1'), b); b = checkForFail(testWrapper(testPLQ2,'testPLQ2'), b); b = checkForFail(testWrapper(testQuadratic,'testQuadratic'), b); b = checkForFail(testWrapper(testLinear,'testLinear'), b); b = checkForFail(testWrapper(testIndicatorSingleton,'testIndicatorSingleton'), b); b = checkForFail(testWrapper(testInd,'testInd'), b); assert(all(all(b))) end
github
ylucet/CCA-master
gph_me_test.m
.m
CCA-master/tests/gph_me_test.m
3,440
utf_8
26f294d4b3fb39fc2db0705af0255e47
function tests = gph_me_test() tests = functiontests(localfunctions); end % Unit test file for gph_me %ME-Line Y=X+1 function [b] = testMELineWrapper(testCase) b = false; lambda = 1; gph = [0 1; 1 1; 1 2]; % f(x) = x + 1 gphme = gph_me(gph, lambda); X = (-5:0.5:5)'; result = gph_eval(gphme, X); desired = X + 1/2; % e_f(x) = x + 1/2 b = all(result == desired); assert(all(all(b))); end function [b] = testMEQuadraticWrapper(testCase) b = false; lambda=1; gph = [-1 1; -1 1; 0.5 0.5]; % f(x) = 1/2*x^2 gphme = gph_me(gph, lambda); X = (-3:0.5:3)'; result = gph_eval(gphme, X); desired = 1/4 * X.^2; b = all(result == desired); assert(all(all(b))); end function [b] = testMEIndicatorWrapper(testCase) b = false; lambda = 1; gph = [5 5; -1 1; 1 1]; % Ind. f(5) = 1 gphme = gph_me(gph, lambda); X = (-3:0.5:3)'; result = gph_eval(gphme, X); desired = 1/2*X.^2 - 5.*X + 13.5; b = all(result == desired); assert(all(all(b))); end function [b] = testUnbSmall0(testCase) eps = 1e-10; b = false; lambda = 1; plq = [0,0,-1,0; inf,0,1,0];%abs expected = plq_me(plq, lambda); gph = gph_plq(plq); gphme = gph_me(gph, lambda); actual = plq_gph(gphme); b = all(actual == expected | abs(actual - expected) < eps); %scf(); %plq_plot(expected, actual); %gph_plot(gphme, gph_plq(expected)); assert(all(all(b))); end function [b] = testUnbSmall1(testCase) eps = 1e-10; b = false; lambda = 1; plq = [0,0,-1,0; 1,0,0,0; inf,1,-2,1]; expected = plq_me(plq, lambda); gph = gph_plq(plq); gphme = gph_me(gph, lambda); actual = plq_gph(gphme); b = all(actual == expected | abs(actual - expected) < eps); %scf(); %plq_plot(expected, actual); %gph_plot(gphme, gph_plq(expected)); assert(all(all(b))); end function [b] = testUnbBig(testCase) eps = 1e-10; b = false; lambda = 1; plq = [-2,0,-2,-2; -1,0,-1.5,-1; 0,0,-0.5,0; 1,0,0,0; 2,0,1,-1; inf,1,-2,1]; expected = plq_me(plq, lambda); gph = gph_plq(plq); gphme = gph_me(gph, lambda); actual = plq_gph(gphme); b = all(actual == expected | abs(actual - expected) < eps); %scf(); %plq_plot(expected, actual); %gph_plot(gphme, gph_plq(expected)); assert(all(all(b))); end function [b] = testLowerBounded(testCase) eps = 1e-10; b = false; lambda = 2; % (x-5)^2+1 = x^2 - 10x + 25 + 1 plq = [2,0,0,inf; 5,0,-1,6; inf,1,-10,26;]; expected = plq_me(plq, lambda); gph = gph_plq(plq); gphme = gph_me(gph, lambda); actual = plq_gph(gphme); b = all(actual == expected | abs(actual - expected) < eps); assert(all(all(b))); end function [b] = testUpperBounded(testCase) eps = 1e-10; b = false; lambda = 3; % (x-1)^2+1 = x^2 - 2x + 1 + 1 plq = [1,1,-2,2; 5,0,1,0; inf,0,0,inf]; expected = plq_me(plq, lambda); gph = gph_plq(plq); gphme = gph_me(gph, lambda); actual = plq_gph(gphme); b = all(actual == expected | abs(actual - expected) < eps); assert(all(all(b))); end function [b] = testBounded(testCase) eps = 1e-10; b = false; lambda = 1.5; plq = [-3,0,0,inf; 0,1,0,3; 2,0,0,3; 5,0,1,1; inf,0,0,inf]; expected = plq_me(plq, lambda); gph = gph_plq(plq); gphme = gph_me(gph, lambda); actual = plq_gph(gphme); b = all(actual == expected | abs(actual - expected) < eps); assert(all(all(b))); end %function [b] = testMEnonconvex() % b = % lambda = 1; % plqf=[-1,0,-1,-1;0,0,1,1;1,0,-1,1;% result = plq_me(plqf,lambda,% desired = [-2,0,-1,-1.5;0,0.5,1,0.5;2,0.5,-1,0.5;% b = (result==desired); %endfunction
github
ylucet/CCA-master
plq_coDirect_test.m
.m
CCA-master/tests/plq_coDirect_test.m
9,789
utf_8
2bd5d0abcb2e138da04394da2860be0b
function tests = plq_coDirect_test() tests = functiontests(localfunctions); end % Author: Mike Trienis % For: Dr. Yves Lucet % Whatsit: A test file for plq convex hull functions plq_coDirect and _plq_conv_on_interval % I = Indicator, E = Exponential, C = Conjugate, L = Linear, Q = Quadratic function [b] = testNCExt_1(testCase) % testL2Lch_1 in test_plq_coSplit.sci. % Bounded on both sides. b = false; plqf = [-1,0,0,inf; 1,0,1,-1; 4,0,0,0; inf,0,0,inf]; [result, iters] = plq_coDirect(plqf); desired = [-1,0,0,inf; 4,0,0.4,-1.6; inf,0,0,inf]; if size(result) == size(desired) b = all(result == desired | abs(result - desired) < 1E-5); b = b & (iters == 1); else b = false; end; assert(all(all(b))) end function [b] = testNCExt_2(testCase) % Bounded on the left, co is slanted. b = false; plqf = [1,0,1,-1; 4,0,0,0; inf,0,0,inf]; [result, iters] = plq_coDirect(plqf); desired = [4,0,1,-4; inf,0,0,inf]; if size(result) == size(desired) b = all(result == desired | abs(result - desired) < 1E-5); b = b & (iters == 1); else b = false; end; assert(all(all(b))) end function [b] = testNCExt_3(testCase) % Bounded on the right, co is flat. b = false; plqf = [-1,0,0,3; 3,0,-1,2; inf,0,0,inf]; [result, iters] = plq_coDirect(plqf); desired = [3,0,0,-1; inf,0,0,inf]; if size(result) == size(desired) b = all(result == desired | abs(result - desired) < 1E-5); b = b & (iters == 1); else b = false; end; assert(all(all(b))) end function [b] = testNCExt_4(testCase) % Bounded upside down quadratic. b = false; plqf = [-1,0,0,inf; 2,-1,0,1; inf,0,0,inf]; [result, iters] = plq_coDirect(plqf); desired = [-1,0,0,inf; 2,0,-1,-1; inf,0,0,inf]; if size(result) == size(desired) b = all(result == desired | abs(result - desired) < 1E-5); b = b & (iters == 0); else b = false; end; assert(all(all(b))) end %---------------------------% function [b] = testQ2Lch_1(testCase) b = false; plqf = [0,1,0,0;3,0,0,0]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2.5; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired = plqf; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testL2Qch_2(testCase) b = false; plqf = [-1,0,0,1;3,1,0,0]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2.5; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired = [-0.2087122,0,-0.4174243,-0.0435608;3,1,0,0]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testL2Qch_3(testCase) b = false; plqf = [0,0,0,0;2,-1,0,0]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired =[2,0,-1,-2]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Lch_3(testCase) b = false; plqf = [1,1,0,0;4,0,0,1]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2.5; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired = [0.1270167,1,0,0;4,0,0.2540333,-0.0161332]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Lch_4(testCase) b = false; plqf = [1,-1,0,1;3,0,0,0]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired = [3,0,0.6,-1.8]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Lch_5(testCase) % This test was added to test the x(1)==-inf & x(5)==inf & % a(1)<>0 & a(2)==0 case of _plq_conv_buildl. % _plq_conv_on_interval: % a(1) >= 0, a(2) >= 0 % a(1) <> 0, a(2) == 0 % a(1) > 0, a(2) == 0 % _conv_interval_func: % (a(1) == 0 | x(5) == inf) & (a(2) == 0 | x(1) <> -inf) % x(5) == inf, a(2) == 0 % _plq_conv_buildl: % a(1) > 0, a(2) == 0 % x(1) == -inf, x(5) == inf b = false; plqf = [0,1,1,0;inf,0,0,0]; result = plq_conv_on_interval(plqf(1,:), plqf(2,:), -inf, 0, inf); result(end,1)=0; desired = [-0.5,1,1,0;0,0,0,-0.25]; b = all(norm(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Qch_1(testCase) b = false; plqf = [3/2,1,0,0;3,1,-4,6]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2.5; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired=[0.5,1,0,0;2.5,0,1,-0.25;3,1,-4,6]; b = all(abs(result-desired) < 1E-5 | result == desired); assert(all(all(b))) end function [b] = testQ2Qch_2(testCase) b = false; plqf = [0,1,1,2;5,1,-1,2]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2.5; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired=[-0.5,1,1,2;0.5,0,0,1.75;5,1,-1,2]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Qch_3(testCase) b = false; plqf = [0,2,4,0;2,2,-4,0]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired =[-1,2,4,0;1,0,0,-2;2,2,-4,0]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Qch_4(testCase) b = false; plqf = [1,-1,0,2;5,1,-4,4]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired=[2.2426407,0,0.4852814,-1.0294373;5,1,-4,4]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Qch_5(testCase) b = false; plqf = [0,-1,-4,0;2,-1,4,0]; f1 = plqf(1,:); f2 = plqf(2,:); x1=-2; x3=f1(1,1); x5=f2(1,1); result = plq_conv_on_interval(f1,f2,x1,x3,x5); desired=[0,0,-2,0;2,0,2,0]; b = all(abs(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Qch_6(testCase) b = false; plqf = [0,2,4,0;inf,2,-4,0]; [result, iters] = plq_coDirect(plqf); result(end,1)=0; desired=[-1,2,4,0;1,0,0,- 2;inf,2,-4,0]; desired(end,1)=0; b = (iters == 1) & all(norm(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Qch_7(testCase) % This test was added to test the x(1)==-inf & x(5)==inf & % a(1)<>0 & a(2)==0 case of _plq_conv_buildl. % _plq_conv_on_interval: % a(1) <> 0, a(2) <> 0 % _conv_interval_func: % (a(1) == 0 | x(5) == inf) & (a(2) == 0 | x(1) <> -inf) % x(5) == inf, a(2) == 0 % _plq_conv_buildl: % a(1) <> 0, a(2) <> 0 b = false; plqf = [0,2,1,0;inf,1,0,0]; result = plq_conv_on_interval(plqf(1,:), plqf(2,:), -inf, 0, inf); desired = [-0.1464466,2,1,0;0.2071068,0,0.4142136,-0.0428932;inf,1,0,0]; b = (all(abs(result - desired) < 1E-5 | result == desired)); assert(all(all(b))) end %---------------------------% function [b] = testL2L2Qch_7(testCase) b = false; plqf = [0,0,1,0;2,0,0,0;inf,1,-4,4]; [result, iters] = plq_coDirect(plqf); result(end,1)=0; desired = [2.5,0,1,-2.25;inf,1,-4,4]; desired(end,1)=0; b = (iters == 2) & all(norm(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2Q2Qch_8(testCase) b = false; plqf =[-2,1,8,16;2,-1,0,8;inf,1,-8,16]; [result, iters] = plq_coDirect(plqf); result(end,1)=0; desired = [-4,1,8,16;4,0,0,0;inf,1,-8, 16]; desired(end,1)=0; b = (iters == 3) & all(norm(result-desired) < 1E-5); assert(all(all(b))) end %---------------------------% function [b] = testQ2L2L2Qch_10(testCase) b = false; plqf =[-3,1,8,16;0,0,1,4;3,0,-1,4;inf,1,-8,16]; [result, iters] = plq_coDirect(plqf); result(end,1)=0; desired = [-4,1,8,16;4,0,0,0;inf,1,-8,16]; desired(end,1)=0; b = (iters == 3) & all(norm(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testQ2L2L2Qch_11(testCase) b = false; plqf =[-3,1,8,16;0,0,-1,-2;3,0,1,-2;inf,1,-8,16]; [result, iters] = plq_coDirect(plqf); result(end,1)=0; desired = [-4.2426407,1,8,16;0,0,-0.4852814,-2;4.2426407,0,0.4852814,-2;inf,1,-8,16]; desired(end,1)=0; b = (iters == 3) & all(norm(result-desired) < 1E-5); assert(all(all(b))) end %---------------------------% function [b] = testL2Q2Lch_12(testCase) b = false; plqf =[-2,0,-1,10;2,1,0,8;inf,0,1,10]; [result, iters] = plq_coDirect(plqf); result(end,1)=0; desired=[-0.5,0,-1,7.75;0.5,1,0,8;inf,0,1,7.75]; desired(end,1)=0; b = (iters == 2) & all(norm(result-desired) < 1E-5); assert(all(all(b))) end function [b] = testL2Q2Lch_13(testCase) b = false; plqf =[-2,0,-1,2;1,-1,0,8;inf,0,1,6]; [result, iters] = plq_coDirect(plqf); result(end,1)=0; desired=[- 2,0,-1,2;inf,0,1,6]; desired(end,1)=0; b = (iters == 1) & all(norm(result-desired) < 1E-5); assert(all(all(b))) end %---------------------------% function [b] = testPosInfHull_0(testCase) b = false; plqf = [inf,0,0,inf]; [result, iters] = plq_coDirect(plqf); desired = [inf,0,0,inf]; b = (iters == 0) & (result == desired); assert(all(all(b))) end function [b] = testNegInfHull_0(testCase) b = false; plqf = [inf,0,0,-inf]; [result, iters] = plq_coDirect(plqf); desired = [inf,0,0,-inf]; b = (iters == 0) & (result == desired); assert(all(all(b))) end function [b] = testNegInfHull_1(testCase) b = false; plqf = [0,-1,-2,1;1,0,0,1;inf,1,1,-1]; [result, iters] = plq_coDirect(plqf); desired = [inf,0,0,-inf]; b = (iters == 0) & (result == desired); assert(all(all(b))) end function [b] = testNegInfHull_2(testCase) b = false; plqf = [-1,1,4,3;1,0,2.5,2.5;3,1,-2,6;inf,-2,12,-9]; [result, iters] = plq_coDirect(plqf); desired = [inf,0,0,-inf]; b = (iters == 0) & (result == desired); assert(all(all(b))) end function [b] = testNegInfHull_3(testCase) b = false; plqf = [0,0,-1,0;1,1,0,0;inf,0,-2,3]; [result, iters] = plq_coDirect(plqf); desired = [inf,0,0,-inf]; b = (iters == 0) & (result == desired); assert(all(all(b))) end
github
ylucet/CCA-master
gph_prox_test.m
.m
CCA-master/tests/gph_prox_test.m
2,566
utf_8
6dbdbd8c3c030f86ccc9109ea8a5fa49
function tests = gph_prox_helper() tests = functiontests(localfunctions); end %perform all tests %P: input gph function %lambda: input real number lambda >0 function b = helper(p, lambda) P=gph_plq(p); M=gph_me(P,lambda);%m=plq_me(p,lambda); R=gph_prox(P,lambda);%r=plq_prox(p,lambda);%monotone but nonconvex %since there is no plq_compose function %we numerically evaluate the moreau envelope %computed directly and through the proximal mapping dx=linspace(-10,10)'; dy=gph_eval(R,dx);%dy=plq_eval(r,dx); dp=gph_eval(P,dy);%dp=plq_eval(p,dy); dz=dp+(dx-dy).^2/(2*lambda); dm=gph_eval(M,dx);%dm=plq_eval(m,dx); b=all((dm-dz)+1); assert(b) end %while we could avoid using plq functions, we prefer to use exactly %the same tests as plg_prox without modifying unit test functions %these functions are duplicated below. function b = testLambdaNegative(testCase) p=[0 0 -1 0; inf 0 1 0];lambda =-2; P=gph_plq(p); b=false; try R=gph_prox(P,lambda); catch b= true; end assert(b) end %function b = testLambdaNegative2() % Not Required % p=[0 0 -1 0; % b=% b=_helper(p,lambda); %endfunction function b = testAbs(testCase) p=[0 0 -1 0; inf 0 1 0];lambda =2; b=helper(p,lambda); assert(b) end function b = testPLQ0(testCase) p=[inf 1 0 0];lambda=3; b=helper(p,lambda); assert(b) end function b = testPLQ1(testCase) % A PLQ function: % x<-1: y=(x+1)^2 % -1<x<1: y=0 % 1<x: y=(x-1)^2 p=[-1 1 2 1;1 0 0 0;inf 1 -2 1]; lambda=3; b=helper(p,lambda); assert(b) end function b = testPL(testCase) % A piecewise linear function: % x<0: y=-x % 0<x<1: y=0 % 1<x: y=x-1 p = [0 0 -1 0;1 0 0 0;inf 0 1 -1]; lambda=20; b=helper(p,lambda); assert(b) end function b = testPLQ2(testCase) % A PLQ function: % x in [-1,1]: 0 % otherwise: x^2 - 1 p=[-1 1 0 -1;1 0 0 0;inf 1 0 -1]; lambda=3/4; b=helper(p,lambda); assert(b) end function b = testQuadratic(testCase) p=[inf,1,0,0]; lambda=1/10; b=helper(p,lambda); assert(b) end function b = testLinear(testCase) p=[inf,0,1,0]; lambda=1/3; b=helper(p,lambda); assert(b) end function b = testIndicatorSingleton(testCase) p=[1,0,0,2]; lambda=30.5; b=helper(p,lambda); assert(b) end function b = testInd(testCase) p=[-1 0 0 inf;1 0 0 0 ;inf 0 0 inf]; lambda=10; b=helper(p,lambda); assert(b) end function b = test1(testCase) p=[0 0 -1 0; inf 0 1 0];lambda =2; P=gph_plq(p); R=gph_prox(P,lambda);%R is monotone nonconvex b= ~gph_check(R,true); assert(b) end
github
ylucet/CCA-master
plq_clrDuplicateRows_test.m
.m
CCA-master/tests/plq_clrDuplicateRows_test.m
2,969
utf_8
3526e710c1b7419418a84baffc1b2a09
function tests = plq_clrDuplicateRows_test() tests = functiontests(localfunctions); end function [b] = testDuplicatePoints(testCase) plqDirty=[0,1,0,0;0,2,0,0;1,2,3,4;inf,3,0,0]; plqClean=plq_clean(plqDirty); plqdesired = [0,1,0,0;1,2,3,4;inf,3,0,0]; b = all(plqdesired==plqClean); assert(all(all(b))); end function [b] = testDuplicateRows(testCase) plqDirty=[0,1,0,0;0,1,0,0;1,2,3,4;inf,3,0,0]; plqClean=plq_clean(plqDirty); plqdesired = [0,1,0,0;1,2,3,4;inf,3,0,0]; b = all(plqdesired==plqClean); assert(all(all(b))); end function [b] = testDuplicatePoints2(testCase) plqDirty=[-1,1,2,3;0,1,0,0;0,2,0,0;1,2,3,4;2,4,5,6;inf,3,0,0]; plqClean=plq_clean(plqDirty); plqdesired = [-1,1,2,3;0,1,0,0;1,2,3,4;2,4,5,6;inf,3,0,0]; b = all(plqdesired==plqClean); assert(all(all(b))); end function [b] = testDuplicateRows2(testCase) plqDirty=[-1,1,2,3;0,1,0,0;0,1,0,0;1,2,3,4;2,3,4,5;inf,3,0,0]; plqClean=plq_clean(plqDirty); plqdesired = [-1,1,2,3;0,1,0,0;1,2,3,4;2,3,4,5;inf,3,0,0]; b = all(plqdesired==plqClean); assert(all(all(b))); end function [b] = testDuplicateEnd(testCase) plqDirty=[-1,1,2,3;0,1,0,0;0,1,0,0;0,2,0,0;1,2,3,4;2,3,4,5;inf,3,4,5]; plqClean=plq_clean(plqDirty); plqdesired = [-1,1,2,3;0,1,0,0;1,2,3,4;inf,3,4,5]; b = all(plqdesired==plqClean); assert(all(all(b))); end function [b] = testQuadratic(testCase) x=linspace(-2,2)'; x(end)=inf; plqDirty=[x,ones(size(x)),zeros(size(x)),zeros(size(x))]; plqClean=plq_clean(plqDirty); plqdesired = [inf,1,0,0]; b = all(plqdesired==plqClean); assert(all(all(b))); end function [b] = testLinear(testCase) x=linspace(-2,2)'; function y=f(x), if abs(x)<=1 y=0; else y=abs(x)-1;end;end function y=df(x), if abs(x)<=1 y=0; else y=sign(x);end;end plqDirty=plq_build(x,@f,@df,true); plqClean=plq_clean(plqDirty); plqdesired = [0,0,-1,-1;inf,0,1,-1]; b = all(plqdesired==plqClean); assert(all(all(b))); end function [b] = testDuplicateFunctions(testCase) b = false; plqfstarDirty = [0,0,0,0; 1,1,1,1; 2,1,1,1; 3,2,2,2]; result = plq_clean(plqfstarDirty); desired = [0, 0, 0, 0;2,1,1,1;3,2,2,2]; b = all(result==desired); assert(all(all(b))); end function [b] = testDuplicateDomains(testCase) b = false; plqfstarDirty = [0,0,0,0; 1,1,1,1; 1,2,3,4; 3,2,2,2]; result = plq_clean(plqfstarDirty); desired = [0, 0, 0, 0;1,1,1,1;3,2,2,2]; b = all(result==desired); assert(all(all(b))); end function [b] = testDuplicateDomsAndFns(testCase) b = false; plqfstarDirty = [0,0,0,0; 1,13,13,13; 1,7,7,7; 2,7,7,7; 3,2,2,2]; result = plq_clean(plqfstarDirty); desired = [0,0,0,0;1,13,13,13;2,7,7,7;3,2,2,2]; b = all(result==desired); assert(all(all(b))); end function [b] = testRound2Zero(testCase) b = false; plqfstarDirty = [1E-15,0,0,0; 1,13,1E-14,13; 2,1E-12,7,7; 3,2,2,1E-10]; result = plq_clean(plqfstarDirty); desired = [0,0,0,0;1,13,0,13;2,0,7,7;3,2,2,0]; b = all(result==desired); assert(all(all(b))); end
github
ylucet/CCA-master
gph_eval_test.m
.m
CCA-master/tests/gph_eval_test.m
3,373
utf_8
c61c1ea2049945108aac9473e5a3200e
function tests = gph_eval_test() tests = functiontests(localfunctions); end function [b] = testIndicator(testCase) eps = 1e-10; gph = [-1 -1; -1 1; -3 -3];%I_{-1)-3 X = [-3; -2; -1; 0; 1; 2]; Z = gph_eval(gph, X); expected = [inf; inf; -3; inf; inf; inf]; b = all(expected == Z | abs(expected - Z) < eps); assert(b) end function [b] = testSingleRegion(testCase) eps = 1e-10; b = false; % f(x) = -3*X^2 + 5 (subdifferential: -6*X) gph = [-3 -1; 18 6; -22 2]; X = (-4:0.5:1)'; Z = gph_eval(gph, X); expected = -3*X.^2 + 5; b = all(abs(expected - Z) < eps); assert(b) end function [b] = testAbs(testCase) eps = 1e-10; b = false; %abs function gph = [-1, 0, 0, 1; ... -1, -1, 1, 1; ... 1, 0, 0, 1]; X = [-100; -5; -1; -0.5; 0; 0.1; 0.8; 1; 1.01; 12]; Z = gph_eval(gph, X); expected = abs(X); b = all(abs(expected - Z) < eps); assert(b) end function [b] = testL_bounded(testCase) gph = [-1, -1, 1, 1; ... -1, 0, 0, 1; ... inf, 0, 0, inf];%I_[-1,1]. X = [-5; -1.01; -1; -1;-1;-0.8; -0.2; 0; 0.5; 0.999; 1; 1.001; 5; 100]; Z = gph_eval(gph, X); expected = [inf; inf; 0; 0; 0; 0; 0; 0; 0; 0; 0; inf; inf; inf]; b = all(expected == Z); assert(b) end function [b] = testPL(testCase) eps = 1e-10; % A " gph = [-1, 0, 0, 1, 1, 2; ... -1, -1, 0, 0, 1, 1; ... 1, 0, 0, 0, 0, 1]; X = [-6; -1; -0.5; 0; 0.5; 1; 1.5; 2; 4; 20]; Z = gph_eval(gph, X); expected = [6; 1; 0.5; 0; 0; 0; 0.5; 1; 3; 19]; b = all(abs(expected - Z) < eps); assert(b) end function [b] = testPLQ1(testCase) eps = 1e-10; b = false; % A PLQ function: % x<-1: y=(x+1)^2 % -1<x<1: y=0 % 1<x: y=(x-1)^2 gph = [-2, -1, 1, 2; ... -2, 0, 0, 2; ... 1, 0, 0, 1]; X = [-6; -4; -2.5; -1.75; -1; -0.5; 0; 0.75; 1; 1.5; 2; 2.5; 3; 5; 11]; Z = gph_eval(gph, X); expected = [25; 9; 2.25; 0.5625; 0; 0; 0; 0; 0; 0.25; 1; 2.25; 4; 16; 100]; b = all(abs(expected - Z) < eps); assert(b) end function [b] = testPLQ2(testCase) eps = 1e-10; b = false; % A PLQ function: % x in [-1,1]: 0 % otherwise: x^2 - 1 gph = [-2, -1, -1, 1, 1, 2; ... -4, -2, 0, 0, 2, 4; ... 3, 0, 0, 0, 0, 3]; X = [-9; -5; -2; -1.01; -1; -0.25; 0.1; 0.99; 1; 1.5; 2; 2.5; 3; 7]; Z = gph_eval(gph, X); expected = [80; 24; 3; 0.0201; 0; 0; 0; 0; 0; 1.25; 3; 5.25; 8; 48]; b = all(abs(expected - Z) < eps); assert(b) end function [b] = testEmpty(testCase) gph = [-1, 0, 0, 1;-1, -1, 1, 1; 1, 0, 0, 1];%abs X = []; Z = gph_eval(gph, X); expected = []; b = all(expected == Z); assert(b) end function b=test1(testCase) %evaluate on G(1,:) only G = [-1, 0, 0, 1;-1, -1, 1, 1; 1, 0, 0, 1];%abs x=[-1;0;0;1]; y=gph_eval(G,x); b = isequal(y,[1;0;0;1]); assert(b) end function b = runTestFile(testCase) b = true; b = checkForFail(testWrapper(testIndicator,'testIndicator'), b);%error b = checkForFail(testWrapper(testSingleRegion,'testSingleRegion'), b); b = checkForFail(testWrapper(testAbs,'testAbs'), b); b = checkForFail(testWrapper(testL_bounded,'testL_bounded'), b);%fail b = checkForFail(testWrapper(testPL,'testPL'), b); b = checkForFail(testWrapper(testPLQ1,'testPLQ1'), b); b = checkForFail(testWrapper(testPLQ2,'testPLQ2'), b); b = checkForFail(testWrapper(testEmpty,'testEmpty'), b); b = checkForFail(testWrapper(test1,'test1'), b); %fail assert(b) end
github
ylucet/CCA-master
plq_lft_test.m
.m
CCA-master/tests/plq_lft_test.m
5,179
utf_8
0f78be12e4f713bb5ae6bdbfe677ce78
function tests = plq_lft_test() tests = functiontests(localfunctions); end % Author: Mike Trienis % For: Dr. Yves Lucet % Whatsit: A test file for plq %L: Linear, Q: Quadratic, I: Indicator function [b] = testLLNonsmooth(testCase) b = false; plqf = [ -1, 0, -1, -1; inf, 0, 1, 1]; result = plq_lft(plqf); result2 = mikeplq_lft(plqf); desired = [-1, 0, 0, inf; 1, 0, -1, 0; inf, 0, 0, inf]; b = all(result==desired); assert(all(all(b))); end function [b] = testQQSmooth(testCase) b = false; plqf = [-2,1,1,1;inf,1,1,1]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); %desired = [-3, 1/4, -1/2, -3/4; inf, 1/4, -1/2, -3/4]; desired = [inf, 1/4, -1/2, -3/4]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testQQQSmooth(testCase) b = false; plqf = [-2,1,1,1;2,1,1,1;inf,1,1,1]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); %desired = [-3, 1/4, -1/2, -3/4; 5, 1/4, -1/2, -3/4; inf,1/4,-1/2,-3/4]; desired = [inf,1/4,-1/2,-3/4]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testabs(testCase) b = false; plqf = [0,0,-1,0;inf,0,1,0];%abs result= plq_lft(plqf); result2 = mikeplq_lft(plqf); desired = [-1, 0, 0, inf; 1, 0, 0, 0; inf, 0, 0, inf]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testL(testCase) b = false; plqf=[inf,0,1,1]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); desired = [1, 0, 0, -1]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testI(testCase) b = false; plqf=[1,0,0,-1]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); desired = [inf, 0, 1, 1]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testI2(testCase) b = false; plqf=[1,0,0,-1]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); desired = [inf, 0, 1, 1]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testNormSquared(testCase) b = false; plqf=[inf,1/2,0,0]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); desired = [inf, 1/2, 0, 0]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testQQNonsmooth(testCase) b = false; plqf=[0,1,0,0;inf,2,0,0]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); desired = [0 , 1/4, 0, 0; inf, 1/8, 0, 0]; b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testQLQSmooth(testCase) b = false; plqf=[1,1,0,0;3, 0, 2, -1;inf,3,-16,26]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); s=result(:,1);sa=result(:,2);sb=result(:,3);sc=result(:,4); resultLHS = [s]; result2LHS = result2(:,1); desiredLHS = [2; inf]; resultRHS = [sa, sb, sc]; result2RHS = result2(:,2:4); desiredRHS =[1/4, 0, 0; 1/12, 8/3, -14/3]; b = all((resultLHS==desiredLHS) & (norm(resultRHS - desiredRHS)<1E-8)); assert(all(all(b))); end function [b] = testQLQNonsmooth(testCase) b = false; plqf=[0,1,0,0;1, 0, 1, 0;inf,3, -4, 2]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); s=result(:,1);sa=result(:,2);sb=result(:,3);sc=result(:,4); resultLHS = [s]; result2LHS = result2(:,1); desiredLHS = [0; 1; 2; inf]; resultRHS = [sa, sb, sc]; result2RHS = result(:,2:4); desiredRHS =[1/4, 0, 0; 0, 0, 0; 0,1,-1;1/12,2/3,-2/3]; b = all((resultLHS==desiredLHS) & (norm(resultRHS - desiredRHS)<1E-8)); assert(all(all(b))); end function [b] = testPLQboundedLHS(testCase) b = false; plqf=[-5,0,0,inf;inf,1,0,5]; desired = [-10, 0, -5, -30;inf,1/4,0,-5]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testPLQboundedRHS(testCase) b = false; plqf=[-5,1,0,5;inf,0,0,inf]; desired = [-10, 1/4, 0, -5;inf,0,-5,-30]; result= plq_lft(plqf); result2 = mikeplq_lft(plqf); b = all(result==desired); if (~b) return; end; b = all(result2==desired); assert(all(all(b))); end function [b] = testPiecewiseLinear(testCase) b = false; plqf=plq_build(linspace(-2,2,10),@exp,@exp,false); result= plq_lft(plqf); desired = mikeplq_lft(plqf); b = all(result==desired); assert(all(all(b))); end function [b] = testNonconvex(testCase) b = false; plqf=[-1,0,-1,-1;0,0,1,1;1,0,-1,1;inf,0,1,-1]; result= plq_lft(plqf,false); desired = [-1,0,0,inf;0,0,-1,0;1,0,1,0;inf,0,0,inf]; b = all(result==desired); assert(all(all(b))); end function [b]= testNonconvexSingleInputParameter(testCase) function y=fct(x),y=(x.^2-1).^2;end function y=dfct(x),y=4*x.*(x.^2-1);end x=linspace(-3,3,5);x=[x 0 -1 1]; x=unique(sort(x, 'descend')); f=plq_build(x,@fct); fsdirect=plq_lft(f); b=plq_check(fsdirect); assert(all(all(b))); end
github
ylucet/CCA-master
plq_ll_test.m
.m
CCA-master/tests/plq_ll_test.m
572
utf_8
3f3a36bb3694ae2305130129497eea77
function tests = plq_ll_test() tests = functiontests(localfunctions); end function [b] = test1(testCase) b = false; lambda=0.7;mu=0.4; fctn = [-1,0,-1,-1;0,0,1,1;1,0,-1,1;inf,0,1,-1]; result = plq_ll(fctn,lambda,mu); desired = [-1.3 0. -1. -1.15; -0.7 1.6666667 3.3333333 1.6666667; -0.4 0. 1. 0.85; 0.4 -1.25 0. 0.65; 0.7 0. -1. 0.85; 1.3 1.6666667 -3.3333333 1.6666667; inf 0. 1. -1.15]; b = plq_isEqual(result,desired); assert(b) end function [b] = runTestFile(testCase) b = true; b = checkForFail(testWrapper(test1,'test1'), b); assert(b) end
github
ylucet/CCA-master
plq_gph_test.m
.m
CCA-master/tests/plq_gph_test.m
1,910
utf_8
81f8f57b27605fd0eea546be13c5545a
function tests = plq_gph_test() tests = functiontests(localfunctions); end % Unit test file for plq_gph function [b] = testAbs(testCase) b = false; %abs function gph = [-1, 0, 0, 1; ... -1, -1, 1, 1; ... 1, 0, 0, 1]; plq = plq_gph(gph); expected = [0,0,-1,0; inf,0,1,0]; b = all(plq == expected); assert(all(all(b))); end function [b] = testInd(testCase) b = false; % The function I_[-1,1]. gph = [-1, -1, 1, 1; ... -1, 0, 0, 1; ... inf, 0, 0, inf]; plq = plq_gph(gph); expected = [-1,0,0,inf; 1,0,0,0; inf,0,0,inf]; b = all(plq == expected); assert(all(all(b))); end function [b] = testPL(testCase) b = false; % A " gph = [-1, 0, 0, 1, 1, 2; ... -1, -1, 0, 0, 1, 1; ... 1, 0, 0, 0, 0, 1]; plq = plq_gph(gph); expected = [0,0,-1,0; 1,0,0,0; inf,0,1,-1]; b = all(plq == expected); assert(all(all(b))); end function [b] = testPLQ1(testCase) b = false; % A PLQ function: % x<-1: y=(x+1)^2 % -1<x<1: y=0 % 1<x: y=(x-1)^2 gph = [-2, -1, 1, 2; ... -2, 0, 0, 2; ... 1, 0, 0, 1]; plq = plq_gph(gph); expected = [-1,1,2,1; 1,0,0,0; inf,1,-2,1]; b = all(plq == expected); assert(all(all(b))); end function [b] = testPLQ2(testCase) b = false; % A PLQ function: % x in [-1,1]: 0 % otherwise: x^2 - 1 gph = [-2, -1, -1, 1, 1, 2; ... -4, -2, 0, 0, 2, 4; ... 3, 0, 0, 0, 0, 3]; plq = plq_gph(gph); expected = [-1,1,0,-1; 1,0,0,0; inf,1,0,-1]; b = all(plq == expected); assert(all(all(b))); end function [b] = testFullDomain(testCase) b = false; p = [inf, 1, 0, 0];f=gph_plq(p); e=[-1 1;-2 2;1 1]; b=all(f==e); assert(all(all(b))); end function [b] = testIndicator(testCase) b = false; p = [1, 0, 0, 1];f=gph_plq(p); e=[1 1;-1 1;1 1]; b=all(f==e); assert(all(all(b))); end
github
ylucet/CCA-master
plq_pa_test.m
.m
CCA-master/tests/plq_pa_test.m
1,642
utf_8
1b5fa5acc52497af96a880c288bc398a
function tests = plq_pa_test() tests = functiontests(localfunctions); end % I = Indicator, E = Exponential, C = Conjugate, L = Linear, Q = Quadratic function b = testL2Lpa(testCase) lambda_pa = 0.5; f1 = [inf, 0, 1, 0]; f2 = [inf, 0, -1, 5]; desired = [inf,0,0,2]; result = plq_pa(f1,f2,lambda_pa); result2 = plq_pa_mu(1,lambda_pa,f1,f2); b = isequal(desired, result, result2); assert(b) end function b = testI2Ipa(testCase) lambda_pa = 0.5; f2 = [5,0,0,1]; f1 = [6,0,0,4]; desired = [5.5,0,0,2.625]; result = plq_pa(f1,f2,lambda_pa); %2 lines below fail after modifying plq_scalar. %Need to investigate (later) result2 = plq_pa_mu(1,lambda_pa,f1,f2); b = isequal(desired, result, result2); b = isequal(desired, result); assert(b) end function b = testAbs2zero(testCase) lambda_pa = 1; f0 = [0,0,0,0]; f1 = [0,0,-1,0;inf,0,1,0]; r = plq_pa(f0,f1,lambda_pa); rp= plq_pa_mu(1,lambda_pa,f0,f1); b = isequal(f1,r, rp); assert(b) end function b = testL2L(testCase) lambda_pa = 0.5; f0 = [inf,0,-1,0]; f1 = [inf,0,1,0]; r = plq_pa(f0,f1,lambda_pa); rp= plq_pa_mu(1,0.5,f0,f1); b = isequal([inf,0,0,-0.5], r, rp); assert(b) end function b = testAbs2zero2(testCase) lambda_pa = 0.5; f0 = [inf,0,0,0]; f1 = [0,0,-1,0;inf,0,1,0]; r = plq_pa(f0,f1,lambda_pa); rp= plq_pa_mu(1,lambda_pa,f0,f1); b = isequal(r, rp); assert(b) end function b = testPaNc(testCase) lambda_pa = 1; f0 = [0,0,-1,0;inf,0,1,0]; %abs f1 = plq_scalar(f0,-1);%-abs r = plq_pa(f0,f1,lambda_pa,false); rp= plq_pa_mu(1,lambda_pa,f0,f1); %since f1 + r x^2 is NOT convex, the pa is NOT equal to f1 b = isequal(r, rp); assert(b) end