From b156d5aee6df2c7027ea45d3824813f8dcc536ef Mon Sep 17 00:00:00 2001 From: Andrew Hoopes Date: Wed, 27 Feb 2019 17:37:41 -0500 Subject: [PATCH] refactor codebase to c++ --- CMakeLists.txt | 211 +- anatomicuts/AnatomiCuts_correspondences.cxx | 6 +- anatomicuts/CMakeLists.txt | 5 +- check_siemens_dir/CMakeLists.txt | 2 +- ...ck_siemens_dir.c => check_siemens_dir.cpp} | 8 - connectgraph/connectgraph.cpp | 6 +- dicom/CMakeLists.txt | 18 - dmri_poistats/datamodel/PoistatsModel.h | 4 +- .../datamodel/utils/InitializePath.h | 4 +- dmri_poistats/dmri_initialize_path.cxx | 6 +- dmri_tensoreig/CMakeLists.txt | 4 +- .../{dmri_tensoreig.c => dmri_tensoreig.cpp} | 4 +- dngtester/CMakeLists.txt | 4 +- dngtester/cpptester.cpp | 10 - dngtester/{dngtester.c => dngtester.cpp} | 28 +- dummy/CMakeLists.txt | 2 +- dummy/dummy.c | 237 - dummy/dummy.cpp | 8 + dummy/myown.c | 42 - fem_elastic/CMakeLists.txt | 6 +- fem_elastic/exportGcam.cpp | 22 +- fem_elastic/fapplyMorph.cpp | 6 +- fem_elastic/fcreateMorph.cpp | 6 +- fem_elastic/fem_3d.cpp | 10 +- fem_elastic/fsurf2vol.cpp | 29 +- fem_elastic/mesh.h | 6 +- fem_elastic/morph.h | 6 +- fem_elastic/simple_timer.h | 41 - fem_elastic/surf_powell.cpp | 6 +- fem_elastic/surf_powell.h | 6 +- fem_elastic/surf_utils.h | 6 +- fem_elastic/transformUtils.cpp | 8 - freeview/DialogLoadTransform.cpp | 6 +- freeview/DialogLoadVolume.cpp | 6 +- freeview/DialogTransformVolume.cpp | 6 +- freeview/FSGroupDescriptor.h | 6 +- freeview/FSLabel.h | 6 +- freeview/FSPointSet.h | 6 +- freeview/FSSurface.cpp | 6 +- freeview/FSSurface.h | 6 +- freeview/FSVolume.cpp | 6 +- freeview/FSVolume.h | 6 +- freeview/LUTDataHolder.h | 6 +- freeview/LayerConnectomeMatrix.h | 6 +- freeview/LayerFCD.h | 6 +- freeview/LayerMRI.cpp | 6 +- freeview/LayerMRI.h | 6 +- freeview/LayerPropertyMRI.h | 6 +- freeview/LayerPropertyPointSet.h | 6 +- freeview/LayerPropertyROI.h | 6 +- freeview/LayerROI.h | 4 +- freeview/LayerVolumeTrack.cpp | 6 +- freeview/MyUtils.cpp | 6 +- freeview/PanelVolume.h | 6 +- freeview/SurfaceAnnotation.h | 6 +- freeview/SurfaceLabel.h | 6 +- freeview/SurfaceOverlay.cpp | 6 +- freeview/SurfaceOverlay.h | 6 +- freeview/SurfaceSpline.h | 6 +- freeview/VolumeFilter.cpp | 6 +- freeview/VolumeFilter.h | 6 +- freeview/VolumeFilterClose.cpp | 6 +- freeview/VolumeFilterConvolve.cpp | 6 +- freeview/VolumeFilterDilate.cpp | 6 +- freeview/VolumeFilterErode.cpp | 6 +- freeview/VolumeFilterMean.cpp | 6 +- freeview/VolumeFilterOpen.cpp | 6 +- freeview/main.cpp | 6 +- fslutils/fsl_label2voxel.cpp | 4 +- hiam_make_surfaces/CMakeLists.txt | 2 +- ...make_surfaces.c => hiam_make_surfaces.cpp} | 0 hiam_make_template/CMakeLists.txt | 2 +- ...make_template.c => hiam_make_template.cpp} | 23 +- hiam_register/CMakeLists.txt | 2 +- .../{hiam_register.c => hiam_register.cpp} | 5 +- hipsstubs/CMakeLists.txt | 7 - hipsstubs/hipsrepl.c | 117 - hipsstubs/hipsstubs.c | 330 - histo_compute_joint_density/CMakeLists.txt | 2 +- ...sity.c => histo_compute_joint_density.cpp} | 8 +- histo_fix_topology/CMakeLists.txt | 2 +- ..._fix_topology.c => histo_fix_topology.cpp} | 0 histo_register_block/CMakeLists.txt | 2 +- ...ister_block.c => histo_register_block.cpp} | 0 histo_segment/CMakeLists.txt | 2 +- .../{histo_segment.c => histo_segment.cpp} | 0 histo_synthesize/CMakeLists.txt | 2 +- ...isto_synthesize.c => histo_synthesize.cpp} | 6 +- include/DICOMRead.h | 8 +- include/FsgdfPlot.h | 4 +- include/MRISOBBTree.h | 16 - include/MRISdistancefield.h | 16 +- include/annotation.h | 8 +- include/{argparse.hpp => argparse.h} | 16 +- include/art1.h | 85 - include/artmap.h | 86 - include/aseg_edit_svm.h | 43 - include/autoencoder.h | 1 - include/backprop.h | 124 - include/base.h | 13 - include/canny.h | 96 - include/cdflib.h | 121 - include/chronometer.h | 53 +- include/cma.h | 11 - include/cmat.h | 8 - include/cmdargs.h | 11 - include/colortab.h | 6 +- include/congraph.h | 48 - include/connect.h | 120 - include/connectcomp.h | 2 +- include/cpputils.h | 11 - include/diag.h | 17 +- include/dmatrix.h | 9 - include/dtk.fs.h | 2 +- include/error.h | 10 - include/evschutils.h | 4 +- include/fastmarching.h | 21 +- include/fexterns.h | 27 - include/fftutils.h | 4 +- include/fgutil.h | 57 - include/field_code.h | 2 +- include/filecode.h | 49 - include/fio.h | 8 - include/fmarchmesh.h | 58 - include/fsgdf_wrap.h | 8 - include/gca.h | 10 - include/gcamcomputeLabelsLinearCPU.h | 11 - include/gcamorph.h | 8 - include/gcamorphtestutils.h | 15 +- include/gcarray.h | 86 - include/gclass.h | 6 +- include/geodesics.h | 8 - include/{gifti_local.h => gifti.h} | 7 +- include/gmm/gmm.h | 53 - include/gmm/gmm_MUMPS_interface.h | 306 - include/gmm/gmm_algobase.h | 225 - include/gmm/gmm_blas.h | 2283 -- include/gmm/gmm_blas_interface.h | 855 - include/gmm/gmm_condition_number.h | 142 - include/gmm/gmm_conjugated.h | 395 - include/gmm/gmm_def.h | 1117 - include/gmm/gmm_dense_Householder.h | 316 - include/gmm/gmm_dense_lu.h | 250 - include/gmm/gmm_dense_qr.h | 788 - include/gmm/gmm_dense_sylvester.h | 173 - include/gmm/gmm_domain_decomp.h | 164 - include/gmm/gmm_except.h | 333 - include/gmm/gmm_inoutput.h | 1131 - include/gmm/gmm_interface.h | 1065 - include/gmm/gmm_interface_bgeot.h | 82 - include/gmm/gmm_iter.h | 139 - include/gmm/gmm_iter_solvers.h | 109 - include/gmm/gmm_kernel.h | 53 - include/gmm/gmm_lapack_interface.h | 422 - include/gmm/gmm_least_squares_cg.h | 95 - include/gmm/gmm_matrix.h | 1200 - include/gmm/gmm_modified_gram_schmidt.h | 97 - include/gmm/gmm_opt.h | 125 - include/gmm/gmm_precond.h | 64 - include/gmm/gmm_precond_diagonal.h | 131 - include/gmm/gmm_precond_ildlt.h | 286 - include/gmm/gmm_precond_ildltt.h | 217 - include/gmm/gmm_precond_ilu.h | 280 - include/gmm/gmm_precond_ilut.h | 227 - include/gmm/gmm_precond_ilutp.h | 281 - include/gmm/gmm_precond_mr_approx_inverse.h | 148 - include/gmm/gmm_real_part.h | 604 - include/gmm/gmm_ref.h | 525 - include/gmm/gmm_scaled.h | 427 - include/gmm/gmm_solver_Newton.h | 137 - include/gmm/gmm_solver_Schwarz_additive.h | 746 - include/gmm/gmm_solver_bfgs.h | 207 - include/gmm/gmm_solver_bicgstab.h | 160 - include/gmm/gmm_solver_cg.h | 212 - include/gmm/gmm_solver_constrained_cg.h | 166 - include/gmm/gmm_solver_gmres.h | 173 - include/gmm/gmm_solver_idgmres.h | 804 - include/gmm/gmm_solver_qmr.h | 209 - include/gmm/gmm_std.h | 255 - include/gmm/gmm_sub_index.h | 217 - include/gmm/gmm_sub_matrix.h | 409 - include/gmm/gmm_sub_vector.h | 557 - include/gmm/gmm_superlu_interface.h | 406 - include/gmm/gmm_transposed.h | 243 - include/gmm/gmm_tri_solve.h | 221 - include/gmm/gmm_vector.h | 968 - include/gmm/gmm_vector_to_matrix.h | 339 - include/gw_utils.h | 2 +- include/h_logz.h | 280 - include/handle.h | 38 - include/heap.h | 200 - include/hip_brf.h | 91 - include/hipl_for.h | 58 - include/hipl_format.h | 58 - include/hips.h | 342 +- include/hips_basic.h | 424 - include/hips_error.h | 198 - include/hips_header.h | 180 - include/hips_parser.h | 177 - include/hipsext.h | 59 - include/hipsh.h | 963 - include/hipspub.h | 65 - include/hipsu.h | 490 - include/histo.h | 4 +- include/image.h | 7 +- include/imautils.h | 6 +- include/inverse.h | 63 - include/iutils.h | 44 - include/{json.hpp => json.h} | 0 include/kinput.h | 86 - include/label.h | 4 +- include/ldtmplt.h | 28 - include/log.h | 71 + include/log.hpp | 73 - include/lpafile.h | 64 - include/{lut.hpp => lut.h} | 4 +- include/mailbox.h | 68 - include/map.h | 101 - include/matrix.h | 13 +- include/mgh_filter.h | 31 - include/mgh_matrix.h | 72 - include/mincutils.h | 76 - include/minmaxrc.h | 51 - include/mri.h | 25 +- include/mri2.h | 10 +- include/mriBSpline.h | 9 - include/mriFunctionalDataAccess.h | 661 - include/mriHeadPointList.h | 157 - include/mriROI.h | 130 - include/mriSurface.h | 279 - include/mriTransform.h | 17 +- include/mriTypes.h | 50 - include/mriVolume.h | 834 - include/mri_ca_labelMapper.h | 323 - include/mri_ca_labelingParameters.h | 117 - include/mri_ca_measMapper.h | 502 - include/mri_ca_measureVolume.h | 6 +- include/mri_ca_sparse3DMatrix.h | 317 - include/mri_ca_util.h | 6 +- include/mri_transform.h | 50 - include/mriclass.h | 14 +- include/mris_expand.h | 66 - include/mrisbiorthogonalwavelets.h | 62 - include/mrisurf.h | 27 +- include/mrisurf_base.h | 5 +- include/mrisurf_metricProperties.h | 2 +- include/mrisutils.h | 4 +- include/mthread.h | 72 - include/numerics.h | 9 - include/omp_support.h | 15 - include/path.h | 1 - include/pbm.h | 50 - include/pbmplus.h | 221 - include/pdf.h | 11 - include/pgm.h | 81 - include/pixrect/bw2var.h | 40 - include/pixrect/cg12_var.h | 138 - include/pixrect/cg2reg.h | 355 - include/pixrect/cg2var.h | 89 - include/pixrect/cg3var.h | 51 - include/pixrect/cg4var.h | 61 - include/pixrect/cg8var.h | 181 - include/pixrect/cg9var.h | 93 - include/pixrect/gp1cmds.h | 421 - include/pixrect/gp1reg.h | 160 - include/pixrect/gp1var.h | 113 - include/pixrect/gt_fbi.h | 944 - include/pixrect/gt_rp.h | 116 - include/pixrect/gtvar.h | 330 - include/pixrect/mem32_var.h | 34 - include/pixrect/mem_rop_impl_ops.h | 260 - include/pixrect/mem_rop_impl_util.h | 61 - include/pixrect/memreg.h | 65 - include/pixrect/memvar.h | 152 - include/pixrect/pixfont.h | 59 - include/pixrect/pixrect.h | 353 - include/pixrect/pixrect_hs.h | 37 - include/pixrect/pr_dblbuf.h | 36 - include/pixrect/pr_impl_make.h | 31 - include/pixrect/pr_impl_util.h | 187 - include/pixrect/pr_io.h | 57 - include/pixrect/pr_line.h | 69 - include/pixrect/pr_planegroups.h | 52 - include/pixrect/pr_util.h | 139 - include/pixrect/traprop.h | 29 - include/pixrect/tv1var.h | 63 - include/pnm.h | 72 - include/{pointset.hpp => pointset.h} | 4 +- include/ppm.h | 132 - include/queue.h | 87 - include/rbf.h | 10 +- include/rec.h | 51 - include/rescale.h | 46 - include/rfa.h | 13 +- include/rfutils.h | 7 - include/rgb.h | 120 + include/rgb_image.h | 197 - include/rgb_utils.h | 37 - include/romp_support.h | 6 +- include/runfuncs.h | 50 - include/sort_definition.h | 4 +- include/sse_mathfun.h | 765 - include/stats.h | 8 +- include/stc.h | 77 - include/struct.h | 39 - include/surfgrad.h | 9 - include/sys/timeb.h | 24 - include/thread.h | 96 - include/timer.h | 96 +- include/{topology => }/topo_parms.h | 0 include/transform.h | 14 +- include/trig512.h | 544 - include/utils.h | 12 +- include/utilsmath.h | 15 - include/version.h | 14 +- include/voxlist.h | 10 - include/x3DList.h | 126 - include/xDebug.h | 2 +- include/xGLutWindow.h | 209 - include/xGrowableArray.h | 77 - include/xList.h | 290 - include/xSparseVolume.h | 110 - include/xUndoList.h | 107 - include/xUtilities.h | 73 - include/xVoxel.h | 64 +- include/xview/alert.h | 63 - include/xview/attr.h | 481 - include/xview/attrol.h | 64 - include/xview/base.h | 121 - include/xview/canvas.h | 162 - include/xview/cms.h | 151 - include/xview/cms_grays.h | 45 - include/xview/cms_mono.h | 37 - include/xview/cms_rgb.h | 49 - include/xview/cmsrainbow.h | 57 - include/xview/cursor.h | 156 - include/xview/db.h | 26 - include/xview/defaults.h | 155 - include/xview/dragdrop.h | 131 - include/xview/drawable.h | 70 - include/xview/expandname.h | 74 - include/xview/font.h | 229 - include/xview/frame.h | 268 - include/xview/fullscreen.h | 144 - include/xview/generic.h | 304 - include/xview/icon.h | 108 - include/xview/icon_load.h | 170 - include/xview/notice.h | 122 - include/xview/notify.h | 356 - include/xview/openmenu.h | 292 - include/xview/openwin.h | 142 - include/xview/panel.h | 737 - include/xview/pixwin.h | 160 - include/xview/pkg.h | 108 - include/xview/pkg_public.h | 92 - include/xview/rect.h | 146 - include/xview/rectlist.h | 125 - include/xview/screen.h | 125 - include/xview/scrollbar.h | 157 - include/xview/sel_attrs.h | 119 - include/xview/sel_compat.h | 46 - include/xview/sel_pkg.h | 243 - include/xview/sel_svc.h | 314 - include/xview/selection.h | 104 - include/xview/seln.h | 21 - include/xview/server.h | 177 - include/xview/str_utils.h | 148 - include/xview/sun.h | 52 - include/xview/svrimage.h | 105 - include/xview/termsw.h | 109 - include/xview/text.h | 42 - include/xview/textsw.h | 539 - include/xview/tty.h | 141 - include/xview/ttysw.h | 100 - include/xview/win_enum.h | 87 - include/xview/win_env.h | 71 - include/xview/win_event.h | 351 - include/xview/win_input.h | 602 - include/xview/win_notify.h | 47 - include/xview/win_screen.h | 7 - include/xview/win_struct.h | 44 - include/xview/window.h | 461 - include/xview/window_hs.h | 67 - include/xview/wmgr.h | 68 - include/xview/xv_c_types.h | 171 - include/xview/xv_error.h | 90 - include/xview/xv_i18n.h | 76 - include/xview/xv_version.h | 39 - include/xview/xv_xrect.h | 25 - include/xview/xview.h | 25 - include/xview/xview_xvin.h | 49 - itkutils/ui/CommandParser.cxx | 9 +- itkutils/ui/FreeSurferExecutable.cxx | 10 +- itkutils/ui/FreeSurferExecutable.h | 4 +- label2flat/CMakeLists.txt | 2 +- label2flat/{label2flat.c => label2flat.cpp} | 2 +- label2patch/CMakeLists.txt | 2 +- .../{label2patch.c => label2patch.cpp} | 2 +- label_area/CMakeLists.txt | 2 +- label_area/{label_area.c => label_area.cpp} | 2 +- label_border/CMakeLists.txt | 2 +- .../{label_border.c => label_border.cpp} | 2 +- log/CMakeLists.txt | 14 - log/congraph.c | 578 - log/connect.c | 1591 - log/h_logz.c | 4280 --- log/lmedian.c | 484 - log/map.c | 445 - log/runfuncs.c | 5559 --- lta_convert/lta_convert.cpp | 10 - mkxsubjreg/CMakeLists.txt | 2 +- mkxsubjreg/{mkxsubjreg.c => mkxsubjreg.cpp} | 0 mri_add_xform_to_header/CMakeLists.txt | 2 +- ...o_header.c => mri_add_xform_to_header.cpp} | 2 +- mri_and/CMakeLists.txt | 4 +- mri_and/{mri_and.c => mri_and.cpp} | 2 - mri_and/{mri_or.c => mri_or.cpp} | 2 - mri_annotation2label/CMakeLists.txt | 2 +- ...ation2label.c => mri_annotation2label.cpp} | 0 mri_aparc2aseg/CMakeLists.txt | 2 +- .../{mri_aparc2aseg.c => mri_aparc2aseg.cpp} | 0 mri_aparc2wmseg/CMakeLists.txt | 2 +- ...{mri_aparc2wmseg.c => mri_aparc2wmseg.cpp} | 0 mri_apply_inu_correction/CMakeLists.txt | 2 +- ...rection.c => mri_apply_inu_correction.cpp} | 0 mri_aseg_edit_reclassify/CMakeLists.txt | 2 +- ...lassify.c => mri_aseg_edit_reclassify.cpp} | 6 +- mri_aseg_edit_train/CMakeLists.txt | 2 +- ...g_edit_train.c => mri_aseg_edit_train.cpp} | 6 +- mri_auto_fill/CMakeLists.txt | 2 +- .../{mri_auto_fill.c => mri_auto_fill.cpp} | 5 +- mri_average/CMakeLists.txt | 2 +- .../{mri_average.c => mri_average.cpp} | 6 +- mri_bc_sc_bias_correct/CMakeLists.txt | 2 +- ...s_correct.c => mri_bc_sc_bias_correct.cpp} | 0 mri_bias/CMakeLists.txt | 4 +- .../{mri_apply_bias.c => mri_apply_bias.cpp} | 6 +- ...ri_compute_bias.c => mri_compute_bias.cpp} | 6 +- mri_binarize/CMakeLists.txt | 2 +- .../{mri_binarize.c => mri_binarize.cpp} | 0 mri_build_priors/CMakeLists.txt | 2 +- ...ri_build_priors.c => mri_build_priors.cpp} | 0 mri_ca_label/CMakeLists.txt | 2 +- .../{mri_ca_label.c => mri_ca_label.cpp} | 8 +- mri_ca_normalize/CMakeLists.txt | 4 +- ...ri_ca_normalize.c => mri_ca_normalize.cpp} | 6 +- ..._cal_normalize.c => mri_cal_normalize.cpp} | 6 +- mri_ca_register/CMakeLists.txt | 2 +- ...{mri_ca_register.c => mri_ca_register.cpp} | 6 +- mri_ca_tissue_parms/CMakeLists.txt | 2 +- ...tissue_parms.c => mri_ca_tissue_parms.cpp} | 6 +- mri_ca_train/CMakeLists.txt | 2 +- .../{mri_ca_train.c => mri_ca_train.cpp} | 6 +- mri_cal_renormalize_gca/CMakeLists.txt | 2 +- ...lize_gca.c => mri_cal_renormalize_gca.cpp} | 6 +- mri_cc/CMakeLists.txt | 2 +- mri_cc/{mri_cc.c => mri_cc.cpp} | 6 +- mri_cc_ma_fill/mri_cc_ma_fill.c | 6 +- mri_cc_medial_axis/mri_cc_medial_axis.c | 6 +- mri_cht2p/CMakeLists.txt | 2 +- mri_cht2p/{mri_cht2p.c => mri_cht2p.cpp} | 0 mri_classify/CMakeLists.txt | 2 +- .../{mri_classify.c => mri_classify.cpp} | 1 - mri_cnr/CMakeLists.txt | 2 +- mri_cnr/{mri_cnr.c => mri_cnr.cpp} | 0 mri_compile_edits/CMakeLists.txt | 2 +- ..._compile_edits.c => mri_compile_edits.cpp} | 0 mri_compute_change_map/CMakeLists.txt | 2 +- ...hange_map.c => mri_compute_change_map.cpp} | 8 +- mri_compute_overlap/CMakeLists.txt | 2 +- ...pute_overlap.c => mri_compute_overlap.cpp} | 6 +- mri_compute_seg_overlap/CMakeLists.txt | 2 +- ..._overlap.c => mri_compute_seg_overlap.cpp} | 0 .../CMakeLists.txt | 2 +- ...c => mri_compute_structure_transforms.cpp} | 6 +- mri_compute_volume_fractions/CMakeLists.txt | 8 +- ...ions.c => mri_compute_layer_fractions.cpp} | 6 +- ...ons.c => mri_compute_volume_fractions.cpp} | 12 +- ...s.c => mri_compute_volume_intensities.cpp} | 6 +- ...s.c => mris_compute_layer_intensities.cpp} | 6 +- mri_concat/CMakeLists.txt | 2 +- mri_concat/{mri_concat.c => mri_concat.cpp} | 0 mri_concatenate_gcam/mri_concatenate_gcam.cpp | 8 - mri_concatenate_lta/CMakeLists.txt | 2 +- ...catenate_lta.c => mri_concatenate_lta.cpp} | 2 +- mri_convert/CMakeLists.txt | 6 +- .../{mri_convert.c => mri_convert.cpp} | 264 +- .../{mri_make_uchar.c => mri_make_uchar.cpp} | 6 +- mri_convert_mdh/CMakeLists.txt | 2 +- ...{mri_convert_mdh.c => mri_convert_mdh.cpp} | 0 mri_copy_values/CMakeLists.txt | 2 +- ...{mri_copy_values.c => mri_copy_values.cpp} | 0 mri_cor2label/CMakeLists.txt | 2 +- .../{mri_cor2label.c => mri_cor2label.cpp} | 0 mri_coreg/CMakeLists.txt | 2 +- mri_coreg/{mri_coreg.c => mri_coreg.cpp} | 16 +- mri_correct_segmentations/CMakeLists.txt | 2 +- ...ations.c => mri_correct_segmentations.cpp} | 2 - mri_dct_align/CMakeLists.txt | 4 +- .../{mri_dct_align.c => mri_dct_align.cpp} | 6 +- ...lign_binary.c => mri_dct_align_binary.cpp} | 6 +- mri_deface/CMakeLists.txt | 2 +- mri_deface/{mri_deface.c => mri_deface.cpp} | 6 +- mri_diff/CMakeLists.txt | 2 +- mri_diff/{mri_diff.c => mri_diff.cpp} | 0 mri_distance_transform/CMakeLists.txt | 2 +- .../mri_distance_transform.cpp | 4 +- mri_divide_segmentation/CMakeLists.txt | 2 +- ...entation.c => mri_divide_segmentation.cpp} | 6 +- mri_edit_segmentation/CMakeLists.txt | 2 +- ...gmentation.c => mri_edit_segmentation.cpp} | 6 +- .../CMakeLists.txt | 2 +- ...> mri_edit_segmentation_with_surfaces.cpp} | 0 mri_edit_wm_with_aseg/CMakeLists.txt | 2 +- ..._with_aseg.c => mri_edit_wm_with_aseg.cpp} | 6 +- mri_elastic_energy/CMakeLists.txt | 2 +- ...lastic_energy.c => mri_elastic_energy.cpp} | 6 +- mri_em_register/CMakeLists.txt | 2 +- mri_em_register/emregisterutils.h | 49 +- mri_em_register/findtranslation.h | 32 +- ...{mri_em_register.c => mri_em_register.cpp} | 21 +- mri_estimate_tissue_parms/CMakeLists.txt | 2 +- ..._parms.c => mri_estimate_tissue_parms.cpp} | 11 +- mri_evaluate_morph/CMakeLists.txt | 2 +- ...valuate_morph.c => mri_evaluate_morph.cpp} | 0 mri_extract/CMakeLists.txt | 2 +- .../{mri_extract.c => mri_extract.cpp} | 0 mri_extract_conditions/CMakeLists.txt | 2 +- ...onditions.c => mri_extract_conditions.cpp} | 0 mri_extract_fcd_features/CMakeLists.txt | 2 +- ...eatures.c => mri_extract_fcd_features.cpp} | 6 +- mri_extract_label/CMakeLists.txt | 2 +- ..._extract_label.c => mri_extract_label.cpp} | 0 mri_extract_largest_CC/CMakeLists.txt | 2 +- ...argest_CC.c => mri_extract_largest_CC.cpp} | 0 .../{myutils.c => myutils.cpp} | 0 .../{subroutines.c => subroutines.cpp} | 0 .../mri_extract_ma_intensity.c | 6 +- mri_fcili/CMakeLists.txt | 2 +- mri_fcili/{mri_fcili.c => mri_fcili.cpp} | 0 mri_fdr/CMakeLists.txt | 2 +- mri_fdr/{mri_fdr.c => mri_fdr.cpp} | 4 +- mri_fieldsign/CMakeLists.txt | 2 +- .../{mri_fieldsign.c => mri_fieldsign.cpp} | 10 +- mri_fill/CMakeLists.txt | 2 +- mri_fill/{mri_fill.c => mri_fill.cpp} | 6 +- mri_fill/{myutil.c => myutil.cpp} | 0 mri_fill/{subroutines.c => subroutines.cpp} | 0 mri_fit_bias/CMakeLists.txt | 2 +- .../{mri_fit_bias.c => mri_fit_bias.cpp} | 76 +- mri_fslmat_to_lta/CMakeLists.txt | 2 +- ..._fslmat_to_lta.c => mri_fslmat_to_lta.cpp} | 0 mri_fuse_intensity_images/CMakeLists.txt | 2 +- ...images.c => mri_fuse_intensity_images.cpp} | 6 +- .../mri_fuse_segmentations.cpp | 14 +- mri_fwhm/CMakeLists.txt | 2 +- mri_fwhm/{mri_fwhm.c => mri_fwhm.cpp} | 0 mri_gca_ambiguous/CMakeLists.txt | 2 +- ..._gca_ambiguous.c => mri_gca_ambiguous.cpp} | 48 +- mri_gcab_train/CMakeLists.txt | 2 +- .../{mri_gcab_train.c => mri_gcab_train.cpp} | 6 +- mri_gcut/mri_gcut.cpp | 6 +- mri_gdfglm/CMakeLists.txt | 2 +- mri_gdfglm/{mri_gdfglm.c => mri_gdfglm.cpp} | 0 mri_glmfit/CMakeLists.txt | 2 +- mri_glmfit/{mri_glmfit.c => mri_glmfit.cpp} | 28 +- mri_gtmpvc/CMakeLists.txt | 2 +- mri_gtmpvc/{mri_gtmpvc.c => mri_gtmpvc.cpp} | 61 +- mri_gtmseg/CMakeLists.txt | 2 +- mri_gtmseg/{mri_gtmseg.c => mri_gtmseg.cpp} | 6 +- mri_hausdorff_dist/CMakeLists.txt | 2 +- ...ausdorff_dist.c => mri_hausdorff_dist.cpp} | 4 +- mri_head/CMakeLists.txt | 2 +- mri_head/{mri_head.c => mri_head.cpp} | 0 mri_hires_register/CMakeLists.txt | 12 +- ..._distances.c => mri_compute_distances.cpp} | 6 +- ...ires_register.c => mri_hires_register.cpp} | 6 +- ...ri_linear_align.c => mri_linear_align.cpp} | 6 +- ...n_binary.c => mri_linear_align_binary.cpp} | 6 +- .../{mri_nl_align.c => mri_nl_align.cpp} | 6 +- ...align_binary.c => mri_nl_align_binary.cpp} | 6 +- mri_histo_eq/CMakeLists.txt | 2 +- .../{mri_histo_eq.c => mri_histo_eq.cpp} | 6 +- mri_histo_normalize/CMakeLists.txt | 2 +- ...to_normalize.c => mri_histo_normalize.cpp} | 6 +- mri_ibmc/CMakeLists.txt | 2 +- mri_ibmc/{mri_ibmc.c => mri_ibmc.cpp} | 6 +- mri_info/CMakeLists.txt | 2 +- mri_info/{mri_info.c => mri_info.cpp} | 4 +- mri_interpolate/CMakeLists.txt | 2 +- ...{mri_interpolate.c => mri_interpolate.cpp} | 0 mri_jacobian/CMakeLists.txt | 2 +- .../{mri_jacobian.c => mri_jacobian.cpp} | 6 +- mri_joint_density/CMakeLists.txt | 2 +- ..._joint_density.c => mri_joint_density.cpp} | 6 +- mri_label2label/CMakeLists.txt | 2 +- ...{mri_label2label.c => mri_label2label.cpp} | 0 mri_label2vol/CMakeLists.txt | 2 +- .../{mri_label2vol.c => mri_label2vol.cpp} | 0 mri_label_accuracy/CMakeLists.txt | 2 +- ...abel_accuracy.c => mri_label_accuracy.cpp} | 0 mri_label_histo/CMakeLists.txt | 2 +- ...{mri_label_histo.c => mri_label_histo.cpp} | 6 +- mri_label_vals/CMakeLists.txt | 2 +- .../{mri_label_vals.c => mri_label_vals.cpp} | 6 +- mri_label_volume/CMakeLists.txt | 2 +- ...ri_label_volume.c => mri_label_volume.cpp} | 6 +- mri_linear_register/CMakeLists.txt | 2 +- ...ear_register.c => mri_linear_register.cpp} | 6 +- mri_log_likelihood/CMakeLists.txt | 2 +- ...og_likelihood.c => mri_log_likelihood.cpp} | 0 mri_make_bem_surfaces/CMakeLists.txt | 2 +- ...m_surfaces.c => mri_make_bem_surfaces.cpp} | 0 mri_make_density_map/CMakeLists.txt | 2 +- ...density_map.c => mri_make_density_map.cpp} | 0 mri_make_labels/CMakeLists.txt | 2 +- ...{mri_make_labels.c => mri_make_labels.cpp} | 0 mri_make_register/CMakeLists.txt | 2 +- ..._make_register.c => mri_make_register.cpp} | 2 +- mri_make_template/CMakeLists.txt | 2 +- ..._make_template.c => mri_make_template.cpp} | 0 mri_map_cpdat/mri_map_cpdat.cpp | 8 - mri_mark_temporal_lobe/CMakeLists.txt | 2 +- ...oral_lobe.c => mri_mark_temporal_lobe.cpp} | 6 +- mri_mask/CMakeLists.txt | 2 +- mri_mask/{mri_mask.c => mri_mask.cpp} | 0 mri_matrix_multiply/CMakeLists.txt | 2 +- ...rix_multiply.c => mri_matrix_multiply.cpp} | 0 mri_mc/CMakeLists.txt | 6 +- .../{build_MC_table.c => build_MC_table.cpp} | 0 ...ld_test_volume.c => build_test_volume.cpp} | 0 mri_mc/{mri_mc.c => mri_mc.cpp} | 0 mri_mc/{mri_pretess.c => mri_pretess.cpp} | 0 ...nent.c => mris_extract_main_component.cpp} | 0 mri_mcsim/CMakeLists.txt | 2 +- mri_mcsim/{mri_mcsim.c => mri_mcsim.cpp} | 8 +- mri_mi/CMakeLists.txt | 2 +- mri_mi/{mri_mi.c => mri_mi.cpp} | 2 - mri_modify/mri_copy_params.cpp | 4 +- mri_modify/mri_modify.cpp | 4 +- mri_morphology/CMakeLists.txt | 2 +- .../{mri_morphology.c => mri_morphology.cpp} | 6 +- mri_mosaic/CMakeLists.txt | 2 +- mri_mosaic/{mri_mosaic.c => mri_mosaic.cpp} | 6 +- mri_ms_EM/CMakeLists.txt | 2 +- .../{PoissonSolver.c => PoissonSolver.cpp} | 0 mri_ms_EM/{mri_ms_EM.c => mri_ms_EM.cpp} | 6 +- mri_ms_EM/{myutils.c => myutils.cpp} | 0 mri_ms_EM_with_atlas/CMakeLists.txt | 2 +- .../{PoissonSolver.c => PoissonSolver.cpp} | 0 ..._with_atlas.c => mri_ms_EM_with_atlas.cpp} | 6 +- .../{myutils.c => myutils.cpp} | 0 .../{subroutines.c => subroutines.cpp} | 0 mri_ms_LDA/CMakeLists.txt | 2 +- mri_ms_LDA/{mri_ms_LDA.c => mri_ms_LDA.cpp} | 6 +- mri_ms_fitparms/CMakeLists.txt | 2 +- ...{mri_ms_fitparms.c => mri_ms_fitparms.cpp} | 6 +- mri_multiscale_segment/CMakeLists.txt | 2 +- ...e_segment.c => mri_multiscale_segment.cpp} | 6 +- mri_multispectral_segment/CMakeLists.txt | 2 +- ...egment.c => mri_multispectral_segment.cpp} | 0 mri_nlfilter/CMakeLists.txt | 2 +- .../{mri_nlfilter.c => mri_nlfilter.cpp} | 0 mri_normalize/CMakeLists.txt | 4 +- ...ong_normalize.c => mri_long_normalize.cpp} | 0 .../{mri_normalize.c => mri_normalize.cpp} | 6 +- mri_normalize_tp2/CMakeLists.txt | 2 +- ..._normalize_tp2.c => mri_normalize_tp2.cpp} | 0 mri_otl/CMakeLists.txt | 4 +- ...{list_otl_labels.c => list_otl_labels.cpp} | 0 mri_paint/CMakeLists.txt | 2 +- mri_paint/{mri_paint.c => mri_paint.cpp} | 0 mri_parse_sdcmdir/CMakeLists.txt | 4 +- ..._parse_sdcmdir.c => mri_parse_sdcmdir.cpp} | 0 mri_parselabel/mri_parselabel.cpp | 4 +- mri_partial_ribbon/CMakeLists.txt | 2 +- ...artial_ribbon.c => mri_partial_ribbon.cpp} | 1 - mri_path2label/CMakeLists.txt | 2 +- .../{mri_path2label.c => mri_path2label.cpp} | 1 - mri_polv/CMakeLists.txt | 2 +- mri_polv/{mri_polv.c => mri_polv.cpp} | 0 mri_probe_ima/CMakeLists.txt | 2 +- .../{mri_probe_ima.c => mri_probe_ima.cpp} | 2 +- mri_probedicom/CMakeLists.txt | 3 +- .../{mri_probedicom.c => mri_probedicom.cpp} | 0 mri_rbvpvc/mri_rbvpvc.c | 87 +- mri_reduce/CMakeLists.txt | 2 +- mri_reduce/{mri_reduce.c => mri_reduce.cpp} | 0 mri_refine_seg/CMakeLists.txt | 2 +- mri_refine_seg/mri_refine_seg.cpp | 10 +- mri_register/CMakeLists.txt | 2 +- .../{mri_register.c => mri_register.cpp} | 6 +- mri_relabel_hypointensities/CMakeLists.txt | 2 +- ...ties.c => mri_relabel_hypointensities.cpp} | 0 mri_relabel_nonwm_hypos/CMakeLists.txt | 2 +- ...wm_hypos.c => mri_relabel_nonwm_hypos.cpp} | 0 mri_remove_neck/CMakeLists.txt | 2 +- ...{mri_remove_neck.c => mri_remove_neck.cpp} | 6 +- mri_rf_label/CMakeLists.txt | 2 +- .../{mri_rf_label.c => mri_rf_label.cpp} | 10 +- mri_rf_long_label/CMakeLists.txt | 2 +- ..._rf_long_label.c => mri_rf_long_label.cpp} | 10 +- mri_rf_long_train/CMakeLists.txt | 2 +- ..._rf_long_train.c => mri_rf_long_train.cpp} | 6 +- mri_rf_train/CMakeLists.txt | 2 +- .../{mri_rf_train.c => mri_rf_train.cpp} | 6 +- mri_ribbon/CMakeLists.txt | 2 +- mri_ribbon/{mri_ribbon.c => mri_ribbon.cpp} | 0 mri_rigid_register/CMakeLists.txt | 2 +- ...igid_register.c => mri_rigid_register.cpp} | 6 +- mri_robust_register/CostFunctions.cpp | 8 - mri_robust_register/CostFunctions.h | 7 - mri_robust_register/JointHisto.h | 7 - mri_robust_register/MultiRegistration.cpp | 8 - mri_robust_register/MultiRegistration.h | 7 - mri_robust_register/MyMRI.cpp | 8 - mri_robust_register/MyMRI.h | 7 - mri_robust_register/MyMatrix.cpp | 13 +- mri_robust_register/MyMatrix.h | 7 - mri_robust_register/RegPowell.h | 7 - mri_robust_register/Registration.cpp | 8 - mri_robust_register/Registration.h | 7 - mri_robust_register/RegistrationStep.h | 7 - mri_robust_register/Regression.cpp | 7 - mri_robust_register/Regression.h | 7 - mri_robust_register/RobustGaussian.cpp | 8 +- mri_robust_register/lta_diff.cpp | 9 - mri_robust_register/mri_create_tests.cpp | 9 - mri_robust_register/mri_gradient_info.cpp | 9 - mri_robust_register/mri_robust_register.cpp | 29 +- mri_robust_register/mri_robust_template.cpp | 15 +- mri_sbbr/CMakeLists.txt | 2 +- mri_sbbr/{mri_sbbr.c => mri_sbbr.cpp} | 25 +- mri_seg_diff/CMakeLists.txt | 2 +- .../{mri_seg_diff.c => mri_seg_diff.cpp} | 0 mri_seg_overlap/CMakeLists.txt | 2 +- mri_seg_overlap/mri_seg_overlap.cpp | 40 +- mri_segcentroids/mri_segcentroids.cpp | 4 +- mri_seghead/CMakeLists.txt | 2 +- .../{mri_seghead.c => mri_seghead.cpp} | 0 mri_segment/CMakeLists.txt | 2 +- .../{mri_segment.c => mri_segment.cpp} | 10 +- mri_segment_tumor/CMakeLists.txt | 2 +- ..._segment_tumor.c => mri_segment_tumor.cpp} | 1 - mri_segment_wm_damage/CMakeLists.txt | 2 +- ..._wm_damage.c => mri_segment_wm_damage.cpp} | 6 +- mri_segreg/CMakeLists.txt | 2 +- mri_segreg/{mri_segreg.c => mri_segreg.cpp} | 18 +- mri_segstats/CMakeLists.txt | 2 +- .../{mri_segstats.c => mri_segstats.cpp} | 0 mri_simulate_atrophy/CMakeLists.txt | 2 +- ...ate_atrophy.c => mri_simulate_atrophy.cpp} | 6 +- mri_stats2seg/CMakeLists.txt | 2 +- .../{mri_stats2seg.c => mri_stats2seg.cpp} | 2 +- mri_strip_nonwhite/CMakeLists.txt | 2 +- ...trip_nonwhite.c => mri_strip_nonwhite.cpp} | 5 +- mri_strip_subject_info/CMakeLists.txt | 2 +- ...ject_info.c => mri_strip_subject_info.cpp} | 0 mri_surf2surf/CMakeLists.txt | 2 +- .../{mri_surf2surf.c => mri_surf2surf.cpp} | 0 mri_surf2vol/CMakeLists.txt | 2 +- .../{mri_surf2vol.c => mri_surf2vol.cpp} | 0 mri_surfacemask/mri_surfacemask.cpp | 4 +- mri_surfcluster/CMakeLists.txt | 2 +- ...{mri_surfcluster.c => mri_surfcluster.cpp} | 0 mri_synthesize/CMakeLists.txt | 2 +- .../{mri_synthesize.c => mri_synthesize.cpp} | 0 mri_tessellate/CMakeLists.txt | 4 +- ...{ico_supersample.c => ico_supersample.cpp} | 0 .../{mri_tessellate.c => mri_tessellate.cpp} | 4 +- mri_tessellate/trilib.h | 6 +- mri_threshold/CMakeLists.txt | 2 +- .../{mri_threshold.c => mri_threshold.cpp} | 0 mri_topologycorrection/CMakeLists.txt | 2 +- ...orrection.c => mri_topologycorrection.cpp} | 0 mri_train/CMakeLists.txt | 2 +- mri_train/{mri_train.c => mri_train.cpp} | 13 +- mri_train_autoencoder/CMakeLists.txt | 4 +- ...utoencoder.c => mri_apply_autoencoder.cpp} | 6 +- ...utoencoder.c => mri_train_autoencoder.cpp} | 6 +- mri_transform/CMakeLists.txt | 2 +- .../{mri_transform.c => mri_transform.cpp} | 0 mri_transform_to_COR/CMakeLists.txt | 2 +- ...form_to_COR.c => mri_transform_to_COR.cpp} | 0 mri_twoclass/CMakeLists.txt | 2 +- .../{mri_twoclass.c => mri_twoclass.cpp} | 6 +- mri_update_gca/CMakeLists.txt | 2 +- .../{mri_update_gca.c => mri_update_gca.cpp} | 6 +- mri_vol2roi/CMakeLists.txt | 2 +- .../{mri_vol2roi.c => mri_vol2roi.cpp} | 2 +- mri_vol2surf/CMakeLists.txt | 2 +- .../{mri_vol2surf.c => mri_vol2surf.cpp} | 0 mri_vol2vol/CMakeLists.txt | 2 +- .../{mri_vol2vol.c => mri_vol2vol.cpp} | 38 +- mri_volcluster/CMakeLists.txt | 2 +- .../{mri_volcluster.c => mri_volcluster.cpp} | 0 mri_voldiff/CMakeLists.txt | 2 +- .../{mri_voldiff.c => mri_voldiff.cpp} | 0 mri_volsynth/CMakeLists.txt | 2 +- .../{mri_volsynth.c => mri_volsynth.cpp} | 0 mri_warp_convert/mri_warp_convert.cpp | 10 - mri_watershed/CMakeLists.txt | 2 +- mri_watershed/brain_volume/TVector.h | 3 - .../brain_volume/mri_brain_volume.cpp | 18 +- mri_watershed/brain_volume/mrivariables.h | 13 +- mri_watershed/mri_validate_skull_stripped.cpp | 5 +- mri_watershed/mri_watershed.cpp | 39 +- mri_wbc/CMakeLists.txt | 2 +- mri_wbc/{mri_wbc.c => mri_wbc.cpp} | 11 +- mri_wmfilter/CMakeLists.txt | 2 +- .../{mri_wmfilter.c => mri_wmfilter.cpp} | 0 mri_xcorr/CMakeLists.txt | 2 +- mri_xcorr/{mri_xcorr.c => mri_xcorr.cpp} | 0 mri_xvolavg/CMakeLists.txt | 2 +- .../{mri_xvolavg.c => mri_xvolavg.cpp} | 0 mri_z2p/CMakeLists.txt | 2 +- mri_z2p/{mri_z2p.c => mri_z2p.cpp} | 0 mris2rgb/CMakeLists.txt | 2 +- mris2rgb/{mris2rgb.c => mris2rgb.cpp} | 3 +- mris2rgb/{oglutil.c => oglutil.cpp} | 0 mris2rgb/{texfont.c => texfont.cpp} | 0 mris_BA_segment/CMakeLists.txt | 2 +- ...{mris_BA_segment.c => mris_BA_segment.cpp} | 0 mris_add_template/CMakeLists.txt | 2 +- ...s_add_template.c => mris_add_template.cpp} | 0 mris_anatomical_stats/CMakeLists.txt | 2 +- ...ical_stats.c => mris_anatomical_stats.cpp} | 0 mris_annot_to_segmentation/CMakeLists.txt | 2 +- ...ation.c => mris_annot_to_segmentation.cpp} | 2 +- mris_apply_reg/CMakeLists.txt | 2 +- .../{mris_apply_reg.c => mris_apply_reg.cpp} | 0 mris_aseg_distance/CMakeLists.txt | 2 +- ...aseg_distance.c => mris_aseg_distance.cpp} | 0 mris_average_curvature/CMakeLists.txt | 2 +- ...curvature.c => mris_average_curvature.cpp} | 0 mris_average_parcellation/CMakeLists.txt | 2 +- ...lation.c => mris_average_parcellation.cpp} | 6 +- mris_ca_label/CMakeLists.txt | 2 +- .../{mris_ca_label.c => mris_ca_label.cpp} | 6 +- mris_ca_train/CMakeLists.txt | 2 +- .../{mris_ca_train.c => mris_ca_train.cpp} | 6 +- mris_calc/CMakeLists.txt | 2 +- mris_calc/{mris_calc.c => mris_calc.cpp} | 7 +- mris_classify_thickness/CMakeLists.txt | 2 +- ...hickness.c => mris_classify_thickness.cpp} | 60 +- mris_compute_acorr/CMakeLists.txt | 2 +- ...compute_acorr.c => mris_compute_acorr.cpp} | 0 mris_compute_optimal_kernel/CMakeLists.txt | 2 +- ...rnel.c => mris_compute_optimal_kernel.cpp} | 0 mris_compute_overlap/CMakeLists.txt | 2 +- ...ute_overlap.c => mris_compute_overlap.cpp} | 10 +- mris_compute_parc_overlap/CMakeLists.txt | 2 +- ...verlap.c => mris_compute_parc_overlap.cpp} | 5 +- mris_compute_volume_fractions/CMakeLists.txt | 2 +- ...ns.c => mris_compute_volume_fractions.cpp} | 0 .../{myown.c => myown.cpp} | 0 mris_congeal/CMakeLists.txt | 2 +- .../{mris_congeal.c => mris_congeal.cpp} | 5 +- mris_convert/CMakeLists.txt | 2 +- .../{mris_convert.c => mris_convert.cpp} | 2 +- mris_copy_header/CMakeLists.txt | 2 +- ...ris_copy_header.c => mris_copy_header.cpp} | 0 mris_curvature/CMakeLists.txt | 2 +- .../{mris_curvature.c => mris_curvature.cpp} | 0 mris_curvature_stats/CMakeLists.txt | 2 +- ...ature_stats.c => mris_curvature_stats.cpp} | 12 +- mris_decimate/main.cpp | 6 +- mris_decimate/mris_decimate.cpp | 6 +- mris_decimate/mris_decimate.h | 6 +- mris_defects_pointset/CMakeLists.txt | 2 +- .../mris_defects_pointset.cpp | 18 +- mris_deform/CMakeLists.txt | 6 +- .../{mris_ca_deform.c => mris_ca_deform.cpp} | 6 +- .../{mris_deform.c => mris_deform.cpp} | 9 +- mris_deform/{mris_nudge.c => mris_nudge.cpp} | 0 mris_density/CMakeLists.txt | 2 +- .../{mris_density.c => mris_density.cpp} | 0 mris_diff/CMakeLists.txt | 2 +- mris_diff/{mris_diff.c => mris_diff.cpp} | 0 mris_distance_map/CMakeLists.txt | 2 +- ...s_distance_map.c => mris_distance_map.cpp} | 0 mris_distance_to_label/CMakeLists.txt | 2 +- .../mris_distance_to_label.cpp | 10 +- mris_distance_transform/CMakeLists.txt | 2 +- ...ransform.c => mris_distance_transform.cpp} | 6 +- mris_divide_parcellation/CMakeLists.txt | 2 +- ...llation.c => mris_divide_parcellation.cpp} | 0 mris_entropy/CMakeLists.txt | 2 +- .../{mris_entropy.c => mris_entropy.cpp} | 0 mris_errors/CMakeLists.txt | 2 +- .../{mris_errors.c => mris_errors.cpp} | 0 mris_euler_number/CMakeLists.txt | 2 +- ...s_euler_number.c => mris_euler_number.cpp} | 0 mris_expand/CMakeLists.txt | 2 +- .../{mris_expand.c => mris_expand.cpp} | 6 +- mris_extract_patches/CMakeLists.txt | 2 +- ...act_patches.c => mris_extract_patches.cpp} | 6 +- mris_fbirn_annot/CMakeLists.txt | 2 +- ...ris_fbirn_annot.c => mris_fbirn_annot.cpp} | 0 mris_fill/CMakeLists.txt | 2 +- mris_fill/{mris_fill.c => mris_fill.cpp} | 6 +- mris_find_flat_regions/CMakeLists.txt | 2 +- ...t_regions.c => mris_find_flat_regions.cpp} | 0 mris_fix_topology/CMakeLists.txt | 4 +- ...s_fix_topology.c => mris_fix_topology.cpp} | 6 +- ...section.c => mris_remove_intersection.cpp} | 6 +- mris_flatten/CMakeLists.txt | 2 +- .../{mris_flatten.c => mris_flatten.cpp} | 0 mris_fwhm/CMakeLists.txt | 2 +- mris_fwhm/{mris_fwhm.c => mris_fwhm.cpp} | 2 +- mris_glm/CMakeLists.txt | 2 +- mris_glm/{mris_glm.c => mris_glm.cpp} | 0 mris_hausdorff_dist/CMakeLists.txt | 2 +- ...usdorff_dist.c => mris_hausdorff_dist.cpp} | 6 +- mris_inflate/CMakeLists.txt | 2 +- .../{mris_inflate.c => mris_inflate.cpp} | 6 +- mris_info/mris_info.cpp | 6 +- mris_init_global_tractography/CMakeLists.txt | 2 +- ...hy.c => mris_init_global_tractography.cpp} | 6 +- mris_interpolate_warp/CMakeLists.txt | 2 +- ...olate_warp.c => mris_interpolate_warp.cpp} | 6 +- mris_jacobian/CMakeLists.txt | 2 +- .../{mris_jacobian.c => mris_jacobian.cpp} | 0 mris_label2annot/CMakeLists.txt | 2 +- ...ris_label2annot.c => mris_label2annot.cpp} | 0 mris_label_area/CMakeLists.txt | 2 +- ...{mris_label_area.c => mris_label_area.cpp} | 9 +- mris_label_calc/mris_label_calc.cpp | 9 - mris_label_mode/CMakeLists.txt | 2 +- ...{mris_label_mode.c => mris_label_mode.cpp} | 0 mris_left_right_register/CMakeLists.txt | 2 +- ...egister.c => mris_left_right_register.cpp} | 5 +- mris_longitudinal_surfaces/CMakeLists.txt | 2 +- ...faces.c => mris_longitudinal_surfaces.cpp} | 8 +- mris_make_average_surface/CMakeLists.txt | 2 +- ...urface.c => mris_make_average_surface.cpp} | 0 mris_make_face_parcellation/CMakeLists.txt | 2 +- ...tion.c => mris_make_face_parcellation.cpp} | 6 +- mris_make_map_surfaces/CMakeLists.txt | 2 +- ..._surfaces.c => mris_make_map_surfaces.cpp} | 0 mris_make_surfaces/CMakeLists.txt | 8 +- ...vo_surfaces.c => mris_exvivo_surfaces.cpp} | 8 +- ...make_surfaces.c => mris_make_surfaces.cpp} | 22 +- ...s_mef_surfaces.c => mris_mef_surfaces.cpp} | 14 +- ...ne_surfaces.c => mris_refine_surfaces.cpp} | 8 +- mris_make_template/CMakeLists.txt | 2 +- ...make_template.c => mris_make_template.cpp} | 2 +- mris_map_cuts/CMakeLists.txt | 2 +- .../{mris_map_cuts.c => mris_map_cuts.cpp} | 6 +- mris_merge_parcellations/CMakeLists.txt | 2 +- ...lations.c => mris_merge_parcellations.cpp} | 6 +- mris_mesh_subdivide/mris_mesh_subdivide.cxx | 12 +- mris_morph_stats/CMakeLists.txt | 2 +- ...ris_morph_stats.c => mris_morph_stats.cpp} | 0 mris_ms_refine/CMakeLists.txt | 2 +- .../{mris_ms_refine.c => mris_ms_refine.cpp} | 20 +- mris_ms_surface_CNR/CMakeLists.txt | 2 +- ..._surface_CNR.c => mris_ms_surface_CNR.cpp} | 8 +- mris_multiscale_stats/CMakeLists.txt | 2 +- ...cale_stats.c => mris_multiscale_stats.cpp} | 6 +- mris_niters2fwhm/CMakeLists.txt | 2 +- ...ris_niters2fwhm.c => mris_niters2fwhm.cpp} | 0 mris_parcellate_connectivity/CMakeLists.txt | 2 +- ...ity.c => mris_parcellate_connectivity.cpp} | 6 +- mris_pmake/CMakeLists.txt | 4 +- mris_pmake/{abs2rel.c => abs2rel.cpp} | 0 mris_pmake/general.cpp | 4 +- mris_pmake/mris_pmake.cpp | 4 +- mris_pmake/{rel2abs.c => rel2abs.cpp} | 0 mris_pval_fill/mris_pval_fill.c | 6 +- mris_register/CMakeLists.txt | 2 +- .../{mris_register.c => mris_register.cpp} | 5 +- mris_register_label_map/CMakeLists.txt | 2 +- ...abel_map.c => mris_register_label_map.cpp} | 0 mris_register_to_volume/CMakeLists.txt | 4 +- ..._to_label.c => mris_register_to_label.cpp} | 6 +- ...o_volume.c => mris_register_to_volume.cpp} | 19 +- mris_remove_variance/CMakeLists.txt | 2 +- ...ve_variance.c => mris_remove_variance.cpp} | 0 mris_resample/CMakeLists.txt | 2 +- mris_resample/mris_resample.cpp | 10 +- mris_rescale/CMakeLists.txt | 2 +- .../{mris_rescale.c => mris_rescale.cpp} | 0 mris_reverse/CMakeLists.txt | 2 +- .../{mris_reverse.c => mris_reverse.cpp} | 0 mris_rf_label/CMakeLists.txt | 2 +- .../{mris_rf_label.c => mris_rf_label.cpp} | 18 +- mris_rf_train/CMakeLists.txt | 2 +- .../{mris_rf_train.c => mris_rf_train.cpp} | 6 +- mris_rotate/CMakeLists.txt | 2 +- .../{mris_rotate.c => mris_rotate.cpp} | 0 mris_sample_label/CMakeLists.txt | 2 +- ...s_sample_label.c => mris_sample_label.cpp} | 0 mris_sample_parc/CMakeLists.txt | 2 +- ...ris_sample_parc.c => mris_sample_parc.cpp} | 0 mris_seg2annot/CMakeLists.txt | 2 +- .../{mris_seg2annot.c => mris_seg2annot.cpp} | 0 mris_segment/CMakeLists.txt | 2 +- .../{mris_segment.c => mris_segment.cpp} | 8 +- mris_segment_vals/CMakeLists.txt | 2 +- ...s_segment_vals.c => mris_segment_vals.cpp} | 0 mris_segmentation_stats/CMakeLists.txt | 2 +- ...on_stats.c => mris_segmentation_stats.cpp} | 9 +- mris_shrinkwrap/CMakeLists.txt | 4 +- ...AA_shrinkwrap.c => mris_AA_shrinkwrap.cpp} | 6 +- ...{mris_shrinkwrap.c => mris_shrinkwrap.cpp} | 6 +- mris_simulate_atrophy/CMakeLists.txt | 2 +- ...te_atrophy.c => mris_simulate_atrophy.cpp} | 6 +- mris_smooth/CMakeLists.txt | 2 +- .../{mris_smooth.c => mris_smooth.cpp} | 0 mris_spharm/mris_spharm.c | 10 +- mris_sphere/CMakeLists.txt | 4 +- ...es.c => mris_remove_negative_vertices.cpp} | 6 +- .../{mris_sphere.c => mris_sphere.cpp} | 6 +- mris_spherical_average/CMakeLists.txt | 2 +- ...l_average.c => mris_spherical_average.cpp} | 0 .../mris_spherical_wavelets.c | 6 +- mris_surface_change/CMakeLists.txt | 2 +- ...rface_change.c => mris_surface_change.cpp} | 0 mris_surface_stats/CMakeLists.txt | 2 +- ...surface_stats.c => mris_surface_stats.cpp} | 6 +- mris_surface_to_vol_distances/CMakeLists.txt | 2 +- ...es.c => mris_surface_to_vol_distances.cpp} | 6 +- mris_svm_classify/CMakeLists.txt | 2 +- ...s_svm_classify.c => mris_svm_classify.cpp} | 6 +- mris_svm_train/CMakeLists.txt | 2 +- .../{mris_svm_train.c => mris_svm_train.cpp} | 6 +- mris_talairach/CMakeLists.txt | 2 +- .../{mris_talairach.c => mris_talairach.cpp} | 0 mris_thickness/CMakeLists.txt | 6 +- ...r_profiles.c => mris_cluster_profiles.cpp} | 0 .../{mris_gradient.c => mris_gradient.cpp} | 0 ...y_profile.c => mris_intensity_profile.cpp} | 0 .../{mris_thickness.c => mris_thickness.cpp} | 6 +- mris_thickness_comparison/CMakeLists.txt | 2 +- ...arison.c => mris_thickness_comparison.cpp} | 0 mris_thickness_diff/CMakeLists.txt | 2 +- ...ickness_diff.c => mris_thickness_diff.cpp} | 4 +- mris_topo_fixer/CMakeLists.txt | 17 +- {utilscpp => mris_topo_fixer}/face.cpp | 2 +- {include/topology => mris_topo_fixer}/face.h | 4 - {utilscpp => mris_topo_fixer}/fastloop.cpp | 4 +- .../topology => mris_topo_fixer}/fastloop.h | 4 - {utilscpp => mris_topo_fixer}/globals.cpp | 25 +- .../topology => mris_topo_fixer}/globals.h | 4 - {utilscpp => mris_topo_fixer}/loop.cpp | 2 +- {include/topology => mris_topo_fixer}/loop.h | 4 - mris_topo_fixer/mris_topo_fixer.cpp | 14 +- .../mris_topology.cpp | 18 +- {include => mris_topo_fixer}/mris_topology.h | 21 +- {utilscpp => mris_topo_fixer}/patchdisk.cpp | 2 +- .../topology => mris_topo_fixer}/patchdisk.h | 5 - {utilscpp => mris_topo_fixer}/segment.cpp | 2 +- .../topology => mris_topo_fixer}/segment.h | 4 - {utilscpp => mris_topo_fixer}/surface.cpp | 8 +- .../topology => mris_topo_fixer}/surface.h | 4 - {utilscpp => mris_topo_fixer}/vertex.cpp | 2 +- .../topology => mris_topo_fixer}/vertex.h | 5 - mris_transform/CMakeLists.txt | 2 +- .../{mris_transform.c => mris_transform.cpp} | 0 mris_translate_annotation/CMakeLists.txt | 2 +- ...tation.c => mris_translate_annotation.cpp} | 0 .../CMakeLists.txt | 2 +- ...c => mris_transmantle_dysplasia_paths.cpp} | 6 +- mris_twoclass/CMakeLists.txt | 2 +- .../{mris_twoclass.c => mris_twoclass.cpp} | 6 +- mris_volmask/TestMRISDistanceField.cpp | 4 +- mris_volmask/TestMRISOBBTree.cpp | 4 +- mris_volmask/cmd_line_interface.h | 7 - mris_volmask/mris_volmask.cpp | 14 +- mris_volmask/mris_volmask_old.cpp | 6 +- mris_volume/CMakeLists.txt | 4 +- .../{mris_volume.c => mris_volume.cpp} | 6 +- .../{mris_wm_volume.c => mris_wm_volume.cpp} | 6 +- mris_w_to_curv/CMakeLists.txt | 2 +- .../{mris_w_to_curv.c => mris_w_to_curv.cpp} | 0 mris_warp/CMakeLists.txt | 2 +- mris_warp/{mris_warp.c => mris_warp.cpp} | 6 +- mris_watershed/CMakeLists.txt | 2 +- .../{mris_watershed.c => mris_watershed.cpp} | 0 mrisp_paint/CMakeLists.txt | 2 +- .../{mrisp_paint.c => mrisp_paint.cpp} | 0 mrisp_write/CMakeLists.txt | 2 +- .../{mrisp_write.c => mrisp_write.cpp} | 0 oct_register_mosaic/CMakeLists.txt | 2 +- ...ister_mosaic.c => oct_register_mosaic.cpp} | 8 +- oct_train/CMakeLists.txt | 4 +- .../{oct_rf_train.c => oct_rf_train.cpp} | 6 +- oct_train/{oct_train.c => oct_train.cpp} | 6 +- optseq2/CMakeLists.txt | 2 +- optseq2/{optseq2.c => optseq2.cpp} | 2 +- packages/CMakeLists.txt | 23 + packages/cephes/CMakeLists.txt | 18 + {utils => packages}/cephes/bdtr.c | 0 {include => packages/cephes}/cephes.h | 0 {utils => packages}/cephes/chdtr.c | 0 {utils => packages}/cephes/const.c | 0 {utils => packages}/cephes/fdtr.c | 0 {utils => packages}/cephes/gamma.c | 0 {utils => packages}/cephes/igam.c | 0 {utils => packages}/cephes/igami.c | 0 {utils => packages}/cephes/incbet.c | 0 {utils => packages}/cephes/incbi.c | 0 {include => packages/cephes}/mconf.h | 10 - {utils => packages}/cephes/mtherr.c | 0 {utils => packages}/cephes/ndtr.c | 0 {utils => packages}/cephes/ndtri.c | 0 {utils => packages}/cephes/polevl.c | 0 {utils => packages}/cephes/stdtr.c | 0 packages/dicom/CMakeLists.txt | 17 + {dicom => packages/dicom}/condition.c | 0 {include => packages}/dicom/condition.h | 0 {include => packages}/dicom/ctn_os.h | 0 {dicom => packages/dicom}/ctnthread.c | 0 {include => packages}/dicom/ctnthread.h | 0 {dicom => packages/dicom}/dcm.c | 0 {dicom => packages/dicom}/dcmcond.c | 0 {dicom => packages/dicom}/dcmdict.c | 0 {include => packages}/dicom/dcmprivate.h | 0 {dicom => packages/dicom}/dcmsupport.c | 0 {include => packages}/dicom/dicom.h | 0 {include => packages}/dicom/dicom_objects.h | 0 {include => packages}/dicom/dicom_platform.h | 17 +- {include => packages}/dicom/dicom_uids.h | 0 {dicom => packages/dicom}/lst.c | 0 {include => packages}/dicom/lst.h | 0 {include => packages}/dicom/lstprivate.h | 0 packages/expat/CMakeLists.txt | 10 +- packages/gifti/CMakeLists.txt | 8 + {utils => packages/gifti}/gifti_io.c | 0 {include => packages/gifti}/gifti_io.h | 14 +- {utils => packages/gifti}/gifti_tool.c | 0 {utils => packages/gifti}/gifti_tool.h | 0 {utils => packages/gifti}/gifti_xml.c | 4 +- {include => packages/gifti}/gifti_xml.h | 0 packages/glut/CMakeLists.txt | 101 +- packages/jpeg/CMakeLists.txt | 9 +- packages/minc/CMakeLists.txt | 6 +- packages/minc/minc.h | 14 + packages/minc/minc_basic.h | 171 +- packages/minc/minc_convenience.c | 3 - packages/minc/minc_files.c | 4 - packages/minc/minc_files.h | 10 +- packages/minc/minc_gaussian.c | 5 - packages/minc/minc_image_conversion.c | 4 - packages/minc/minc_input_free.c | 4 - packages/minc/minc_input_mnc.c | 3 - packages/minc/minc_internals.h | 9 +- packages/minc/minc_inverse.c | 7 +- packages/minc/minc_multidim_arrays.c | 4 - .../minc}/minc_multidim_arrays.h | 8 +- packages/minc/minc_netcdf_convenience.c | 9 - packages/minc/minc_netcdf_convenience.h | 29 +- packages/minc/minc_output_mnc.c | 3 - packages/minc/minc_output_volume.c | 5 - packages/minc/minc_progress.c | 3 - {include => packages/minc}/minc_structures.h | 0 packages/minc/minc_time.c | 28 +- packages/minc/minc_value_conversion.c | 4 - packages/minc/minc_varlists.h | 1 - packages/minc/minc_volume_io.c | 20 - {include => packages/minc}/minc_volume_io.h | 52 - packages/netcdf/CMakeLists.txt | 6 +- packages/nifti/CMakeLists.txt | 3 + {include => packages/nifti}/nifti1.h | 0 {utils => packages/nifti}/nifti1_io.c | 0 {include => packages/nifti}/nifti1_io.h | 0 {utils => packages/nifti}/znzlib.c | 0 {include => packages/nifti}/znzlib.h | 0 {utils/NrrdIO => packages/nrrdio}/754.c | 0 packages/nrrdio/CMakeLists.txt | 52 + {include/NrrdIO => packages/nrrdio}/NrrdIO.h | 89 +- {utils/NrrdIO => packages/nrrdio}/accessors.c | 0 {utils/NrrdIO => packages/nrrdio}/array.c | 0 .../NrrdIO => packages/nrrdio}/arraysNrrd.c | 0 {utils/NrrdIO => packages/nrrdio}/axis.c | 0 {utils/NrrdIO => packages/nrrdio}/biffbiff.c | 0 {utils/NrrdIO => packages/nrrdio}/comment.c | 0 .../nrrdio}/copyright.NrrdIO | 0 .../NrrdIO => packages/nrrdio}/defaultsNrrd.c | 0 {utils/NrrdIO => packages/nrrdio}/dio.c | 0 {utils/NrrdIO => packages/nrrdio}/encoding.c | 0 .../nrrdio}/encodingAscii.c | 0 .../nrrdio}/encodingBzip2.c | 0 .../NrrdIO => packages/nrrdio}/encodingGzip.c | 0 .../NrrdIO => packages/nrrdio}/encodingHex.c | 0 .../NrrdIO => packages/nrrdio}/encodingRaw.c | 0 {utils/NrrdIO => packages/nrrdio}/endianAir.c | 0 .../NrrdIO => packages/nrrdio}/endianNrrd.c | 0 {utils/NrrdIO => packages/nrrdio}/enum.c | 0 {utils/NrrdIO => packages/nrrdio}/enumsNrrd.c | 0 {utils/NrrdIO => packages/nrrdio}/format.c | 0 {utils/NrrdIO => packages/nrrdio}/formatEPS.c | 0 .../NrrdIO => packages/nrrdio}/formatNRRD.c | 0 {utils/NrrdIO => packages/nrrdio}/formatPNG.c | 0 {utils/NrrdIO => packages/nrrdio}/formatPNM.c | 0 .../NrrdIO => packages/nrrdio}/formatText.c | 0 {utils/NrrdIO => packages/nrrdio}/formatVTK.c | 0 {utils/NrrdIO => packages/nrrdio}/gzio.c | 0 {utils/NrrdIO => packages/nrrdio}/keyvalue.c | 0 .../NrrdIO => packages/nrrdio}/methodsNrrd.c | 0 {utils/NrrdIO => packages/nrrdio}/miscAir.c | 0 {utils/NrrdIO => packages/nrrdio}/mop.c | 0 {utils/NrrdIO => packages/nrrdio}/parseAir.c | 0 {utils/NrrdIO => packages/nrrdio}/parseNrrd.c | 0 .../NrrdIO => packages/nrrdio}/privateAir.h | 0 .../NrrdIO => packages/nrrdio}/privateNrrd.h | 0 {utils/NrrdIO => packages/nrrdio}/qnanhibit.c | 0 {utils/NrrdIO => packages/nrrdio}/read.c | 0 {utils/NrrdIO => packages/nrrdio}/reorder.c | 0 {utils/NrrdIO => packages/nrrdio}/sampleIO.c | 0 {utils/NrrdIO => packages/nrrdio}/sane.c | 0 {utils/NrrdIO => packages/nrrdio}/simple.c | 0 {utils/NrrdIO => packages/nrrdio}/string.c | 0 {utils/NrrdIO => packages/nrrdio}/subset.c | 0 .../NrrdIO => packages/nrrdio}/teem32bit.h | 0 {include/NrrdIO => packages/nrrdio}/teemDio.h | 0 .../NrrdIO => packages/nrrdio}/teemEndian.h | 0 {include/NrrdIO => packages/nrrdio}/teemPng.h | 0 .../nrrdio}/teemQnanhibit.h | 0 {utils/NrrdIO => packages/nrrdio}/write.c | 0 {svm-lib => packages/svm}/CMakeLists.txt | 8 +- {svm-lib => packages/svm}/README.txt | 0 {svm-lib => packages/svm}/svm-data-param.cpp | 0 {svm-lib => packages/svm}/svm-data-param.h | 0 {svm-lib => packages/svm}/svm-element-type.h | 0 {svm-lib => packages/svm}/svm-element-types.h | 0 {svm-lib => packages/svm}/svm-io-format.h | 0 {svm-lib => packages/svm}/svm-kernel-param.h | 0 {svm-lib => packages/svm}/svm-kernel.cpp | 0 {svm-lib => packages/svm}/svm-kernel.h | 0 {svm-lib => packages/svm}/svm-lib-c.cpp | 0 {svm-lib => packages/svm}/svm-lib-c.h | 0 {svm-lib => packages/svm}/svm-lib.cpp | 0 {svm-lib => packages/svm}/svm-lib.h | 0 {svm-lib => packages/svm}/svm-matrix.h | 0 {svm-lib => packages/svm}/svm-model.cpp | 0 {svm-lib => packages/svm}/svm-model.h | 0 {svm-lib => packages/svm}/svm-param.cpp | 0 {svm-lib => packages/svm}/svm-param.h | 0 .../svm/svm-pr-loqo.cpp | 0 {svm-lib => packages/svm}/svm-pr-loqo.h | 0 {svm-lib => packages/svm}/svm-similarity.cpp | 0 {svm-lib => packages/svm}/svm-similarity.h | 0 {svm-lib => packages/svm}/svm-sketch.cpp | 0 {svm-lib => packages/svm}/svm-sketch.h | 0 {svm-lib => packages/svm}/svm-vector-types.h | 0 {svm-lib => packages/svm}/svm-vector.h | 0 packages/tetgen/CMakeLists.txt | 4 - packages/tiff/CMakeLists.txt | 8 +- packages/xml2/CMakeLists.txt | 9 +- python/bindings/surface.h | 2 - python/bindings/volume.h | 2 - qdec/QdecMain.cxx | 8 +- qdec/vtkKWQdecWindow.cxx | 2 - qdec/vtkKWQdecWindow.h | 2 - qdec_glmfit/qdec_glmfit.cxx | 2 - qdecproject/QdecContrast.cxx | 8 - qdecproject/QdecGlmDesign.cxx | 7 +- rbftest/CMakeLists.txt | 2 +- rbftest/{rbftest.c => rbftest.cpp} | 46 +- regdat2xfm/regdat2xfm.cpp | 4 +- repair_siemens_file/CMakeLists.txt | 2 +- ...siemens_file.c => repair_siemens_file.cpp} | 8 - resurf/CMakeLists.txt | 6 +- resurf/Code/fsSurface.h | 6 +- resurf/mris_multimodal.cxx | 6 +- resurf/mris_profileClustering.cxx | 6 +- resurf/mris_surf2vtk.cxx | 6 +- rgb/CMakeLists.txt | 18 - rgb/close.c | 77 - rgb/filbuf.c | 42 - rgb/flsbuf.c | 42 - rgb/name.c | 17 - rgb/open.c | 302 - rgb/pix.c | 25 - rgb/rdwr.c | 88 - rgb/rgbutils.c | 135 - rgb/rle.c | 168 - rgb/row.c | 350 - spherical_stats/CMakeLists.txt | 2 +- ...{spherical_stats.c => spherical_stats.cpp} | 8 +- stat_normalize/CMakeLists.txt | 2 +- .../{stat_normalize.c => stat_normalize.cpp} | 0 stim_polar/CMakeLists.txt | 2 +- stim_polar/{stim_polar.c => stim_polar.cpp} | 0 svm-lib/INSTALL_README.txt | 31 - svm-lib/classification_setup.example | 71 - swi_processing/CMakeLists.txt | 2 +- swi_processing/cmd_line_interface.h | 8 - swi_processing/swi_preprocess.cpp | 4 - swi_processing/swi_process.cpp | 4 - talairach_afd/CMakeLists.txt | 2 +- .../{talairach_afd.c => talairach_afd.cpp} | 0 template/CMakeLists.txt | 2 +- .../{main_template.c => main_template.cpp} | 6 +- ...lastic_energy.c => mri_elastic_energy.cpp} | 6 +- ...e_segment.c => mri_multiscale_segment.cpp} | 6 +- template/{template.c => template.cpp} | 0 test_exclude_minc/test_exclude_minc.c | 79 - test_makevol/CMakeLists.txt | 2 +- test_makevol/{main.c => main.cpp} | 0 tkmedit/development_notes.txt | 133 - tkmedit/tkmDisplayArea.c | 8829 ----- tkmedit/tkmDisplayArea.h | 790 - tkmedit/tkmFunctionalVolume.c | 4830 --- tkmedit/tkmFunctionalVolume.h | 485 - tkmedit/tkmMeditWindow.c | 5439 --- tkmedit/tkmMeditWindow.h | 481 - tkmedit/tkmedit.c | 13645 ------- tkmedit/tkmedit.h | 443 - tkregister2/CMakeLists.txt | 2 +- .../{tkregister2.c => tkregister2.cpp} | 6 +- tksurfer/development_notes.txt | 165 - tksurfer/tksurfer.c | 31484 ---------------- trc/dmri_forrest.cxx | 6 +- trc/dmri_group.cxx | 6 +- trc/dmri_mergepaths.cxx | 6 +- trc/dmri_motion.cxx | 6 +- trc/dmri_paths.cxx | 6 +- trc/dmri_pathstats.cxx | 6 +- trc/dmri_spline.cxx | 14 +- trc/dmri_train.cxx | 6 +- trc/dmri_trk2trk.cxx | 6 +- trc/dmri_vox2vox.cxx | 6 +- tridec/CMakeLists.txt | 2 +- tridec/{tridec.c => tridec.cpp} | 0 utils/{Bruker.c => Bruker.cpp} | 6 - utils/CMakeLists.txt | 492 +- utils/{DICOMRead.c => DICOMRead.cpp} | 43 +- ...ARS_DT_Boundary.c => MARS_DT_Boundary.cpp} | 0 ...nGlobal.c => MRISrigidBodyAlignGlobal.cpp} | 12 +- utils/{MRIio_old.c => MRIio_old.cpp} | 8 +- utils/{Progname.c => Progname.cpp} | 0 utils/{afni.c => afni.cpp} | 8 +- utils/{annotation.c => annotation.cpp} | 20 +- {utilscpp => utils}/argparse.cpp | 43 +- utils/art1.c | 457 - utils/artmap.c | 578 - utils/aseg_edit_svm.c | 143 - utils/{autoencoder.c => autoencoder.cpp} | 0 utils/backprop.c | 1379 - utils/{bfileio.c => bfileio.cpp} | 60 +- utils/{box.c => box.cpp} | 0 utils/{chklc.c => chklc.cpp} | 2 +- utils/{chronometer.c => chronometer.cpp} | 0 utils/{class_array.c => class_array.cpp} | 4 +- utils/{cluster.c => cluster.cpp} | 0 utils/{cma.c => cma.cpp} | 9 +- utils/{cmat.c => cmat.cpp} | 0 utils/{cmdargs.c => cmdargs.cpp} | 0 utils/{colortab.c => colortab.cpp} | 14 +- utils/{connectcomp.c => connectcomp.cpp} | 4 +- utils/{corio.c => corio.cpp} | 0 utils/cpputils.cpp | 9 +- utils/{ctrpoints.c => ctrpoints.cpp} | 2 +- utils/{cvector.c => cvector.cpp} | 4 +- utils/dcdflib.c | 9166 ----- utils/{dct.c => dct.cpp} | 0 utils/{density.c => density.cpp} | 0 utils/{diag.c => diag.cpp} | 4 +- utils/{diffuse.c => diffuse.cpp} | 17 - utils/{dmatrix.c => dmatrix.cpp} | 0 utils/{dti.c => dti.cpp} | 16 +- utils/{dtk.fs.c => dtk.fs.cpp} | 12 +- utils/{error.c => error.cpp} | 11 +- utils/{evschutils.c => evschutils.cpp} | 4 +- utils/{fcd.c => fcd.cpp} | 0 utils/{fftutils.c => fftutils.cpp} | 4 +- utils/{field_code.c => field_code.cpp} | 2 +- utils/{filter.c => filter.cpp} | 8 +- utils/{fio.c => fio.cpp} | 0 utils/{flash.c => flash.cpp} | 0 utils/fmarchmesh.c | 454 - utils/{fmriutils.c => fmriutils.cpp} | 0 utils/{fnv_hash_test.c => fnv_hash_test.cpp} | 0 utils/{fsPrintHelp.c => fsPrintHelp.cpp} | 14 +- utils/fs_powell.cpp | 8 +- utils/{fsenv.c => fsenv.cpp} | 0 utils/{fsgdf.c => fsgdf.cpp} | 0 utils/{fsglm.c => fsglm.cpp} | 7 +- utils/{fsinit.c => fsinit.cpp} | 0 utils/{gca.c => gca.cpp} | 51 +- utils/{gcaboundary.c => gcaboundary.cpp} | 0 utils/{gcamorph.c => gcamorph.cpp} | 16 +- utils/gcarray.c | 1087 - utils/{gclass.c => gclass.cpp} | 22 +- utils/{gcsa.c => gcsa.cpp} | 7 +- utils/geodesics.cpp | 49 +- utils/{geos.c => geos.cpp} | 0 utils/{getdelim.c => getdelim.cpp} | 0 utils/{getline.c => getline.cpp} | 0 utils/{gifti_local.c => gifti.cpp} | 16 +- utils/gifti_test.c | 448 - utils/gifti_test.h | 25 - utils/{gtm.c => gtm.cpp} | 63 +- utils/{gw_ic2562.c => gw_ic2562.cpp} | 0 utils/{gw_utils.c => gw_utils.cpp} | 2 +- utils/handle.c | 220 - utils/heap.c | 528 - utils/{hippo.c => hippo.cpp} | 4 +- utils/hips.cpp | 60 + utils/{histo.c => histo.cpp} | 4 +- utils/{ic12.c => ic12.cpp} | 0 utils/{ic163842.c => ic163842.cpp} | 0 utils/{ic2562.c => ic2562.cpp} | 0 utils/{ic42.c => ic42.cpp} | 0 utils/{ic642.c => ic642.cpp} | 0 utils/{icosahedron.c => icosahedron.cpp} | 0 utils/{image.c => image.cpp} | 100 +- utils/{imageio.c => imageio.cpp} | 166 +- utils/{imautils.c => imautils.cpp} | 12 +- utils/{intensity_eig.c => intensity_eig.cpp} | 0 utils/{ipmpar.c => ipmpar.cpp} | 0 utils/{joint_histo.c => joint_histo.cpp} | 0 utils/{kernel.c => kernel.cpp} | 2 - utils/kinput.c | 285 - utils/{label.c => label.cpp} | 39 +- utils/log.cpp | 59 + utils/lpafile.c | 481 - {utilscpp => utils}/lut.cpp | 2 +- utils/{machine.c => machine.cpp} | 0 utils/{matfile.c => matfile.cpp} | 4 +- utils/{matrix.c => matrix.cpp} | 2 +- utils/{mgh_filter.c => mgh_filter.cpp} | 0 utils/{mgh_malloc.c => mgh_malloc.cpp} | 0 utils/mgh_matrix.c | 658 - utils/{min_heap.c => min_heap.cpp} | 0 utils/mincutils.c | 273 - utils/minmaxrc.c | 184 - utils/{morph.c => morph.cpp} | 2 +- utils/{mosaic.c => mosaic.cpp} | 0 utils/{mri.c => mri.cpp} | 28 +- utils/{mri2.c => mri2.cpp} | 38 +- utils/{mriBSpline.c => mriBSpline.cpp} | 2 +- utils/mriFunctionalDataAccess.c | 2878 -- utils/mriHeadPointList.c | 1150 - utils/mriSurface.c | 1382 - utils/{mriTransform.c => mriTransform.cpp} | 459 +- utils/mriVolume.c | 3655 -- utils/{mri_conform.c => mri_conform.cpp} | 46 +- utils/mri_fastmarching.cpp | 17 +- utils/{mri_identify.c => mri_identify.cpp} | 31 +- utils/{mri_level_set.c => mri_level_set.cpp} | 0 utils/{mri_tess.c => mri_tess.cpp} | 0 utils/{mri_topology.c => mri_topology.cpp} | 0 utils/mri_transform.c | 88 - utils/{mriclass.c => mriclass.cpp} | 55 +- utils/{mricurv.c => mricurv.cpp} | 0 utils/{mrifilter.c => mrifilter.cpp} | 32 +- utils/{mriflood.c => mriflood.cpp} | 18 +- utils/{mrihisto.c => mrihisto.cpp} | 2 +- utils/{mriio.c => mriio.cpp} | 289 +- utils/mriio_nrrd.c | 226 - utils/mriio_nrrd_itk.cpp | 265 - utils/{mrimorph.c => mrimorph.cpp} | 15 +- utils/{mrinorm.c => mrinorm.cpp} | 4 +- utils/{mripolv.c => mripolv.cpp} | 4 +- utils/{mriprob.c => mriprob.cpp} | 0 ...ris_compVolFrac.c => mris_compVolFrac.cpp} | 0 {utilscpp => utils}/mris_fastmarching.cpp | 38 +- utils/mrisbiorthogonalwavelets.c | 659 - utils/{mrisegment.c => mrisegment.cpp} | 0 utils/{mriset.c => mriset.cpp} | 24 +- utils/{mrishash.c => mrishash.cpp} | 10 +- utils/{mrisp.c => mrisp.cpp} | 2 +- utils/{mrisurf.c => mrisurf.cpp} | 6 +- utils/{mrisurf_base.c => mrisurf_base.cpp} | 20 +- .../{mrisurf_defect.c => mrisurf_defect.cpp} | 13 +- .../{mrisurf_deform.c => mrisurf_deform.cpp} | 22 +- ...surf_integrate.c => mrisurf_integrate.cpp} | 26 +- utils/{mrisurf_io.c => mrisurf_io.cpp} | 45 +- ...perties.c => mrisurf_metricProperties.cpp} | 47 +- utils/{mrisurf_mri.c => mrisurf_mri.cpp} | 43 +- ...risurf_obsolete.c => mrisurf_obsolete.cpp} | 4 +- ...risurf_timeStep.c => mrisurf_timeStep.cpp} | 26 +- ...risurf_topology.c => mrisurf_topology.cpp} | 35 +- utils/{mrisurf_vals.c => mrisurf_vals.cpp} | 0 utils/{mrisutils.c => mrisutils.cpp} | 17 +- utils/{mrivoxel.c => mrivoxel.cpp} | 2 +- utils/numerics.cpp | 103 +- utils/{offset.c => offset.cpp} | 11 +- utils/{path.c => path.cpp} | 1 - utils/{pdf.c => pdf.cpp} | 0 utils/{pgmstubs.c => pgmstubs.cpp} | 0 {utilscpp => utils}/pointset.cpp | 6 +- utils/{prime.c => prime.cpp} | 0 utils/queue.c | 167 - utils/{randomfields.c => randomfields.cpp} | 0 utils/{rbf.c => rbf.cpp} | 81 +- utils/{rbm.c => rbm.cpp} | 0 utils/{realm.c => realm.cpp} | 40 +- utils/rec.c | 192 - utils/{region.c => region.cpp} | 0 utils/{registerio.c => registerio.cpp} | 4 +- utils/{resample.c => resample.cpp} | 7 +- utils/rescale.c | 139 - utils/{retinotopy.c => retinotopy.cpp} | 0 utils/{rfa.c => rfa.cpp} | 2 +- utils/{rforest.c => rforest.cpp} | 6 +- utils/{rfutils.c => rfutils.cpp} | 0 utils/rgb.cpp | 926 + utils/{romp_support.c => romp_support.cpp} | 161 +- utils/{selxavgio.c => selxavgio.cpp} | 0 utils/{sig.c => sig.cpp} | 0 utils/{signa.c => signa.cpp} | 0 utils/{sort.c => sort.cpp} | 0 utils/{stats.c => stats.cpp} | 6 +- utils/stc.c | 202 - utils/{surfcluster.c => surfcluster.cpp} | 12 +- utils/{surfgrad.c => surfgrad.cpp} | 0 utils/{svm.c => svm.cpp} | 0 utils/{tags.c => tags.cpp} | 1 + utils/{talairachex.c => talairachex.cpp} | 0 utils/test/MRISresampleOntoSphere.cpp | 6 +- utils/test/MRISwaveletsTransform.cpp | 6 +- utils/test/mri_concatenate_lta.c | 2 +- utils/test/mri_ms_LDA.c | 6 +- utils/test/mri_ms_compute_CNR.c | 6 +- utils/test/mri_ms_gca_EM.c | 6 +- utils/test/mris_indirect_morph.cpp | 6 +- utils/test/sse_mathfun_test.c | 1183 - utils/thread.c | 449 - utils/timer.c | 137 - utils/timer.cpp | 53 + utils/{transform.c => transform.cpp} | 10 +- utils/{tritri.c => tritri.cpp} | 0 utils/{tukey.c => tukey.cpp} | 0 utils/{utils.c => utils.cpp} | 24 +- utils/{version.c => version.cpp} | 8 +- utils/{vertexRotator.c => vertexRotator.cpp} | 10 +- utils/{vlabels.c => vlabels.cpp} | 0 utils/{volcluster.c => volcluster.cpp} | 0 utils/{voxlist.c => voxlist.cpp} | 0 utils/x3DList.c | 538 - utils/{xDebug.c => xDebug.cpp} | 2 +- utils/xGLutWindow.c | 756 - utils/xGrowableArray.c | 295 - utils/xList.c | 632 - utils/xSparseVolume.c | 380 - utils/{xTypes.c => xTypes.cpp} | 0 utils/xUndoList.c | 460 - utils/xUtilities.c | 200 - utils/xVoxel.c | 206 - utils/xVoxel.cpp | 206 + utils/{xmlToHtml.c => xmlToHtml.cpp} | 0 utilscpp/CMakeLists.txt | 26 - utilscpp/log.cpp | 72 - utilscpp/test/ctest.c | 54 - vtkfsio/CMakeLists.txt | 21 - vtkfsio/lh.vtkFSSurfaceWriterTestFile | Bin 13626 -> 0 bytes vtkfsio/vtkFSSurfaceLabelSource.cxx | 370 - vtkfsio/vtkFSSurfaceLabelSource.h | 106 - vtkfsio/vtkFSSurfaceScalarsReader.cxx | 98 - vtkfsio/vtkFSSurfaceScalarsReader.h | 73 - vtkfsio/vtkFSSurfaceSource.cxx | 622 - vtkfsio/vtkFSSurfaceSource.h | 148 - vtkfsio/vtkFSSurfaceWriter.cxx | 147 - vtkfsio/vtkFSSurfaceWriter.h | 74 - vtkfsio/vtkFSSurfaceWriterTester.cxx | 77 - vtkfsio/vtkFSVolumeSource.cxx | 884 - vtkfsio/vtkFSVolumeSource.h | 184 - vtkutils/vtkFreesurferLookupTable.h | 2 - .../vtkKWRGBATransferFunctionEditorTester.cxx | 8 +- 1564 files changed, 5774 insertions(+), 171438 deletions(-) rename check_siemens_dir/{check_siemens_dir.c => check_siemens_dir.cpp} (98%) delete mode 100644 dicom/CMakeLists.txt rename dmri_tensoreig/{dmri_tensoreig.c => dmri_tensoreig.cpp} (99%) rename dngtester/{dngtester.c => dngtester.cpp} (97%) delete mode 100644 dummy/dummy.c create mode 100644 dummy/dummy.cpp delete mode 100644 dummy/myown.c delete mode 100644 fem_elastic/simple_timer.h rename hiam_make_surfaces/{hiam_make_surfaces.c => hiam_make_surfaces.cpp} (100%) rename hiam_make_template/{hiam_make_template.c => hiam_make_template.cpp} (94%) rename hiam_register/{hiam_register.c => hiam_register.cpp} (99%) delete mode 100644 hipsstubs/CMakeLists.txt delete mode 100644 hipsstubs/hipsrepl.c delete mode 100644 hipsstubs/hipsstubs.c rename histo_compute_joint_density/{histo_compute_joint_density.c => histo_compute_joint_density.cpp} (97%) rename histo_fix_topology/{histo_fix_topology.c => histo_fix_topology.cpp} (100%) rename histo_register_block/{histo_register_block.c => histo_register_block.cpp} (100%) rename histo_segment/{histo_segment.c => histo_segment.cpp} (100%) rename histo_synthesize/{histo_synthesize.c => histo_synthesize.cpp} (99%) rename include/{argparse.hpp => argparse.h} (96%) delete mode 100644 include/art1.h delete mode 100644 include/artmap.h delete mode 100644 include/aseg_edit_svm.h delete mode 100644 include/backprop.h delete mode 100644 include/canny.h delete mode 100644 include/cdflib.h delete mode 100644 include/congraph.h delete mode 100644 include/connect.h delete mode 100644 include/fexterns.h delete mode 100644 include/fgutil.h delete mode 100644 include/filecode.h delete mode 100644 include/fmarchmesh.h delete mode 100644 include/gcarray.h rename include/{gifti_local.h => gifti.h} (86%) delete mode 100644 include/gmm/gmm.h delete mode 100644 include/gmm/gmm_MUMPS_interface.h delete mode 100644 include/gmm/gmm_algobase.h delete mode 100644 include/gmm/gmm_blas.h delete mode 100644 include/gmm/gmm_blas_interface.h delete mode 100644 include/gmm/gmm_condition_number.h delete mode 100644 include/gmm/gmm_conjugated.h delete mode 100644 include/gmm/gmm_def.h delete mode 100644 include/gmm/gmm_dense_Householder.h delete mode 100644 include/gmm/gmm_dense_lu.h delete mode 100644 include/gmm/gmm_dense_qr.h delete mode 100644 include/gmm/gmm_dense_sylvester.h delete mode 100644 include/gmm/gmm_domain_decomp.h delete mode 100644 include/gmm/gmm_except.h delete mode 100644 include/gmm/gmm_inoutput.h delete mode 100644 include/gmm/gmm_interface.h delete mode 100644 include/gmm/gmm_interface_bgeot.h delete mode 100644 include/gmm/gmm_iter.h delete mode 100644 include/gmm/gmm_iter_solvers.h delete mode 100644 include/gmm/gmm_kernel.h delete mode 100644 include/gmm/gmm_lapack_interface.h delete mode 100644 include/gmm/gmm_least_squares_cg.h delete mode 100644 include/gmm/gmm_matrix.h delete mode 100644 include/gmm/gmm_modified_gram_schmidt.h delete mode 100644 include/gmm/gmm_opt.h delete mode 100644 include/gmm/gmm_precond.h delete mode 100644 include/gmm/gmm_precond_diagonal.h delete mode 100644 include/gmm/gmm_precond_ildlt.h delete mode 100644 include/gmm/gmm_precond_ildltt.h delete mode 100644 include/gmm/gmm_precond_ilu.h delete mode 100644 include/gmm/gmm_precond_ilut.h delete mode 100644 include/gmm/gmm_precond_ilutp.h delete mode 100644 include/gmm/gmm_precond_mr_approx_inverse.h delete mode 100644 include/gmm/gmm_real_part.h delete mode 100644 include/gmm/gmm_ref.h delete mode 100644 include/gmm/gmm_scaled.h delete mode 100644 include/gmm/gmm_solver_Newton.h delete mode 100644 include/gmm/gmm_solver_Schwarz_additive.h delete mode 100644 include/gmm/gmm_solver_bfgs.h delete mode 100644 include/gmm/gmm_solver_bicgstab.h delete mode 100644 include/gmm/gmm_solver_cg.h delete mode 100644 include/gmm/gmm_solver_constrained_cg.h delete mode 100644 include/gmm/gmm_solver_gmres.h delete mode 100644 include/gmm/gmm_solver_idgmres.h delete mode 100644 include/gmm/gmm_solver_qmr.h delete mode 100644 include/gmm/gmm_std.h delete mode 100644 include/gmm/gmm_sub_index.h delete mode 100644 include/gmm/gmm_sub_matrix.h delete mode 100644 include/gmm/gmm_sub_vector.h delete mode 100644 include/gmm/gmm_superlu_interface.h delete mode 100644 include/gmm/gmm_transposed.h delete mode 100644 include/gmm/gmm_tri_solve.h delete mode 100644 include/gmm/gmm_vector.h delete mode 100644 include/gmm/gmm_vector_to_matrix.h delete mode 100644 include/h_logz.h delete mode 100644 include/handle.h delete mode 100644 include/heap.h delete mode 100644 include/hip_brf.h delete mode 100644 include/hipl_for.h delete mode 100644 include/hipl_format.h delete mode 100644 include/hips_basic.h delete mode 100644 include/hips_error.h delete mode 100644 include/hips_header.h delete mode 100644 include/hips_parser.h delete mode 100644 include/hipsext.h delete mode 100644 include/hipsh.h delete mode 100644 include/hipspub.h delete mode 100644 include/hipsu.h delete mode 100644 include/inverse.h delete mode 100644 include/iutils.h rename include/{json.hpp => json.h} (100%) delete mode 100644 include/kinput.h delete mode 100644 include/ldtmplt.h create mode 100644 include/log.h delete mode 100644 include/log.hpp delete mode 100644 include/lpafile.h rename include/{lut.hpp => lut.h} (95%) delete mode 100644 include/mailbox.h delete mode 100644 include/map.h delete mode 100644 include/mgh_filter.h delete mode 100644 include/mgh_matrix.h delete mode 100644 include/mincutils.h delete mode 100644 include/minmaxrc.h delete mode 100644 include/mriFunctionalDataAccess.h delete mode 100644 include/mriHeadPointList.h delete mode 100644 include/mriROI.h delete mode 100644 include/mriSurface.h delete mode 100644 include/mriTypes.h delete mode 100644 include/mriVolume.h delete mode 100644 include/mri_ca_labelMapper.h delete mode 100644 include/mri_ca_labelingParameters.h delete mode 100644 include/mri_ca_measMapper.h delete mode 100644 include/mri_ca_sparse3DMatrix.h delete mode 100644 include/mri_transform.h delete mode 100644 include/mris_expand.h delete mode 100644 include/mrisbiorthogonalwavelets.h delete mode 100644 include/mthread.h delete mode 100644 include/omp_support.h delete mode 100644 include/pbm.h delete mode 100644 include/pbmplus.h delete mode 100644 include/pgm.h delete mode 100644 include/pixrect/bw2var.h delete mode 100644 include/pixrect/cg12_var.h delete mode 100644 include/pixrect/cg2reg.h delete mode 100644 include/pixrect/cg2var.h delete mode 100644 include/pixrect/cg3var.h delete mode 100644 include/pixrect/cg4var.h delete mode 100644 include/pixrect/cg8var.h delete mode 100644 include/pixrect/cg9var.h delete mode 100644 include/pixrect/gp1cmds.h delete mode 100644 include/pixrect/gp1reg.h delete mode 100644 include/pixrect/gp1var.h delete mode 100644 include/pixrect/gt_fbi.h delete mode 100644 include/pixrect/gt_rp.h delete mode 100644 include/pixrect/gtvar.h delete mode 100644 include/pixrect/mem32_var.h delete mode 100644 include/pixrect/mem_rop_impl_ops.h delete mode 100644 include/pixrect/mem_rop_impl_util.h delete mode 100644 include/pixrect/memreg.h delete mode 100644 include/pixrect/memvar.h delete mode 100644 include/pixrect/pixfont.h delete mode 100644 include/pixrect/pixrect.h delete mode 100644 include/pixrect/pixrect_hs.h delete mode 100644 include/pixrect/pr_dblbuf.h delete mode 100644 include/pixrect/pr_impl_make.h delete mode 100644 include/pixrect/pr_impl_util.h delete mode 100644 include/pixrect/pr_io.h delete mode 100644 include/pixrect/pr_line.h delete mode 100644 include/pixrect/pr_planegroups.h delete mode 100644 include/pixrect/pr_util.h delete mode 100644 include/pixrect/traprop.h delete mode 100644 include/pixrect/tv1var.h delete mode 100644 include/pnm.h rename include/{pointset.hpp => pointset.h} (97%) delete mode 100644 include/ppm.h delete mode 100644 include/queue.h delete mode 100644 include/rec.h delete mode 100644 include/rescale.h create mode 100644 include/rgb.h delete mode 100644 include/rgb_image.h delete mode 100644 include/rgb_utils.h delete mode 100644 include/runfuncs.h delete mode 100644 include/sse_mathfun.h delete mode 100644 include/stc.h delete mode 100644 include/struct.h delete mode 100644 include/sys/timeb.h delete mode 100644 include/thread.h rename include/{topology => }/topo_parms.h (100%) delete mode 100644 include/trig512.h delete mode 100644 include/x3DList.h delete mode 100644 include/xGLutWindow.h delete mode 100644 include/xGrowableArray.h delete mode 100644 include/xList.h delete mode 100644 include/xSparseVolume.h delete mode 100644 include/xUndoList.h delete mode 100644 include/xUtilities.h delete mode 100644 include/xview/alert.h delete mode 100644 include/xview/attr.h delete mode 100644 include/xview/attrol.h delete mode 100644 include/xview/base.h delete mode 100644 include/xview/canvas.h delete mode 100644 include/xview/cms.h delete mode 100644 include/xview/cms_grays.h delete mode 100644 include/xview/cms_mono.h delete mode 100644 include/xview/cms_rgb.h delete mode 100644 include/xview/cmsrainbow.h delete mode 100644 include/xview/cursor.h delete mode 100644 include/xview/db.h delete mode 100644 include/xview/defaults.h delete mode 100644 include/xview/dragdrop.h delete mode 100644 include/xview/drawable.h delete mode 100644 include/xview/expandname.h delete mode 100644 include/xview/font.h delete mode 100644 include/xview/frame.h delete mode 100644 include/xview/fullscreen.h delete mode 100644 include/xview/generic.h delete mode 100644 include/xview/icon.h delete mode 100644 include/xview/icon_load.h delete mode 100644 include/xview/notice.h delete mode 100644 include/xview/notify.h delete mode 100644 include/xview/openmenu.h delete mode 100644 include/xview/openwin.h delete mode 100644 include/xview/panel.h delete mode 100644 include/xview/pixwin.h delete mode 100644 include/xview/pkg.h delete mode 100644 include/xview/pkg_public.h delete mode 100644 include/xview/rect.h delete mode 100644 include/xview/rectlist.h delete mode 100644 include/xview/screen.h delete mode 100644 include/xview/scrollbar.h delete mode 100644 include/xview/sel_attrs.h delete mode 100644 include/xview/sel_compat.h delete mode 100644 include/xview/sel_pkg.h delete mode 100644 include/xview/sel_svc.h delete mode 100644 include/xview/selection.h delete mode 100644 include/xview/seln.h delete mode 100644 include/xview/server.h delete mode 100644 include/xview/str_utils.h delete mode 100644 include/xview/sun.h delete mode 100644 include/xview/svrimage.h delete mode 100644 include/xview/termsw.h delete mode 100644 include/xview/text.h delete mode 100644 include/xview/textsw.h delete mode 100644 include/xview/tty.h delete mode 100644 include/xview/ttysw.h delete mode 100644 include/xview/win_enum.h delete mode 100644 include/xview/win_env.h delete mode 100644 include/xview/win_event.h delete mode 100644 include/xview/win_input.h delete mode 100644 include/xview/win_notify.h delete mode 100644 include/xview/win_screen.h delete mode 100644 include/xview/win_struct.h delete mode 100644 include/xview/window.h delete mode 100644 include/xview/window_hs.h delete mode 100644 include/xview/wmgr.h delete mode 100644 include/xview/xv_c_types.h delete mode 100644 include/xview/xv_error.h delete mode 100644 include/xview/xv_i18n.h delete mode 100644 include/xview/xv_version.h delete mode 100644 include/xview/xv_xrect.h delete mode 100644 include/xview/xview.h delete mode 100644 include/xview/xview_xvin.h rename label2flat/{label2flat.c => label2flat.cpp} (99%) rename label2patch/{label2patch.c => label2patch.cpp} (99%) rename label_area/{label_area.c => label_area.cpp} (99%) rename label_border/{label_border.c => label_border.cpp} (99%) delete mode 100644 log/CMakeLists.txt delete mode 100644 log/congraph.c delete mode 100644 log/connect.c delete mode 100644 log/h_logz.c delete mode 100644 log/lmedian.c delete mode 100644 log/map.c delete mode 100644 log/runfuncs.c rename mkxsubjreg/{mkxsubjreg.c => mkxsubjreg.cpp} (100%) rename mri_add_xform_to_header/{mri_add_xform_to_header.c => mri_add_xform_to_header.cpp} (99%) rename mri_and/{mri_and.c => mri_and.cpp} (98%) rename mri_and/{mri_or.c => mri_or.cpp} (98%) rename mri_annotation2label/{mri_annotation2label.c => mri_annotation2label.cpp} (100%) rename mri_aparc2aseg/{mri_aparc2aseg.c => mri_aparc2aseg.cpp} (100%) rename mri_aparc2wmseg/{mri_aparc2wmseg.c => mri_aparc2wmseg.cpp} (100%) rename mri_apply_inu_correction/{mri_apply_inu_correction.c => mri_apply_inu_correction.cpp} (100%) rename mri_aseg_edit_reclassify/{mri_aseg_edit_reclassify.c => mri_aseg_edit_reclassify.cpp} (98%) rename mri_aseg_edit_train/{mri_aseg_edit_train.c => mri_aseg_edit_train.cpp} (99%) rename mri_auto_fill/{mri_auto_fill.c => mri_auto_fill.cpp} (99%) rename mri_average/{mri_average.c => mri_average.cpp} (99%) rename mri_bc_sc_bias_correct/{mri_bc_sc_bias_correct.c => mri_bc_sc_bias_correct.cpp} (100%) rename mri_bias/{mri_apply_bias.c => mri_apply_bias.cpp} (98%) rename mri_bias/{mri_compute_bias.c => mri_compute_bias.cpp} (99%) rename mri_binarize/{mri_binarize.c => mri_binarize.cpp} (100%) rename mri_build_priors/{mri_build_priors.c => mri_build_priors.cpp} (100%) rename mri_ca_label/{mri_ca_label.c => mri_ca_label.cpp} (99%) rename mri_ca_normalize/{mri_ca_normalize.c => mri_ca_normalize.cpp} (99%) rename mri_ca_normalize/{mri_cal_normalize.c => mri_cal_normalize.cpp} (99%) rename mri_ca_register/{mri_ca_register.c => mri_ca_register.cpp} (99%) rename mri_ca_tissue_parms/{mri_ca_tissue_parms.c => mri_ca_tissue_parms.cpp} (99%) rename mri_ca_train/{mri_ca_train.c => mri_ca_train.cpp} (99%) rename mri_cal_renormalize_gca/{mri_cal_renormalize_gca.c => mri_cal_renormalize_gca.cpp} (99%) rename mri_cc/{mri_cc.c => mri_cc.cpp} (99%) rename mri_cht2p/{mri_cht2p.c => mri_cht2p.cpp} (100%) rename mri_classify/{mri_classify.c => mri_classify.cpp} (99%) rename mri_cnr/{mri_cnr.c => mri_cnr.cpp} (100%) rename mri_compile_edits/{mri_compile_edits.c => mri_compile_edits.cpp} (100%) rename mri_compute_change_map/{mri_compute_change_map.c => mri_compute_change_map.cpp} (99%) rename mri_compute_overlap/{mri_compute_overlap.c => mri_compute_overlap.cpp} (99%) rename mri_compute_seg_overlap/{mri_compute_seg_overlap.c => mri_compute_seg_overlap.cpp} (100%) rename mri_compute_structure_transforms/{mri_compute_structure_transforms.c => mri_compute_structure_transforms.cpp} (98%) rename mri_compute_volume_fractions/{mri_compute_layer_fractions.c => mri_compute_layer_fractions.cpp} (99%) rename mri_compute_volume_fractions/{mri_compute_volume_fractions.c => mri_compute_volume_fractions.cpp} (98%) rename mri_compute_volume_fractions/{mri_compute_volume_intensities.c => mri_compute_volume_intensities.cpp} (99%) rename mri_compute_volume_fractions/{mris_compute_layer_intensities.c => mris_compute_layer_intensities.cpp} (99%) rename mri_concat/{mri_concat.c => mri_concat.cpp} (100%) rename mri_concatenate_lta/{mri_concatenate_lta.c => mri_concatenate_lta.cpp} (99%) rename mri_convert/{mri_convert.c => mri_convert.cpp} (93%) rename mri_convert/{mri_make_uchar.c => mri_make_uchar.cpp} (98%) rename mri_convert_mdh/{mri_convert_mdh.c => mri_convert_mdh.cpp} (100%) rename mri_copy_values/{mri_copy_values.c => mri_copy_values.cpp} (100%) rename mri_cor2label/{mri_cor2label.c => mri_cor2label.cpp} (100%) rename mri_coreg/{mri_coreg.c => mri_coreg.cpp} (99%) rename mri_correct_segmentations/{mri_correct_segmentations.c => mri_correct_segmentations.cpp} (99%) rename mri_dct_align/{mri_dct_align.c => mri_dct_align.cpp} (99%) rename mri_dct_align/{mri_dct_align_binary.c => mri_dct_align_binary.cpp} (99%) rename mri_deface/{mri_deface.c => mri_deface.cpp} (99%) rename mri_diff/{mri_diff.c => mri_diff.cpp} (100%) rename mri_divide_segmentation/{mri_divide_segmentation.c => mri_divide_segmentation.cpp} (99%) rename mri_edit_segmentation/{mri_edit_segmentation.c => mri_edit_segmentation.cpp} (99%) rename mri_edit_segmentation_with_surfaces/{mri_edit_segmentation_with_surfaces.c => mri_edit_segmentation_with_surfaces.cpp} (100%) rename mri_edit_wm_with_aseg/{mri_edit_wm_with_aseg.c => mri_edit_wm_with_aseg.cpp} (99%) rename mri_elastic_energy/{mri_elastic_energy.c => mri_elastic_energy.cpp} (97%) rename mri_em_register/{mri_em_register.c => mri_em_register.cpp} (99%) rename mri_estimate_tissue_parms/{mri_estimate_tissue_parms.c => mri_estimate_tissue_parms.cpp} (99%) rename mri_evaluate_morph/{mri_evaluate_morph.c => mri_evaluate_morph.cpp} (100%) rename mri_extract/{mri_extract.c => mri_extract.cpp} (100%) rename mri_extract_conditions/{mri_extract_conditions.c => mri_extract_conditions.cpp} (100%) rename mri_extract_fcd_features/{mri_extract_fcd_features.c => mri_extract_fcd_features.cpp} (99%) rename mri_extract_label/{mri_extract_label.c => mri_extract_label.cpp} (100%) rename mri_extract_largest_CC/{mri_extract_largest_CC.c => mri_extract_largest_CC.cpp} (100%) rename mri_extract_largest_CC/{myutils.c => myutils.cpp} (100%) rename mri_extract_largest_CC/{subroutines.c => subroutines.cpp} (100%) rename mri_fcili/{mri_fcili.c => mri_fcili.cpp} (100%) rename mri_fdr/{mri_fdr.c => mri_fdr.cpp} (99%) rename mri_fieldsign/{mri_fieldsign.c => mri_fieldsign.cpp} (99%) rename mri_fill/{mri_fill.c => mri_fill.cpp} (99%) rename mri_fill/{myutil.c => myutil.cpp} (100%) rename mri_fill/{subroutines.c => subroutines.cpp} (100%) rename mri_fit_bias/{mri_fit_bias.c => mri_fit_bias.cpp} (94%) rename mri_fslmat_to_lta/{mri_fslmat_to_lta.c => mri_fslmat_to_lta.cpp} (100%) rename mri_fuse_intensity_images/{mri_fuse_intensity_images.c => mri_fuse_intensity_images.cpp} (99%) rename mri_fwhm/{mri_fwhm.c => mri_fwhm.cpp} (100%) rename mri_gca_ambiguous/{mri_gca_ambiguous.c => mri_gca_ambiguous.cpp} (97%) rename mri_gcab_train/{mri_gcab_train.c => mri_gcab_train.cpp} (99%) rename mri_gdfglm/{mri_gdfglm.c => mri_gdfglm.cpp} (100%) rename mri_glmfit/{mri_glmfit.c => mri_glmfit.cpp} (99%) rename mri_gtmpvc/{mri_gtmpvc.c => mri_gtmpvc.cpp} (97%) rename mri_gtmseg/{mri_gtmseg.c => mri_gtmseg.cpp} (99%) rename mri_hausdorff_dist/{mri_hausdorff_dist.c => mri_hausdorff_dist.cpp} (99%) rename mri_head/{mri_head.c => mri_head.cpp} (100%) rename mri_hires_register/{mri_compute_distances.c => mri_compute_distances.cpp} (99%) rename mri_hires_register/{mri_hires_register.c => mri_hires_register.cpp} (99%) rename mri_hires_register/{mri_linear_align.c => mri_linear_align.cpp} (99%) rename mri_hires_register/{mri_linear_align_binary.c => mri_linear_align_binary.cpp} (99%) rename mri_hires_register/{mri_nl_align.c => mri_nl_align.cpp} (99%) rename mri_hires_register/{mri_nl_align_binary.c => mri_nl_align_binary.cpp} (99%) rename mri_histo_eq/{mri_histo_eq.c => mri_histo_eq.cpp} (98%) rename mri_histo_normalize/{mri_histo_normalize.c => mri_histo_normalize.cpp} (98%) rename mri_ibmc/{mri_ibmc.c => mri_ibmc.cpp} (99%) rename mri_info/{mri_info.c => mri_info.cpp} (99%) rename mri_interpolate/{mri_interpolate.c => mri_interpolate.cpp} (100%) rename mri_jacobian/{mri_jacobian.c => mri_jacobian.cpp} (99%) rename mri_joint_density/{mri_joint_density.c => mri_joint_density.cpp} (98%) rename mri_label2label/{mri_label2label.c => mri_label2label.cpp} (100%) rename mri_label2vol/{mri_label2vol.c => mri_label2vol.cpp} (100%) rename mri_label_accuracy/{mri_label_accuracy.c => mri_label_accuracy.cpp} (100%) rename mri_label_histo/{mri_label_histo.c => mri_label_histo.cpp} (98%) rename mri_label_vals/{mri_label_vals.c => mri_label_vals.cpp} (99%) rename mri_label_volume/{mri_label_volume.c => mri_label_volume.cpp} (99%) rename mri_linear_register/{mri_linear_register.c => mri_linear_register.cpp} (99%) rename mri_log_likelihood/{mri_log_likelihood.c => mri_log_likelihood.cpp} (100%) rename mri_make_bem_surfaces/{mri_make_bem_surfaces.c => mri_make_bem_surfaces.cpp} (100%) rename mri_make_density_map/{mri_make_density_map.c => mri_make_density_map.cpp} (100%) rename mri_make_labels/{mri_make_labels.c => mri_make_labels.cpp} (100%) rename mri_make_register/{mri_make_register.c => mri_make_register.cpp} (99%) rename mri_make_template/{mri_make_template.c => mri_make_template.cpp} (100%) rename mri_mark_temporal_lobe/{mri_mark_temporal_lobe.c => mri_mark_temporal_lobe.cpp} (99%) rename mri_mask/{mri_mask.c => mri_mask.cpp} (100%) rename mri_matrix_multiply/{mri_matrix_multiply.c => mri_matrix_multiply.cpp} (100%) rename mri_mc/{build_MC_table.c => build_MC_table.cpp} (100%) rename mri_mc/{build_test_volume.c => build_test_volume.cpp} (100%) rename mri_mc/{mri_mc.c => mri_mc.cpp} (100%) rename mri_mc/{mri_pretess.c => mri_pretess.cpp} (100%) rename mri_mc/{mris_extract_main_component.c => mris_extract_main_component.cpp} (100%) rename mri_mcsim/{mri_mcsim.c => mri_mcsim.cpp} (99%) rename mri_mi/{mri_mi.c => mri_mi.cpp} (99%) rename mri_morphology/{mri_morphology.c => mri_morphology.cpp} (99%) rename mri_mosaic/{mri_mosaic.c => mri_mosaic.cpp} (98%) rename mri_ms_EM/{PoissonSolver.c => PoissonSolver.cpp} (100%) rename mri_ms_EM/{mri_ms_EM.c => mri_ms_EM.cpp} (99%) rename mri_ms_EM/{myutils.c => myutils.cpp} (100%) rename mri_ms_EM_with_atlas/{PoissonSolver.c => PoissonSolver.cpp} (100%) rename mri_ms_EM_with_atlas/{mri_ms_EM_with_atlas.c => mri_ms_EM_with_atlas.cpp} (99%) rename mri_ms_EM_with_atlas/{myutils.c => myutils.cpp} (100%) rename mri_ms_EM_with_atlas/{subroutines.c => subroutines.cpp} (100%) rename mri_ms_LDA/{mri_ms_LDA.c => mri_ms_LDA.cpp} (99%) rename mri_ms_fitparms/{mri_ms_fitparms.c => mri_ms_fitparms.cpp} (99%) rename mri_multiscale_segment/{mri_multiscale_segment.c => mri_multiscale_segment.cpp} (99%) rename mri_multispectral_segment/{mri_multispectral_segment.c => mri_multispectral_segment.cpp} (100%) rename mri_nlfilter/{mri_nlfilter.c => mri_nlfilter.cpp} (100%) rename mri_normalize/{mri_long_normalize.c => mri_long_normalize.cpp} (100%) rename mri_normalize/{mri_normalize.c => mri_normalize.cpp} (99%) rename mri_normalize_tp2/{mri_normalize_tp2.c => mri_normalize_tp2.cpp} (100%) rename mri_otl/{list_otl_labels.c => list_otl_labels.cpp} (100%) rename mri_paint/{mri_paint.c => mri_paint.cpp} (100%) rename mri_parse_sdcmdir/{mri_parse_sdcmdir.c => mri_parse_sdcmdir.cpp} (100%) rename mri_partial_ribbon/{mri_partial_ribbon.c => mri_partial_ribbon.cpp} (98%) rename mri_path2label/{mri_path2label.c => mri_path2label.cpp} (99%) rename mri_polv/{mri_polv.c => mri_polv.cpp} (100%) rename mri_probe_ima/{mri_probe_ima.c => mri_probe_ima.cpp} (99%) rename mri_probedicom/{mri_probedicom.c => mri_probedicom.cpp} (100%) rename mri_reduce/{mri_reduce.c => mri_reduce.cpp} (100%) rename mri_register/{mri_register.c => mri_register.cpp} (99%) rename mri_relabel_hypointensities/{mri_relabel_hypointensities.c => mri_relabel_hypointensities.cpp} (100%) rename mri_relabel_nonwm_hypos/{mri_relabel_nonwm_hypos.c => mri_relabel_nonwm_hypos.cpp} (100%) rename mri_remove_neck/{mri_remove_neck.c => mri_remove_neck.cpp} (99%) rename mri_rf_label/{mri_rf_label.c => mri_rf_label.cpp} (99%) rename mri_rf_long_label/{mri_rf_long_label.c => mri_rf_long_label.cpp} (99%) rename mri_rf_long_train/{mri_rf_long_train.c => mri_rf_long_train.cpp} (99%) rename mri_rf_train/{mri_rf_train.c => mri_rf_train.cpp} (99%) rename mri_ribbon/{mri_ribbon.c => mri_ribbon.cpp} (100%) rename mri_rigid_register/{mri_rigid_register.c => mri_rigid_register.cpp} (99%) rename mri_sbbr/{mri_sbbr.c => mri_sbbr.cpp} (98%) rename mri_seg_diff/{mri_seg_diff.c => mri_seg_diff.cpp} (100%) rename mri_seghead/{mri_seghead.c => mri_seghead.cpp} (100%) rename mri_segment/{mri_segment.c => mri_segment.cpp} (99%) rename mri_segment_tumor/{mri_segment_tumor.c => mri_segment_tumor.cpp} (99%) rename mri_segment_wm_damage/{mri_segment_wm_damage.c => mri_segment_wm_damage.cpp} (99%) rename mri_segreg/{mri_segreg.c => mri_segreg.cpp} (99%) rename mri_segstats/{mri_segstats.c => mri_segstats.cpp} (100%) rename mri_simulate_atrophy/{mri_simulate_atrophy.c => mri_simulate_atrophy.cpp} (99%) rename mri_stats2seg/{mri_stats2seg.c => mri_stats2seg.cpp} (99%) rename mri_strip_nonwhite/{mri_strip_nonwhite.c => mri_strip_nonwhite.cpp} (99%) rename mri_strip_subject_info/{mri_strip_subject_info.c => mri_strip_subject_info.cpp} (100%) rename mri_surf2surf/{mri_surf2surf.c => mri_surf2surf.cpp} (100%) rename mri_surf2vol/{mri_surf2vol.c => mri_surf2vol.cpp} (100%) rename mri_surfcluster/{mri_surfcluster.c => mri_surfcluster.cpp} (100%) rename mri_synthesize/{mri_synthesize.c => mri_synthesize.cpp} (100%) rename mri_tessellate/{ico_supersample.c => ico_supersample.cpp} (100%) rename mri_tessellate/{mri_tessellate.c => mri_tessellate.cpp} (99%) rename mri_threshold/{mri_threshold.c => mri_threshold.cpp} (100%) rename mri_topologycorrection/{mri_topologycorrection.c => mri_topologycorrection.cpp} (100%) rename mri_train/{mri_train.c => mri_train.cpp} (98%) rename mri_train_autoencoder/{mri_apply_autoencoder.c => mri_apply_autoencoder.cpp} (99%) rename mri_train_autoencoder/{mri_train_autoencoder.c => mri_train_autoencoder.cpp} (99%) rename mri_transform/{mri_transform.c => mri_transform.cpp} (100%) rename mri_transform_to_COR/{mri_transform_to_COR.c => mri_transform_to_COR.cpp} (100%) rename mri_twoclass/{mri_twoclass.c => mri_twoclass.cpp} (99%) rename mri_update_gca/{mri_update_gca.c => mri_update_gca.cpp} (97%) rename mri_vol2roi/{mri_vol2roi.c => mri_vol2roi.cpp} (99%) rename mri_vol2surf/{mri_vol2surf.c => mri_vol2surf.cpp} (100%) rename mri_vol2vol/{mri_vol2vol.c => mri_vol2vol.cpp} (99%) rename mri_volcluster/{mri_volcluster.c => mri_volcluster.cpp} (100%) rename mri_voldiff/{mri_voldiff.c => mri_voldiff.cpp} (100%) rename mri_volsynth/{mri_volsynth.c => mri_volsynth.cpp} (100%) rename mri_wbc/{mri_wbc.c => mri_wbc.cpp} (99%) rename mri_wmfilter/{mri_wmfilter.c => mri_wmfilter.cpp} (100%) rename mri_xcorr/{mri_xcorr.c => mri_xcorr.cpp} (100%) rename mri_xvolavg/{mri_xvolavg.c => mri_xvolavg.cpp} (100%) rename mri_z2p/{mri_z2p.c => mri_z2p.cpp} (100%) rename mris2rgb/{mris2rgb.c => mris2rgb.cpp} (99%) rename mris2rgb/{oglutil.c => oglutil.cpp} (100%) rename mris2rgb/{texfont.c => texfont.cpp} (100%) rename mris_BA_segment/{mris_BA_segment.c => mris_BA_segment.cpp} (100%) rename mris_add_template/{mris_add_template.c => mris_add_template.cpp} (100%) rename mris_anatomical_stats/{mris_anatomical_stats.c => mris_anatomical_stats.cpp} (100%) rename mris_annot_to_segmentation/{mris_annot_to_segmentation.c => mris_annot_to_segmentation.cpp} (99%) rename mris_apply_reg/{mris_apply_reg.c => mris_apply_reg.cpp} (100%) rename mris_aseg_distance/{mris_aseg_distance.c => mris_aseg_distance.cpp} (100%) rename mris_average_curvature/{mris_average_curvature.c => mris_average_curvature.cpp} (100%) rename mris_average_parcellation/{mris_average_parcellation.c => mris_average_parcellation.cpp} (98%) rename mris_ca_label/{mris_ca_label.c => mris_ca_label.cpp} (99%) rename mris_ca_train/{mris_ca_train.c => mris_ca_train.cpp} (99%) rename mris_calc/{mris_calc.c => mris_calc.cpp} (99%) rename mris_classify_thickness/{mris_classify_thickness.c => mris_classify_thickness.cpp} (97%) rename mris_compute_acorr/{mris_compute_acorr.c => mris_compute_acorr.cpp} (100%) rename mris_compute_optimal_kernel/{mris_compute_optimal_kernel.c => mris_compute_optimal_kernel.cpp} (100%) rename mris_compute_overlap/{mris_compute_overlap.c => mris_compute_overlap.cpp} (97%) rename mris_compute_parc_overlap/{mris_compute_parc_overlap.c => mris_compute_parc_overlap.cpp} (99%) rename mris_compute_volume_fractions/{mris_compute_volume_fractions.c => mris_compute_volume_fractions.cpp} (100%) rename mris_compute_volume_fractions/{myown.c => myown.cpp} (100%) rename mris_congeal/{mris_congeal.c => mris_congeal.cpp} (99%) rename mris_convert/{mris_convert.c => mris_convert.cpp} (99%) rename mris_copy_header/{mris_copy_header.c => mris_copy_header.cpp} (100%) rename mris_curvature/{mris_curvature.c => mris_curvature.cpp} (100%) rename mris_curvature_stats/{mris_curvature_stats.c => mris_curvature_stats.cpp} (99%) rename mris_deform/{mris_ca_deform.c => mris_ca_deform.cpp} (99%) rename mris_deform/{mris_deform.c => mris_deform.cpp} (99%) rename mris_deform/{mris_nudge.c => mris_nudge.cpp} (100%) rename mris_density/{mris_density.c => mris_density.cpp} (100%) rename mris_diff/{mris_diff.c => mris_diff.cpp} (100%) rename mris_distance_map/{mris_distance_map.c => mris_distance_map.cpp} (100%) rename mris_distance_transform/{mris_distance_transform.c => mris_distance_transform.cpp} (99%) rename mris_divide_parcellation/{mris_divide_parcellation.c => mris_divide_parcellation.cpp} (100%) rename mris_entropy/{mris_entropy.c => mris_entropy.cpp} (100%) rename mris_errors/{mris_errors.c => mris_errors.cpp} (100%) rename mris_euler_number/{mris_euler_number.c => mris_euler_number.cpp} (100%) rename mris_expand/{mris_expand.c => mris_expand.cpp} (99%) rename mris_extract_patches/{mris_extract_patches.c => mris_extract_patches.cpp} (99%) rename mris_fbirn_annot/{mris_fbirn_annot.c => mris_fbirn_annot.cpp} (100%) rename mris_fill/{mris_fill.c => mris_fill.cpp} (98%) rename mris_find_flat_regions/{mris_find_flat_regions.c => mris_find_flat_regions.cpp} (100%) rename mris_fix_topology/{mris_fix_topology.c => mris_fix_topology.cpp} (99%) rename mris_fix_topology/{mris_remove_intersection.c => mris_remove_intersection.cpp} (98%) rename mris_flatten/{mris_flatten.c => mris_flatten.cpp} (100%) rename mris_fwhm/{mris_fwhm.c => mris_fwhm.cpp} (99%) rename mris_glm/{mris_glm.c => mris_glm.cpp} (100%) rename mris_hausdorff_dist/{mris_hausdorff_dist.c => mris_hausdorff_dist.cpp} (99%) rename mris_inflate/{mris_inflate.c => mris_inflate.cpp} (99%) rename mris_init_global_tractography/{mris_init_global_tractography.c => mris_init_global_tractography.cpp} (99%) rename mris_interpolate_warp/{mris_interpolate_warp.c => mris_interpolate_warp.cpp} (99%) rename mris_jacobian/{mris_jacobian.c => mris_jacobian.cpp} (100%) rename mris_label2annot/{mris_label2annot.c => mris_label2annot.cpp} (100%) rename mris_label_area/{mris_label_area.c => mris_label_area.cpp} (98%) rename mris_label_mode/{mris_label_mode.c => mris_label_mode.cpp} (100%) rename mris_left_right_register/{mris_left_right_register.c => mris_left_right_register.cpp} (99%) rename mris_longitudinal_surfaces/{mris_longitudinal_surfaces.c => mris_longitudinal_surfaces.cpp} (99%) rename mris_make_average_surface/{mris_make_average_surface.c => mris_make_average_surface.cpp} (100%) rename mris_make_face_parcellation/{mris_make_face_parcellation.c => mris_make_face_parcellation.cpp} (99%) rename mris_make_map_surfaces/{mris_make_map_surfaces.c => mris_make_map_surfaces.cpp} (100%) rename mris_make_surfaces/{mris_exvivo_surfaces.c => mris_exvivo_surfaces.cpp} (99%) rename mris_make_surfaces/{mris_make_surfaces.c => mris_make_surfaces.cpp} (99%) rename mris_make_surfaces/{mris_mef_surfaces.c => mris_mef_surfaces.cpp} (99%) rename mris_make_surfaces/{mris_refine_surfaces.c => mris_refine_surfaces.cpp} (99%) rename mris_make_template/{mris_make_template.c => mris_make_template.cpp} (99%) rename mris_map_cuts/{mris_map_cuts.c => mris_map_cuts.cpp} (99%) rename mris_merge_parcellations/{mris_merge_parcellations.c => mris_merge_parcellations.cpp} (99%) rename mris_morph_stats/{mris_morph_stats.c => mris_morph_stats.cpp} (100%) rename mris_ms_refine/{mris_ms_refine.c => mris_ms_refine.cpp} (99%) rename mris_ms_surface_CNR/{mris_ms_surface_CNR.c => mris_ms_surface_CNR.cpp} (99%) rename mris_multiscale_stats/{mris_multiscale_stats.c => mris_multiscale_stats.cpp} (99%) rename mris_niters2fwhm/{mris_niters2fwhm.c => mris_niters2fwhm.cpp} (100%) rename mris_parcellate_connectivity/{mris_parcellate_connectivity.c => mris_parcellate_connectivity.cpp} (99%) rename mris_pmake/{abs2rel.c => abs2rel.cpp} (100%) rename mris_pmake/{rel2abs.c => rel2abs.cpp} (100%) rename mris_register/{mris_register.c => mris_register.cpp} (99%) rename mris_register_label_map/{mris_register_label_map.c => mris_register_label_map.cpp} (100%) rename mris_register_to_volume/{mris_register_to_label.c => mris_register_to_label.cpp} (99%) rename mris_register_to_volume/{mris_register_to_volume.c => mris_register_to_volume.cpp} (99%) rename mris_remove_variance/{mris_remove_variance.c => mris_remove_variance.cpp} (100%) rename mris_rescale/{mris_rescale.c => mris_rescale.cpp} (100%) rename mris_reverse/{mris_reverse.c => mris_reverse.cpp} (100%) rename mris_rf_label/{mris_rf_label.c => mris_rf_label.cpp} (95%) rename mris_rf_train/{mris_rf_train.c => mris_rf_train.cpp} (99%) rename mris_rotate/{mris_rotate.c => mris_rotate.cpp} (100%) rename mris_sample_label/{mris_sample_label.c => mris_sample_label.cpp} (100%) rename mris_sample_parc/{mris_sample_parc.c => mris_sample_parc.cpp} (100%) rename mris_seg2annot/{mris_seg2annot.c => mris_seg2annot.cpp} (100%) rename mris_segment/{mris_segment.c => mris_segment.cpp} (99%) rename mris_segment_vals/{mris_segment_vals.c => mris_segment_vals.cpp} (100%) rename mris_segmentation_stats/{mris_segmentation_stats.c => mris_segmentation_stats.cpp} (98%) rename mris_shrinkwrap/{mris_AA_shrinkwrap.c => mris_AA_shrinkwrap.cpp} (99%) rename mris_shrinkwrap/{mris_shrinkwrap.c => mris_shrinkwrap.cpp} (99%) rename mris_simulate_atrophy/{mris_simulate_atrophy.c => mris_simulate_atrophy.cpp} (99%) rename mris_smooth/{mris_smooth.c => mris_smooth.cpp} (100%) rename mris_sphere/{mris_remove_negative_vertices.c => mris_remove_negative_vertices.cpp} (98%) rename mris_sphere/{mris_sphere.c => mris_sphere.cpp} (99%) rename mris_spherical_average/{mris_spherical_average.c => mris_spherical_average.cpp} (100%) rename mris_surface_change/{mris_surface_change.c => mris_surface_change.cpp} (100%) rename mris_surface_stats/{mris_surface_stats.c => mris_surface_stats.cpp} (99%) rename mris_surface_to_vol_distances/{mris_surface_to_vol_distances.c => mris_surface_to_vol_distances.cpp} (99%) rename mris_svm_classify/{mris_svm_classify.c => mris_svm_classify.cpp} (99%) rename mris_svm_train/{mris_svm_train.c => mris_svm_train.cpp} (99%) rename mris_talairach/{mris_talairach.c => mris_talairach.cpp} (100%) rename mris_thickness/{mris_cluster_profiles.c => mris_cluster_profiles.cpp} (100%) rename mris_thickness/{mris_gradient.c => mris_gradient.cpp} (100%) rename mris_thickness/{mris_intensity_profile.c => mris_intensity_profile.cpp} (100%) rename mris_thickness/{mris_thickness.c => mris_thickness.cpp} (99%) rename mris_thickness_comparison/{mris_thickness_comparison.c => mris_thickness_comparison.cpp} (100%) rename mris_thickness_diff/{mris_thickness_diff.c => mris_thickness_diff.cpp} (99%) rename {utilscpp => mris_topo_fixer}/face.cpp (97%) rename {include/topology => mris_topo_fixer}/face.h (97%) rename {utilscpp => mris_topo_fixer}/fastloop.cpp (99%) rename {include/topology => mris_topo_fixer}/fastloop.h (99%) rename {utilscpp => mris_topo_fixer}/globals.cpp (72%) rename {include/topology => mris_topo_fixer}/globals.h (98%) rename {utilscpp => mris_topo_fixer}/loop.cpp (98%) rename {include/topology => mris_topo_fixer}/loop.h (97%) rename {utilscpp => mris_topo_fixer}/mris_topology.cpp (98%) rename {include => mris_topo_fixer}/mris_topology.h (89%) rename {utilscpp => mris_topo_fixer}/patchdisk.cpp (99%) rename {include/topology => mris_topo_fixer}/patchdisk.h (97%) rename {utilscpp => mris_topo_fixer}/segment.cpp (98%) rename {include/topology => mris_topo_fixer}/segment.h (97%) rename {utilscpp => mris_topo_fixer}/surface.cpp (99%) rename {include/topology => mris_topo_fixer}/surface.h (99%) rename {utilscpp => mris_topo_fixer}/vertex.cpp (98%) rename {include/topology => mris_topo_fixer}/vertex.h (99%) rename mris_transform/{mris_transform.c => mris_transform.cpp} (100%) rename mris_translate_annotation/{mris_translate_annotation.c => mris_translate_annotation.cpp} (100%) rename mris_transmantle_dysplasia_paths/{mris_transmantle_dysplasia_paths.c => mris_transmantle_dysplasia_paths.cpp} (99%) rename mris_twoclass/{mris_twoclass.c => mris_twoclass.cpp} (99%) rename mris_volume/{mris_volume.c => mris_volume.cpp} (98%) rename mris_volume/{mris_wm_volume.c => mris_wm_volume.cpp} (98%) rename mris_w_to_curv/{mris_w_to_curv.c => mris_w_to_curv.cpp} (100%) rename mris_warp/{mris_warp.c => mris_warp.cpp} (99%) rename mris_watershed/{mris_watershed.c => mris_watershed.cpp} (100%) rename mrisp_paint/{mrisp_paint.c => mrisp_paint.cpp} (100%) rename mrisp_write/{mrisp_write.c => mrisp_write.cpp} (100%) rename oct_register_mosaic/{oct_register_mosaic.c => oct_register_mosaic.cpp} (99%) rename oct_train/{oct_rf_train.c => oct_rf_train.cpp} (99%) rename oct_train/{oct_train.c => oct_train.cpp} (99%) rename optseq2/{optseq2.c => optseq2.cpp} (99%) create mode 100644 packages/CMakeLists.txt create mode 100644 packages/cephes/CMakeLists.txt rename {utils => packages}/cephes/bdtr.c (100%) rename {include => packages/cephes}/cephes.h (100%) rename {utils => packages}/cephes/chdtr.c (100%) rename {utils => packages}/cephes/const.c (100%) rename {utils => packages}/cephes/fdtr.c (100%) rename {utils => packages}/cephes/gamma.c (100%) rename {utils => packages}/cephes/igam.c (100%) rename {utils => packages}/cephes/igami.c (100%) rename {utils => packages}/cephes/incbet.c (100%) rename {utils => packages}/cephes/incbi.c (100%) rename {include => packages/cephes}/mconf.h (98%) rename {utils => packages}/cephes/mtherr.c (100%) rename {utils => packages}/cephes/ndtr.c (100%) rename {utils => packages}/cephes/ndtri.c (100%) rename {utils => packages}/cephes/polevl.c (100%) rename {utils => packages}/cephes/stdtr.c (100%) create mode 100644 packages/dicom/CMakeLists.txt rename {dicom => packages/dicom}/condition.c (100%) rename {include => packages}/dicom/condition.h (100%) rename {include => packages}/dicom/ctn_os.h (100%) rename {dicom => packages/dicom}/ctnthread.c (100%) rename {include => packages}/dicom/ctnthread.h (100%) rename {dicom => packages/dicom}/dcm.c (100%) rename {dicom => packages/dicom}/dcmcond.c (100%) rename {dicom => packages/dicom}/dcmdict.c (100%) rename {include => packages}/dicom/dcmprivate.h (100%) rename {dicom => packages/dicom}/dcmsupport.c (100%) rename {include => packages}/dicom/dicom.h (100%) rename {include => packages}/dicom/dicom_objects.h (100%) rename {include => packages}/dicom/dicom_platform.h (87%) rename {include => packages}/dicom/dicom_uids.h (100%) rename {dicom => packages/dicom}/lst.c (100%) rename {include => packages}/dicom/lst.h (100%) rename {include => packages}/dicom/lstprivate.h (100%) create mode 100644 packages/gifti/CMakeLists.txt rename {utils => packages/gifti}/gifti_io.c (100%) rename {include => packages/gifti}/gifti_io.h (99%) rename {utils => packages/gifti}/gifti_tool.c (100%) rename {utils => packages/gifti}/gifti_tool.h (100%) rename {utils => packages/gifti}/gifti_xml.c (99%) rename {include => packages/gifti}/gifti_xml.h (100%) create mode 100644 packages/minc/minc.h rename {include => packages/minc}/minc_multidim_arrays.h (99%) rename {include => packages/minc}/minc_structures.h (100%) rename {include => packages/minc}/minc_volume_io.h (92%) create mode 100644 packages/nifti/CMakeLists.txt rename {include => packages/nifti}/nifti1.h (100%) rename {utils => packages/nifti}/nifti1_io.c (100%) rename {include => packages/nifti}/nifti1_io.h (100%) rename {utils => packages/nifti}/znzlib.c (100%) rename {include => packages/nifti}/znzlib.h (100%) rename {utils/NrrdIO => packages/nrrdio}/754.c (100%) create mode 100644 packages/nrrdio/CMakeLists.txt rename {include/NrrdIO => packages/nrrdio}/NrrdIO.h (99%) rename {utils/NrrdIO => packages/nrrdio}/accessors.c (100%) rename {utils/NrrdIO => packages/nrrdio}/array.c (100%) rename {utils/NrrdIO => packages/nrrdio}/arraysNrrd.c (100%) rename {utils/NrrdIO => packages/nrrdio}/axis.c (100%) rename {utils/NrrdIO => packages/nrrdio}/biffbiff.c (100%) rename {utils/NrrdIO => packages/nrrdio}/comment.c (100%) rename {utils/NrrdIO => packages/nrrdio}/copyright.NrrdIO (100%) rename {utils/NrrdIO => packages/nrrdio}/defaultsNrrd.c (100%) rename {utils/NrrdIO => packages/nrrdio}/dio.c (100%) rename {utils/NrrdIO => packages/nrrdio}/encoding.c (100%) rename {utils/NrrdIO => packages/nrrdio}/encodingAscii.c (100%) rename {utils/NrrdIO => packages/nrrdio}/encodingBzip2.c (100%) rename {utils/NrrdIO => packages/nrrdio}/encodingGzip.c (100%) rename {utils/NrrdIO => packages/nrrdio}/encodingHex.c (100%) rename {utils/NrrdIO => packages/nrrdio}/encodingRaw.c (100%) rename {utils/NrrdIO => packages/nrrdio}/endianAir.c (100%) rename {utils/NrrdIO => packages/nrrdio}/endianNrrd.c (100%) rename {utils/NrrdIO => packages/nrrdio}/enum.c (100%) rename {utils/NrrdIO => packages/nrrdio}/enumsNrrd.c (100%) rename {utils/NrrdIO => packages/nrrdio}/format.c (100%) rename {utils/NrrdIO => packages/nrrdio}/formatEPS.c (100%) rename {utils/NrrdIO => packages/nrrdio}/formatNRRD.c (100%) rename {utils/NrrdIO => packages/nrrdio}/formatPNG.c (100%) rename {utils/NrrdIO => packages/nrrdio}/formatPNM.c (100%) rename {utils/NrrdIO => packages/nrrdio}/formatText.c (100%) rename {utils/NrrdIO => packages/nrrdio}/formatVTK.c (100%) rename {utils/NrrdIO => packages/nrrdio}/gzio.c (100%) rename {utils/NrrdIO => packages/nrrdio}/keyvalue.c (100%) rename {utils/NrrdIO => packages/nrrdio}/methodsNrrd.c (100%) rename {utils/NrrdIO => packages/nrrdio}/miscAir.c (100%) rename {utils/NrrdIO => packages/nrrdio}/mop.c (100%) rename {utils/NrrdIO => packages/nrrdio}/parseAir.c (100%) rename {utils/NrrdIO => packages/nrrdio}/parseNrrd.c (100%) rename {include/NrrdIO => packages/nrrdio}/privateAir.h (100%) rename {include/NrrdIO => packages/nrrdio}/privateNrrd.h (100%) rename {utils/NrrdIO => packages/nrrdio}/qnanhibit.c (100%) rename {utils/NrrdIO => packages/nrrdio}/read.c (100%) rename {utils/NrrdIO => packages/nrrdio}/reorder.c (100%) rename {utils/NrrdIO => packages/nrrdio}/sampleIO.c (100%) rename {utils/NrrdIO => packages/nrrdio}/sane.c (100%) rename {utils/NrrdIO => packages/nrrdio}/simple.c (100%) rename {utils/NrrdIO => packages/nrrdio}/string.c (100%) rename {utils/NrrdIO => packages/nrrdio}/subset.c (100%) rename {include/NrrdIO => packages/nrrdio}/teem32bit.h (100%) rename {include/NrrdIO => packages/nrrdio}/teemDio.h (100%) rename {include/NrrdIO => packages/nrrdio}/teemEndian.h (100%) rename {include/NrrdIO => packages/nrrdio}/teemPng.h (100%) rename {include/NrrdIO => packages/nrrdio}/teemQnanhibit.h (100%) rename {utils/NrrdIO => packages/nrrdio}/write.c (100%) rename {svm-lib => packages/svm}/CMakeLists.txt (52%) rename {svm-lib => packages/svm}/README.txt (100%) rename {svm-lib => packages/svm}/svm-data-param.cpp (100%) rename {svm-lib => packages/svm}/svm-data-param.h (100%) rename {svm-lib => packages/svm}/svm-element-type.h (100%) rename {svm-lib => packages/svm}/svm-element-types.h (100%) rename {svm-lib => packages/svm}/svm-io-format.h (100%) rename {svm-lib => packages/svm}/svm-kernel-param.h (100%) rename {svm-lib => packages/svm}/svm-kernel.cpp (100%) rename {svm-lib => packages/svm}/svm-kernel.h (100%) rename {svm-lib => packages/svm}/svm-lib-c.cpp (100%) rename {svm-lib => packages/svm}/svm-lib-c.h (100%) rename {svm-lib => packages/svm}/svm-lib.cpp (100%) rename {svm-lib => packages/svm}/svm-lib.h (100%) rename {svm-lib => packages/svm}/svm-matrix.h (100%) rename {svm-lib => packages/svm}/svm-model.cpp (100%) rename {svm-lib => packages/svm}/svm-model.h (100%) rename {svm-lib => packages/svm}/svm-param.cpp (100%) rename {svm-lib => packages/svm}/svm-param.h (100%) rename svm-lib/svm-pr-loqo.c => packages/svm/svm-pr-loqo.cpp (100%) rename {svm-lib => packages/svm}/svm-pr-loqo.h (100%) rename {svm-lib => packages/svm}/svm-similarity.cpp (100%) rename {svm-lib => packages/svm}/svm-similarity.h (100%) rename {svm-lib => packages/svm}/svm-sketch.cpp (100%) rename {svm-lib => packages/svm}/svm-sketch.h (100%) rename {svm-lib => packages/svm}/svm-vector-types.h (100%) rename {svm-lib => packages/svm}/svm-vector.h (100%) rename rbftest/{rbftest.c => rbftest.cpp} (85%) rename repair_siemens_file/{repair_siemens_file.c => repair_siemens_file.cpp} (97%) delete mode 100644 rgb/CMakeLists.txt delete mode 100644 rgb/close.c delete mode 100644 rgb/filbuf.c delete mode 100644 rgb/flsbuf.c delete mode 100644 rgb/name.c delete mode 100644 rgb/open.c delete mode 100644 rgb/pix.c delete mode 100644 rgb/rdwr.c delete mode 100644 rgb/rgbutils.c delete mode 100644 rgb/rle.c delete mode 100644 rgb/row.c rename spherical_stats/{spherical_stats.c => spherical_stats.cpp} (99%) rename stat_normalize/{stat_normalize.c => stat_normalize.cpp} (100%) rename stim_polar/{stim_polar.c => stim_polar.cpp} (100%) delete mode 100644 svm-lib/INSTALL_README.txt delete mode 100644 svm-lib/classification_setup.example rename talairach_afd/{talairach_afd.c => talairach_afd.cpp} (100%) rename template/{main_template.c => main_template.cpp} (97%) rename template/{mri_elastic_energy.c => mri_elastic_energy.cpp} (97%) rename template/{mri_multiscale_segment.c => mri_multiscale_segment.cpp} (99%) rename template/{template.c => template.cpp} (100%) delete mode 100644 test_exclude_minc/test_exclude_minc.c rename test_makevol/{main.c => main.cpp} (100%) delete mode 100644 tkmedit/development_notes.txt delete mode 100644 tkmedit/tkmDisplayArea.c delete mode 100644 tkmedit/tkmDisplayArea.h delete mode 100644 tkmedit/tkmFunctionalVolume.c delete mode 100644 tkmedit/tkmFunctionalVolume.h delete mode 100644 tkmedit/tkmMeditWindow.c delete mode 100644 tkmedit/tkmMeditWindow.h delete mode 100644 tkmedit/tkmedit.c delete mode 100644 tkmedit/tkmedit.h rename tkregister2/{tkregister2.c => tkregister2.cpp} (99%) delete mode 100644 tksurfer/development_notes.txt delete mode 100644 tksurfer/tksurfer.c rename tridec/{tridec.c => tridec.cpp} (100%) rename utils/{Bruker.c => Bruker.cpp} (99%) rename utils/{DICOMRead.c => DICOMRead.cpp} (99%) rename utils/{MARS_DT_Boundary.c => MARS_DT_Boundary.cpp} (100%) rename utils/{MRISrigidBodyAlignGlobal.c => MRISrigidBodyAlignGlobal.cpp} (98%) rename utils/{MRIio_old.c => MRIio_old.cpp} (92%) rename utils/{Progname.c => Progname.cpp} (100%) rename utils/{afni.c => afni.cpp} (99%) rename utils/{annotation.c => annotation.cpp} (98%) rename {utilscpp => utils}/argparse.cpp (91%) delete mode 100644 utils/art1.c delete mode 100644 utils/artmap.c delete mode 100644 utils/aseg_edit_svm.c rename utils/{autoencoder.c => autoencoder.cpp} (100%) delete mode 100644 utils/backprop.c rename utils/{bfileio.c => bfileio.cpp} (96%) rename utils/{box.c => box.cpp} (100%) rename utils/{chklc.c => chklc.cpp} (99%) rename utils/{chronometer.c => chronometer.cpp} (100%) rename utils/{class_array.c => class_array.cpp} (100%) rename utils/{cluster.c => cluster.cpp} (100%) rename utils/{cma.c => cma.cpp} (99%) rename utils/{cmat.c => cmat.cpp} (100%) rename utils/{cmdargs.c => cmdargs.cpp} (100%) rename utils/{colortab.c => colortab.cpp} (99%) rename utils/{connectcomp.c => connectcomp.cpp} (99%) rename utils/{corio.c => corio.cpp} (100%) rename utils/{ctrpoints.c => ctrpoints.cpp} (99%) rename utils/{cvector.c => cvector.cpp} (99%) delete mode 100644 utils/dcdflib.c rename utils/{dct.c => dct.cpp} (100%) rename utils/{density.c => density.cpp} (100%) rename utils/{diag.c => diag.cpp} (98%) rename utils/{diffuse.c => diffuse.cpp} (98%) rename utils/{dmatrix.c => dmatrix.cpp} (100%) rename utils/{dti.c => dti.cpp} (98%) rename utils/{dtk.fs.c => dtk.fs.cpp} (98%) rename utils/{error.c => error.cpp} (96%) rename utils/{evschutils.c => evschutils.cpp} (99%) rename utils/{fcd.c => fcd.cpp} (100%) rename utils/{fftutils.c => fftutils.cpp} (99%) rename utils/{field_code.c => field_code.cpp} (98%) rename utils/{filter.c => filter.cpp} (99%) rename utils/{fio.c => fio.cpp} (100%) rename utils/{flash.c => flash.cpp} (100%) delete mode 100644 utils/fmarchmesh.c rename utils/{fmriutils.c => fmriutils.cpp} (100%) rename utils/{fnv_hash_test.c => fnv_hash_test.cpp} (100%) rename utils/{fsPrintHelp.c => fsPrintHelp.cpp} (94%) rename utils/{fsenv.c => fsenv.cpp} (100%) rename utils/{fsgdf.c => fsgdf.cpp} (100%) rename utils/{fsglm.c => fsglm.cpp} (99%) rename utils/{fsinit.c => fsinit.cpp} (100%) rename utils/{gca.c => gca.cpp} (99%) rename utils/{gcaboundary.c => gcaboundary.cpp} (100%) rename utils/{gcamorph.c => gcamorph.cpp} (99%) delete mode 100644 utils/gcarray.c rename utils/{gclass.c => gclass.cpp} (96%) rename utils/{gcsa.c => gcsa.cpp} (99%) rename utils/{geos.c => geos.cpp} (100%) rename utils/{getdelim.c => getdelim.cpp} (100%) rename utils/{getline.c => getline.cpp} (100%) rename utils/{gifti_local.c => gifti.cpp} (99%) delete mode 100644 utils/gifti_test.c delete mode 100644 utils/gifti_test.h rename utils/{gtm.c => gtm.cpp} (98%) rename utils/{gw_ic2562.c => gw_ic2562.cpp} (100%) rename utils/{gw_utils.c => gw_utils.cpp} (99%) delete mode 100644 utils/handle.c delete mode 100644 utils/heap.c rename utils/{hippo.c => hippo.cpp} (99%) create mode 100644 utils/hips.cpp rename utils/{histo.c => histo.cpp} (99%) rename utils/{ic12.c => ic12.cpp} (100%) rename utils/{ic163842.c => ic163842.cpp} (100%) rename utils/{ic2562.c => ic2562.cpp} (100%) rename utils/{ic42.c => ic42.cpp} (100%) rename utils/{ic642.c => ic642.cpp} (100%) rename utils/{icosahedron.c => icosahedron.cpp} (100%) rename utils/{image.c => image.cpp} (98%) rename utils/{imageio.c => imageio.cpp} (93%) rename utils/{imautils.c => imautils.cpp} (99%) rename utils/{intensity_eig.c => intensity_eig.cpp} (100%) rename utils/{ipmpar.c => ipmpar.cpp} (100%) rename utils/{joint_histo.c => joint_histo.cpp} (100%) rename utils/{kernel.c => kernel.cpp} (99%) delete mode 100644 utils/kinput.c rename utils/{label.c => label.cpp} (98%) create mode 100644 utils/log.cpp delete mode 100644 utils/lpafile.c rename {utilscpp => utils}/lut.cpp (98%) rename utils/{machine.c => machine.cpp} (100%) rename utils/{matfile.c => matfile.cpp} (99%) rename utils/{matrix.c => matrix.cpp} (99%) rename utils/{mgh_filter.c => mgh_filter.cpp} (100%) rename utils/{mgh_malloc.c => mgh_malloc.cpp} (100%) delete mode 100644 utils/mgh_matrix.c rename utils/{min_heap.c => min_heap.cpp} (100%) delete mode 100644 utils/mincutils.c delete mode 100644 utils/minmaxrc.c rename utils/{morph.c => morph.cpp} (99%) rename utils/{mosaic.c => mosaic.cpp} (100%) rename utils/{mri.c => mri.cpp} (99%) rename utils/{mri2.c => mri2.cpp} (99%) rename utils/{mriBSpline.c => mriBSpline.cpp} (99%) delete mode 100644 utils/mriFunctionalDataAccess.c delete mode 100644 utils/mriHeadPointList.c delete mode 100644 utils/mriSurface.c rename utils/{mriTransform.c => mriTransform.cpp} (68%) delete mode 100644 utils/mriVolume.c rename utils/{mri_conform.c => mri_conform.cpp} (87%) rename utils/{mri_identify.c => mri_identify.cpp} (98%) rename utils/{mri_level_set.c => mri_level_set.cpp} (100%) rename utils/{mri_tess.c => mri_tess.cpp} (100%) rename utils/{mri_topology.c => mri_topology.cpp} (100%) delete mode 100644 utils/mri_transform.c rename utils/{mriclass.c => mriclass.cpp} (97%) rename utils/{mricurv.c => mricurv.cpp} (100%) rename utils/{mrifilter.c => mrifilter.cpp} (99%) rename utils/{mriflood.c => mriflood.cpp} (99%) rename utils/{mrihisto.c => mrihisto.cpp} (99%) rename utils/{mriio.c => mriio.cpp} (98%) delete mode 100644 utils/mriio_nrrd.c delete mode 100644 utils/mriio_nrrd_itk.cpp rename utils/{mrimorph.c => mrimorph.cpp} (99%) rename utils/{mrinorm.c => mrinorm.cpp} (96%) rename utils/{mripolv.c => mripolv.cpp} (99%) rename utils/{mriprob.c => mriprob.cpp} (100%) rename utils/{mris_compVolFrac.c => mris_compVolFrac.cpp} (100%) rename {utilscpp => utils}/mris_fastmarching.cpp (71%) delete mode 100644 utils/mrisbiorthogonalwavelets.c rename utils/{mrisegment.c => mrisegment.cpp} (100%) rename utils/{mriset.c => mriset.cpp} (99%) rename utils/{mrishash.c => mrishash.cpp} (99%) rename utils/{mrisp.c => mrisp.cpp} (99%) rename utils/{mrisurf.c => mrisurf.cpp} (99%) rename utils/{mrisurf_base.c => mrisurf_base.cpp} (98%) rename utils/{mrisurf_defect.c => mrisurf_defect.cpp} (99%) rename utils/{mrisurf_deform.c => mrisurf_deform.cpp} (99%) rename utils/{mrisurf_integrate.c => mrisurf_integrate.cpp} (99%) rename utils/{mrisurf_io.c => mrisurf_io.cpp} (99%) rename utils/{mrisurf_metricProperties.c => mrisurf_metricProperties.cpp} (99%) rename utils/{mrisurf_mri.c => mrisurf_mri.cpp} (99%) rename utils/{mrisurf_obsolete.c => mrisurf_obsolete.cpp} (99%) rename utils/{mrisurf_timeStep.c => mrisurf_timeStep.cpp} (99%) rename utils/{mrisurf_topology.c => mrisurf_topology.cpp} (99%) rename utils/{mrisurf_vals.c => mrisurf_vals.cpp} (100%) rename utils/{mrisutils.c => mrisutils.cpp} (99%) rename utils/{mrivoxel.c => mrivoxel.cpp} (99%) rename utils/{offset.c => offset.cpp} (99%) rename utils/{path.c => path.cpp} (99%) rename utils/{pdf.c => pdf.cpp} (100%) rename utils/{pgmstubs.c => pgmstubs.cpp} (100%) rename {utilscpp => utils}/pointset.cpp (91%) rename utils/{prime.c => prime.cpp} (100%) delete mode 100644 utils/queue.c rename utils/{randomfields.c => randomfields.cpp} (100%) rename utils/{rbf.c => rbf.cpp} (95%) rename utils/{rbm.c => rbm.cpp} (100%) rename utils/{realm.c => realm.cpp} (99%) delete mode 100644 utils/rec.c rename utils/{region.c => region.cpp} (100%) rename utils/{registerio.c => registerio.cpp} (99%) rename utils/{resample.c => resample.cpp} (99%) delete mode 100644 utils/rescale.c rename utils/{retinotopy.c => retinotopy.cpp} (100%) rename utils/{rfa.c => rfa.cpp} (99%) rename utils/{rforest.c => rforest.cpp} (99%) rename utils/{rfutils.c => rfutils.cpp} (100%) create mode 100644 utils/rgb.cpp rename utils/{romp_support.c => romp_support.cpp} (82%) rename utils/{selxavgio.c => selxavgio.cpp} (100%) rename utils/{sig.c => sig.cpp} (100%) rename utils/{signa.c => signa.cpp} (100%) rename utils/{sort.c => sort.cpp} (100%) rename utils/{stats.c => stats.cpp} (99%) delete mode 100644 utils/stc.c rename utils/{surfcluster.c => surfcluster.cpp} (99%) rename utils/{surfgrad.c => surfgrad.cpp} (100%) rename utils/{svm.c => svm.cpp} (100%) rename utils/{tags.c => tags.cpp} (99%) rename utils/{talairachex.c => talairachex.cpp} (100%) delete mode 100644 utils/test/sse_mathfun_test.c delete mode 100644 utils/thread.c delete mode 100644 utils/timer.c create mode 100644 utils/timer.cpp rename utils/{transform.c => transform.cpp} (99%) rename utils/{tritri.c => tritri.cpp} (100%) rename utils/{tukey.c => tukey.cpp} (100%) rename utils/{utils.c => utils.cpp} (99%) rename utils/{version.c => version.cpp} (98%) rename utils/{vertexRotator.c => vertexRotator.cpp} (98%) rename utils/{vlabels.c => vlabels.cpp} (100%) rename utils/{volcluster.c => volcluster.cpp} (100%) rename utils/{voxlist.c => voxlist.cpp} (100%) delete mode 100644 utils/x3DList.c rename utils/{xDebug.c => xDebug.cpp} (99%) delete mode 100644 utils/xGLutWindow.c delete mode 100644 utils/xGrowableArray.c delete mode 100644 utils/xList.c delete mode 100644 utils/xSparseVolume.c rename utils/{xTypes.c => xTypes.cpp} (100%) delete mode 100644 utils/xUndoList.c delete mode 100644 utils/xUtilities.c delete mode 100644 utils/xVoxel.c create mode 100644 utils/xVoxel.cpp rename utils/{xmlToHtml.c => xmlToHtml.cpp} (100%) delete mode 100644 utilscpp/CMakeLists.txt delete mode 100644 utilscpp/log.cpp delete mode 100644 utilscpp/test/ctest.c delete mode 100644 vtkfsio/CMakeLists.txt delete mode 100644 vtkfsio/lh.vtkFSSurfaceWriterTestFile delete mode 100644 vtkfsio/vtkFSSurfaceLabelSource.cxx delete mode 100644 vtkfsio/vtkFSSurfaceLabelSource.h delete mode 100644 vtkfsio/vtkFSSurfaceScalarsReader.cxx delete mode 100644 vtkfsio/vtkFSSurfaceScalarsReader.h delete mode 100644 vtkfsio/vtkFSSurfaceSource.cxx delete mode 100644 vtkfsio/vtkFSSurfaceSource.h delete mode 100644 vtkfsio/vtkFSSurfaceWriter.cxx delete mode 100644 vtkfsio/vtkFSSurfaceWriter.h delete mode 100644 vtkfsio/vtkFSSurfaceWriterTester.cxx delete mode 100644 vtkfsio/vtkFSVolumeSource.cxx delete mode 100644 vtkfsio/vtkFSVolumeSource.h diff --git a/CMakeLists.txt b/CMakeLists.txt index bad8959771a..76695a13b54 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -# before starting the project, set gcc/g++ as default +# before starting the project, set gcc/g++ as the default compiler find_program(CMAKE_C_COMPILER NAMES $ENV{CC} gcc PATHS ENV PATH NO_DEFAULT_PATH) find_program(CMAKE_CXX_COMPILER NAMES $ENV{CXX} g++ PATHS ENV PATH NO_DEFAULT_PATH) @@ -9,9 +9,10 @@ enable_language(C CXX Fortran) # a few build options option(MINIMAL "Only build core components" OFF) -option(BUILD_GUIS "Build GUIs" ON) +option(BUILD_GUIS "Build GUI tools" ON) option(USE_OPENCL "Build OpenCL algorithms" OFF) option(INFANT_MODULE "Include infant recon-all" OFF) +option(SUPPRESS_WARNINGS "Suppress some selected warnings" ON) if(NOT APPLE) # linux-only build options @@ -26,17 +27,11 @@ include(cmake/functions.cmake) include(TestBigEndian) include(CheckFunctionExists) -# prevents itk from importing as a system +# prevent third-party packages from importing as a system set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE) -# xxd is used to generate the helptext headers - make sure it exists -find_program(XXD xxd) -if(NOT XXD) - message(FATAL_ERROR "The xxd program is required to build freesurfer") -endif() - -# allow reading installation dir from environment var, but if not defined, -# then override default install dir /usr/local (too messy to install there) +# if an install prefix is not provided, check the FS_INSTALL_DIR env var, and +# if that is not defined, set the default path to /usr/local/freesurfer if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) if(NOT "$ENV{FS_INSTALL_DIR}" STREQUAL "") set(CMAKE_INSTALL_PREFIX "$ENV{FS_INSTALL_DIR}" CACHE PATH "Copied from FS_INSTALL_DIR env variable" FORCE) @@ -59,11 +54,16 @@ if(NOT FS_BUILD_STAMP) set(FS_BUILD_STAMP "freesurfer") endif() install(CODE "file(WRITE ${CMAKE_INSTALL_PREFIX}/build-stamp.txt ${FS_BUILD_STAMP}\\n)") - # -------------------------------------------------- -# library dependencies and third-party packages +# external dependencies # -------------------------------------------------- +# xxd is used to generate the helptext headers +find_program(XXD xxd) +if(NOT XXD) + message(FATAL_ERROR "The xxd program is required to build freesurfer") +endif() + # Most of the packages required by freesurfer are located by custom find-modules stored in the # 'cmake' subdir. The find-modules expect each package to be installed under a common # path defined by FS_PACKAGES_DIR. On Martinos machines, this variable automatically defaults @@ -104,17 +104,13 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") find_package(ZLIB REQUIRED) add_definitions(-DHAVE_ZLIB) +# -------- gfortran/blas/lapack -------- if(NOT APPLE) - - # -------- gfortran -------- find_library(GFORTRAN_LIBRARIES HINTS /usr/lib/gcc/x86_64-linux-gnu/4.8 /usr/lib/gcc/x86_64-redhat-linux/4.8.2/ NAMES libgfortran.a gfortran) - - # -------- blas and lapack -------- find_library(BLAS_LIBRARIES NAMES libblas.a) find_library(LAPACK_LIBRARIES NAMES liblapack.a) - endif() # -------- armadillo -------- @@ -196,7 +192,7 @@ if(VTK_FOUND AND NOT APPLE) endif() # -------------------------------------------------- -# global build configuration +# global system information # -------------------------------------------------- add_definitions(-D${CMAKE_SYSTEM_NAME}) @@ -209,89 +205,20 @@ else() set(BYTEORDER 1234) endif() -# prevents itk from importing as a system - -# to see all warnings add -DSUPPRESS_WARNINGS=OFF to cmake command line -option(SUPPRESS_WARNINGS "Allow building in subdirs to supress warnings" ON) -# option(SUPPRESS_WARNINGS "Allow building in subdirs to supress warnings" OFF) - -# compiler warnings -set(C_CXX_FLAGS "${C_CXX_FLAGS} -Wall") -# clang complains about -Wno-unused-but-set-variable and says to use -Wno-unused-const-variable - -if(SUPPRESS_WARNINGS) - if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(C_CXX_FLAGS "${C_CXX_FLAGS} -Wno-unused-const-variable") - else() - set(C_CXX_FLAGS "${C_CXX_FLAGS} -Wno-unused-but-set-variable") - endif() -endif() - -# ANSI -add_definitions(-DANSI) - -# SSE matrix and math functions (affine.h and sse_mathfun.h) -# todo: write some logic to set this correctly -add_definitions(-DUSE_SSE_MATHFUN) -set(C_CXX_FLAGS "${C_CXX_FLAGS} -msse2 -mfpmath=sse -fPIC") - -# large file support: support for files > 2GB -if(APPLE) - add_definitions(-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE) -endif() - -# todo: implement processor-based logic to determine this -set(C_CXX_FLAGS "${C_CXX_FLAGS} -m64") - -# for stripping unused code -if(APPLE) - set(STRIP_FLAGS "-dead_strip") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${STRIP_FLAGS} -static-libgcc") -else() - if(SUPPRESS_WARNINGS) - set(STRIP_FLAGS "-fdata-sections -ffunction-sections -Wl,--gc-sections") - else() - # set(STRIP_FLAGS "-fdata-sections -ffunction-sections") - # Need this linker option for linux else, e.g., linking of gifti_test fails - set(STRIP_FLAGS "-fdata-sections -ffunction-sections -Wl,--gc-sections") - - endif() - set(C_CXX_FLAGS "${C_CXX_FLAGS} ${STRIP_FLAGS}") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${STRIP_FLAGS}") -endif() - -if(NOT APPLE) - # link map (only for linux) - if(SUPPRESS_WARNINGS) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Map,ld_map.txt -Wl,--no-demangle") - endif() -endif() - -# check for clock_gettime on mac -if(APPLE) - check_function_exists(clock_gettime HAVE_CLOCK_GETTIME) - if(HAVE_CLOCK_GETTIME) - add_definitions(-DHAVE_CLOCK_GETTIME) - endif() -endif() - -# apply C and CXX flags -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${C_CXX_FLAGS}") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${C_CXX_FLAGS}") - # enable std c++11 set(CMAKE_CXX_STANDARD 11) -# set executable rpath -if(NOT APPLE) - set(CMAKE_INSTALL_RPATH "$ORIGIN/../lib:${CMAKE_INSTALL_RPATH}") -endif() +# -------------------------------------------------- +# third-party code +# -------------------------------------------------- + +add_subdirectory(packages) # -------------------------------------------------- -# setup python +# setup python # -------------------------------------------------- -# Unfortunately, the python version used to run bind c-libraries must be equivalent to +# Unfortunately, the python version used to run pybind c-libraries must be equivalent to # the version used to build the libraries. The easiest and least intrusive way of making freesurfer # python scripts run out-of-the-box (and to help guarantee reproducibility) requires # distributing a minimal, custom python installation called fspython. This fspython package @@ -316,7 +243,7 @@ if(DISTRIBUTE_FSPYTHON) endif() # initialize pybind for python wrapping -set(PYBIND11_PYTHON_VERSION 3.5) # minimum version required +set(PYBIND11_PYTHON_VERSION 3.5) add_subdirectory(packages/pybind11) if(NOT DISTRIBUTE_FSPYTHON) @@ -324,50 +251,68 @@ if(NOT DISTRIBUTE_FSPYTHON) symlink(${PYTHON_EXECUTABLE} ${CMAKE_INSTALL_PREFIX}/python/bin/python3) endif() +# -------------------------------------------------- +# freesurfer build settings +# -------------------------------------------------- + +# warnings +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -Wno-sign-compare -Wno-write-strings") + +# clang complains about -Wno-unused-but-set-variable and says to use -Wno-unused-const-variable +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-const-variable") +else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-but-set-variable") +endif() + +# ANSI +add_definitions(-DANSI) + +# SSE matrix and math functions (affine.h and sse_mathfun.h) +# todo: write some logic to set this correctly +add_definitions(-DUSE_SSE_MATHFUN) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64 -msse2 -mfpmath=sse -fPIC") + +# large file support: support for files > 2GB +# todo: can this just be removed entirely? +if(APPLE) + add_definitions(-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE) +endif() + +# linker options +if(APPLE) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -dead_strip -static-libgcc") +else() + set(STRIP_FLAGS "-fdata-sections -ffunction-sections -Wl,--gc-sections") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${STRIP_FLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${STRIP_FLAGS} -Wl,-Map,ld_map.txt -Wl,--no-demangle") +endif() + +# check for clock_gettime on mac +if(APPLE) + check_function_exists(clock_gettime HAVE_CLOCK_GETTIME) + if(HAVE_CLOCK_GETTIME) + add_definitions(-DHAVE_CLOCK_GETTIME) + endif() +endif() + # -------------------------------------------------- # build freesurfer # -------------------------------------------------- -# first, prepare the freesurfer distribution +# prepare the freesurfer distribution add_subdirectory(distribution) -# the top-level include dir contain the most commonly -# included freesurfer header files +# the top-level include dir contain the most commonly included freesurfer header files set(FS_INCLUDE_DIRS - ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/packages/minc ${CMAKE_SOURCE_DIR}/packages/netcdf + ${CMAKE_SOURCE_DIR}/packages/nifti ) -# build third-party libraries -# make sure to use the local minc source -add_definitions(-DUSE_LOCAL_MINC) -add_subdirectories( - packages/jpeg - packages/expat - packages/tiff - packages/xml2 - packages/minc - packages/netcdf - packages/tetgen -) - -if(OPENGL_FOUND) - add_subdirectory(packages/glut) -endif() - -# now build the freesurfer static libraries (order here matters!) -add_subdirectories( - log - rgb - hipsstubs - dicom - utils - utilscpp - svm-lib - opencl_algorithms -) +# build the freesurfer static libraries +add_subdirectories(utils opencl_algorithms) # the following utility libraries are required for freeview add_subdirectories(vtkutils lineprof) @@ -476,9 +421,8 @@ add_subdirectories( tkregister2 ) -# the following program subdirectories aren't required in the standard -# recon-all stream - they will be built by default, but not if a minimal build -# is configured +# the following program subdirectories aren't required in the standard recon-all stream. +# they will be built by default, but not if a minimal build is configured if(NOT MINIMAL) add_subdirectories( anatomicuts @@ -487,6 +431,7 @@ if(NOT MINIMAL) connectgraph diffusion_tool dmri_tensoreig + dummy dngtester freeview fsfast @@ -622,7 +567,7 @@ if(NOT MINIMAL) mri_update_gca mri_vol2roi mri_volcluster - mri_volsynth + # mri_volsynth mri_warp_convert mri_wbc mri_wmfilter @@ -683,7 +628,7 @@ if(NOT MINIMAL) mris_multiscale_stats mris_niters2fwhm mris_parcellate_connectivity - mris_pmake + # mris_pmake mris_register_label_map mris_register_to_volume mris_remove_variance diff --git a/anatomicuts/AnatomiCuts_correspondences.cxx b/anatomicuts/AnatomiCuts_correspondences.cxx index 25376da90d0..915f710c4e7 100755 --- a/anatomicuts/AnatomiCuts_correspondences.cxx +++ b/anatomicuts/AnatomiCuts_correspondences.cxx @@ -34,11 +34,11 @@ #include #include "vtkSplineFilter.h" #include "OrientationPlanesFromParcellationFilter.h" -extern "C" -{ + + #include "colortab.h" #include "fsenv.h" -} + typedef std::vector PointDataType; typedef float PixelType; diff --git a/anatomicuts/CMakeLists.txt b/anatomicuts/CMakeLists.txt index 5980bdbe65d..3aaa5e16b3e 100644 --- a/anatomicuts/CMakeLists.txt +++ b/anatomicuts/CMakeLists.txt @@ -13,11 +13,8 @@ if(VTK_FOUND) include(${ITK_USE_FILE}) include(${VTK_USE_FILE}) - - if(SUPPRESS_WARNINGS) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated -Wmaybe-uninitialized") - endif() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated -Wno-maybe-uninitialized -Wno-unused-variable -Wno-unused-local-typedefs") set(TRACKIO ../freeview/track_io/TrackIO.cpp) diff --git a/check_siemens_dir/CMakeLists.txt b/check_siemens_dir/CMakeLists.txt index fd14f3d6bff..fb71947667e 100644 --- a/check_siemens_dir/CMakeLists.txt +++ b/check_siemens_dir/CMakeLists.txt @@ -2,7 +2,7 @@ project(check_siemens_dir) include_directories(${FS_INCLUDE_DIRS}) -add_executable(check_siemens_dir check_siemens_dir.c) +add_executable(check_siemens_dir check_siemens_dir.cpp) target_link_libraries(check_siemens_dir utils) install(TARGETS check_siemens_dir DESTINATION bin) diff --git a/check_siemens_dir/check_siemens_dir.c b/check_siemens_dir/check_siemens_dir.cpp similarity index 98% rename from check_siemens_dir/check_siemens_dir.c rename to check_siemens_dir/check_siemens_dir.cpp index a78de7cc882..095cc6b6d91 100644 --- a/check_siemens_dir/check_siemens_dir.c +++ b/check_siemens_dir/check_siemens_dir.cpp @@ -45,14 +45,6 @@ struct file { const char *Progname; -#ifndef Darwin -#ifndef SunOS -#ifndef Windows_NT -extern void swab(const void *from, void *to, size_t n); -#endif -#endif -#endif - void check_directory(DIR *dp, char *dir_name); void usage(void) { diff --git a/connectgraph/connectgraph.cpp b/connectgraph/connectgraph.cpp index 95974ffbad6..8e9a0a70662 100644 --- a/connectgraph/connectgraph.cpp +++ b/connectgraph/connectgraph.cpp @@ -43,12 +43,12 @@ #include #include -extern "C" -{ + + #include "mri.h" #include "mrisurf.h" #include "colortab.h" -} + using namespace std; diff --git a/dicom/CMakeLists.txt b/dicom/CMakeLists.txt deleted file mode 100644 index 58ff71bfa95..00000000000 --- a/dicom/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -project(dicom) - -include_directories( - ${CMAKE_SOURCE_DIR}/include - ${CMAKE_SOURCE_DIR}/include/dicom -) - -set(SOURCES - condition.c - ctnthread.c - dcm.c - dcmcond.c - dcmdict.c - dcmsupport.c - lst.c -) - -add_library(dicom STATIC ${SOURCES}) diff --git a/dmri_poistats/datamodel/PoistatsModel.h b/dmri_poistats/datamodel/PoistatsModel.h index bf73504627d..c6fc6116745 100644 --- a/dmri_poistats/datamodel/PoistatsModel.h +++ b/dmri_poistats/datamodel/PoistatsModel.h @@ -10,9 +10,9 @@ #include #include -extern "C" { + #include "mri.h" -} + class InitializePath; diff --git a/dmri_poistats/datamodel/utils/InitializePath.h b/dmri_poistats/datamodel/utils/InitializePath.h index d01a5ad8caa..c881f075c2e 100644 --- a/dmri_poistats/datamodel/utils/InitializePath.h +++ b/dmri_poistats/datamodel/utils/InitializePath.h @@ -1,9 +1,9 @@ #ifndef __InitializePath_h #define __InitializePath_h -extern "C" { + #include "mri.h" -} + #include diff --git a/dmri_poistats/dmri_initialize_path.cxx b/dmri_poistats/dmri_initialize_path.cxx index 82918352c4f..d44f4759c22 100644 --- a/dmri_poistats/dmri_initialize_path.cxx +++ b/dmri_poistats/dmri_initialize_path.cxx @@ -4,10 +4,10 @@ #include #include -extern "C" -{ + + #include "matrix.h" -} + #include "ui/CommandParser.h" #include "ui/FreeSurferExecutable.h" diff --git a/dmri_tensoreig/CMakeLists.txt b/dmri_tensoreig/CMakeLists.txt index b2c3fdd45fe..8afda57045b 100644 --- a/dmri_tensoreig/CMakeLists.txt +++ b/dmri_tensoreig/CMakeLists.txt @@ -1,8 +1,8 @@ project(dmri_tensoreig) -include_directories(${FS_INCLUDE_DIRS}) +include_directories(${FS_INCLUDE_DIRS} ${CMAKE_SOURCE_DIR}/packages/dicom) -add_executable(dmri_tensoreig dmri_tensoreig.c) +add_executable(dmri_tensoreig dmri_tensoreig.cpp) target_link_libraries(dmri_tensoreig utils) install(TARGETS dmri_tensoreig DESTINATION bin) diff --git a/dmri_tensoreig/dmri_tensoreig.c b/dmri_tensoreig/dmri_tensoreig.cpp similarity index 99% rename from dmri_tensoreig/dmri_tensoreig.c rename to dmri_tensoreig/dmri_tensoreig.cpp index 579a7ec5450..e9c131dbb11 100644 --- a/dmri_tensoreig/dmri_tensoreig.c +++ b/dmri_tensoreig/dmri_tensoreig.cpp @@ -22,8 +22,6 @@ * */ -char *MRI_INFO_VERSION = "$Revision$"; - #include #include #include @@ -42,7 +40,7 @@ char *MRI_INFO_VERSION = "$Revision$"; #include "mri.h" #include "mri2.h" #include "gcamorph.h" -#include "minc_volume_io.h" +#include "minc.h" #include "analyze.h" #include "mri_identify.h" #include "error.h" diff --git a/dngtester/CMakeLists.txt b/dngtester/CMakeLists.txt index 0c104efcc9d..6788f5361b0 100644 --- a/dngtester/CMakeLists.txt +++ b/dngtester/CMakeLists.txt @@ -1,13 +1,13 @@ project(dngtester) -include_directories(${FS_INCLUDE_DIRS}) +include_directories(${FS_INCLUDE_DIRS} ${CMAKE_SOURCE_DIR}/packages/dicom) # always debug set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g") # dngtester -add_executable(dngtester dngtester.c) +add_executable(dngtester dngtester.cpp) target_link_libraries(dngtester utils) # cpptester diff --git a/dngtester/cpptester.cpp b/dngtester/cpptester.cpp index 775107797b5..3a20cf2babe 100644 --- a/dngtester/cpptester.cpp +++ b/dngtester/cpptester.cpp @@ -8,12 +8,6 @@ #include #include -// all other software are all in "C" -#ifdef __cplusplus -extern "C" -{ -#endif - #include "error.h" #include "macros.h" #include "mri.h" @@ -22,10 +16,6 @@ extern "C" #include "registerio.h" #include "version.h" -#ifdef __cplusplus -} -#endif - using namespace std; static void printUsage(void); diff --git a/dngtester/dngtester.c b/dngtester/dngtester.cpp similarity index 97% rename from dngtester/dngtester.c rename to dngtester/dngtester.cpp index fab3fc5d71b..2ec099ec0dd 100644 --- a/dngtester/dngtester.c +++ b/dngtester/dngtester.cpp @@ -71,7 +71,7 @@ int main(int argc, char **argv) { MRIS *surf, *surf2; int msec, nvertices; //vtxno=0; - struct timeb mytimer; + Timer mytimer; MRI *mri, *mriindex, *mri2; Geodesics *geod; float maxdist; @@ -274,16 +274,16 @@ int main(int argc, char **argv) // apply smoothing: 5 args: surf geod input index output surf = MRISread(argv[1]); printf("reaDing geo\n"); fflush(stdout); - TimerStart(&mytimer) ; + mytimer.reset() ; geod = geodesicsRead(argv[2], &nvertices); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf("t = %g min\n",msec/(1000.0*60)); mri = MRIread(argv[3]); mriindex = MRIread(argv[4]); printf("Smoothing\n"); - TimerStart(&mytimer) ; + mytimer.reset() ; mri2 = GeoSmooth(mri, 10, surf, geod, mriindex, NULL); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf("t = %g min\n",msec/(1000.0*60)); fflush(stdout); MRIwrite(mri2,argv[5]); @@ -302,31 +302,31 @@ int main(int argc, char **argv) // create geod file: 3 args: surf distmax output surf = MRISread(argv[1]); sscanf(argv[2],"%f",&maxdist); - TimerStart(&mytimer) ; + mytimer.reset() ; geod = computeGeodesics(surf, maxdist); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf("done t = %g min\n",msec/(1000.0*60)); geodesicsWrite(geod, surf->nvertices, argv[3]); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf("done write t = %g min\n",msec/(1000.0*60)); exit(0); //------------------------- //GeoDumpVertex("uvtx.108489.dist.dat", geod, 108489); - TimerStart(&mytimer) ; + mytimer.reset() ; geod = geodesicsReadV2(argv[1], &nvertices); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf(" read2 t = %g min\n",msec/(1000.0*60)); exit(0); //------------------------- - TimerStart(&mytimer) ; + mytimer.reset() ; geodesicsWrite(geod, nvertices, "u1.geod"); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf(" write1 t = %g min\n",msec/(1000.0*60)); - TimerStart(&mytimer) ; + mytimer.reset() ; geodesicsWriteV2(geod, nvertices, "u2.geod"); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf(" write2 t = %g min\n",msec/(1000.0*60)); exit(0); //------------------------- diff --git a/dummy/CMakeLists.txt b/dummy/CMakeLists.txt index 81fb9c5a948..95406d653e8 100644 --- a/dummy/CMakeLists.txt +++ b/dummy/CMakeLists.txt @@ -2,7 +2,7 @@ project(dummy) include_directories(${FS_INCLUDE_DIRS}) -add_executable(dummy dummy.c) +add_executable(dummy dummy.cpp) target_link_libraries(dummy utils) install(TARGETS dummy DESTINATION bin) diff --git a/dummy/dummy.c b/dummy/dummy.c deleted file mode 100644 index c3db31b4e3a..00000000000 --- a/dummy/dummy.c +++ /dev/null @@ -1,237 +0,0 @@ -/** - * @file dummy.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:01 $ - * $Revision: 1.10 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - - -/*! -\file dummy.c -\brief Example c file that can be used as a template. -\author Douglas Greve - -*/ - - -// $Id: dummy.c,v 1.10 2011/03/02 00:04:01 nicks Exp $ - -/* - BEGINHELP - - ENDHELP -*/ - -/* - BEGINUSAGE - - ENDUSAGE -*/ - - -#include -#include -#include -#include - -#include "macros.h" -#include "utils.h" -#include "fio.h" -#include "version.h" -#include "cmdargs.h" -#include "error.h" -#include "diag.h" - -static int parse_commandline(int argc, char **argv); -static void check_options(void); -static void print_usage(void) ; -static void usage_exit(void); -static void print_help(void) ; -static void print_version(void) ; -static void dump_options(FILE *fp); -int main(int argc, char *argv[]) ; - -static char vcid[] = "$Id: dummy.c,v 1.10 2011/03/02 00:04:01 nicks Exp $"; -const char *Progname = NULL; -char *cmdline, cwd[2000]; -int debug=0; -int checkoptsonly=0; -struct utsname uts; - -char *TempVolFile=NULL; -char *subject, *hemi, *SUBJECTS_DIR; - -/*---------------------------------------------------------------*/ -int main(int argc, char *argv[]) { - int nargs; - - nargs = handle_version_option (argc, argv, vcid, "$Name: $"); - if (nargs && argc - nargs == 1) exit (0); - argc -= nargs; - cmdline = argv2cmdline(argc,argv); - uname(&uts); - getcwd(cwd,2000); - - Progname = argv[0] ; - argc --; - argv++; - ErrorInit(NULL, NULL, NULL) ; - DiagInit(NULL, NULL, NULL) ; - if (argc == 0) usage_exit(); - parse_commandline(argc, argv); - check_options(); - if (checkoptsonly) return(0); - dump_options(stdout); - - SUBJECTS_DIR = getenv("SUBJECTS_DIR"); - if (SUBJECTS_DIR == NULL) { - printf("ERROR: SUBJECTS_DIR not defined in environment\n"); - exit(1); - } - - return 0; -} -/* ------ Doxygen markup starts on the line below ---- */ -/*! -\fn int parse_commandline(int argc, char **argv) -\brief Parses the command-line arguments -\param argc - number of command line arguments -\param argv - pointer to a character pointer -*/ -/* ------ Doxygen markup ends on the line above ---- */ -static int parse_commandline(int argc, char **argv) { - int nargc , nargsused; - char **pargv, *option ; - - if (argc < 1) usage_exit(); - - nargc = argc; - pargv = argv; - while (nargc > 0) { - - option = pargv[0]; - if (debug) printf("%d %s\n",nargc,option); - nargc -= 1; - pargv += 1; - - nargsused = 0; - - if (!strcasecmp(option, "--help")) print_help() ; - else if (!strcasecmp(option, "--version")) print_version() ; - else if (!strcasecmp(option, "--debug")) debug = 1; - else if (!strcasecmp(option, "--checkopts")) checkoptsonly = 1; - else if (!strcasecmp(option, "--nocheckopts")) checkoptsonly = 0; - - else if (!strcasecmp(option, "--temp-vol")) { - if (nargc < 1) CMDargNErr(option,1); - TempVolFile = pargv[0]; - nargsused = 1; - } else { - fprintf(stderr,"ERROR: Option %s unknown\n",option); - if (CMDsingleDash(option)) - fprintf(stderr," Did you really mean -%s ?\n",option); - exit(-1); - } - nargc -= nargsused; - pargv += nargsused; - } - return(0); -} -/* -- Doxygen markup starts on the line below (this line not needed for Doxygen) -- */ -/*! -\fn static void usage_exit(void) -\brief Prints usage and exits -*/ -/* ------ Doxygen markup ends on the line above (this line not needed for Doxygen) -- */ -static void usage_exit(void) { - print_usage() ; - exit(1) ; -} -/* -- Doxygen markup starts on the line below (this line not needed for Doxygen) -- */ -/*! -\fn static void print_usage(void) -\brief Prints usage and returns (does not exit) -*/ -/* ------ Doxygen markup ends on the line above (this line not needed for Doxygen) -- */ -static void print_usage(void) { - printf("USAGE: %s \n",Progname) ; - printf("\n"); - printf(" --temp-vol volfile : template volume \n"); - printf("\n"); - printf(" --debug turn on debugging\n"); - printf(" --checkopts don't run anything, just check options and exit\n"); - printf(" --help print out information on how to use this program\n"); - printf(" --version print out version and exit\n"); - printf("\n"); - printf("%s\n", vcid) ; - printf("\n"); -} -/* -- Doxygen markup starts on the line below (this line not needed for Doxygen) -- */ -/*! -\fn static void print_help(void) -\brief Prints help and exits -*/ -/* ------ Doxygen markup ends on the line above (this line not needed for Doxygen) -- */ -static void print_help(void) { - print_usage() ; - printf("WARNING: this program is not yet tested!\n"); - exit(1) ; -} -/* -- Doxygen markup starts on the line below (this line not needed for Doxygen) -- */ -/*! -\fn static void print_version(void) -\brief Prints version and exits -*/ -/* ------ Doxygen markup ends on the line above (this line not needed for Doxygen) -- */ -static void print_version(void) { - printf("%s\n", vcid) ; - exit(1) ; -} -/* -- Doxygen markup starts on the line below (this line not needed for Doxygen) -- */ -/*! -\fn static void check_options(void) -\brief Checks command-line options -*/ -/* ------ Doxygen markup ends on the line above (this line not needed for Doxygen) -- */ -static void check_options(void) { - return; -} - -/* -- Doxygen markup starts on the line below (this line not needed for Doxygen) -- */ -/*! -\fn static void dump_options(FILE *fp) -\brief Prints command-line options to the given file pointer -\param FILE *fp - file pointer -*/ -/* ------ Doxygen markup ends on the line above (this line not needed for Doxygen) -- */ -static void dump_options(FILE *fp) { - fprintf(fp,"\n"); - fprintf(fp,"%s\n",vcid); - fprintf(fp,"cwd %s\n",cwd); - fprintf(fp,"cmdline %s\n",cmdline); - fprintf(fp,"sysname %s\n",uts.sysname); - fprintf(fp,"hostname %s\n",uts.nodename); - fprintf(fp,"machine %s\n",uts.machine); - fprintf(fp,"user %s\n",VERuser()); - - return; -} diff --git a/dummy/dummy.cpp b/dummy/dummy.cpp new file mode 100644 index 00000000000..3875f6dcba6 --- /dev/null +++ b/dummy/dummy.cpp @@ -0,0 +1,8 @@ +#include + +#include "log.h" +#include "timer.h" + +int main(int argc, const char **argv) { + logDebug << currentDateTime(); +} diff --git a/dummy/myown.c b/dummy/myown.c deleted file mode 100644 index 5182ad3093a..00000000000 --- a/dummy/myown.c +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file connectgraph.c - * @brief Convert connectivity data to graphviz data format - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:01 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/** - * @file myown.c - * @author Yasunari Tosa - * @date Wed Oct 13 11:48:26 2004 - * - * @brief sample test program - * - * - */ -#include -#include - -int main(int argc, char *argv[]) { - printf("just a sample program.\n"); - exit(0); -} diff --git a/fem_elastic/CMakeLists.txt b/fem_elastic/CMakeLists.txt index a54f3ff5740..2bb38f19d40 100644 --- a/fem_elastic/CMakeLists.txt +++ b/fem_elastic/CMakeLists.txt @@ -23,19 +23,19 @@ if(PETSC_FOUND) # createMorph add_executable(createMorph fcreateMorph.cpp ${COMMON3D_SOURCES}) add_help(createMorph createMorph.help.xml) - target_link_libraries(createMorph utils utilscpp tetgen) + target_link_libraries(createMorph utils tetgen) install(TARGETS createMorph DESTINATION bin) # applyMorph add_executable(applyMorph fapplyMorph.cpp ${COMMON3D_SOURCES}) add_help(applyMorph applyMorph.help.xml) - target_link_libraries(applyMorph utils utilscpp tetgen) + target_link_libraries(applyMorph utils tetgen) install(TARGETS applyMorph DESTINATION bin) # exportGcam add_executable(exportGcam exportGcam.cpp ${COMMON3D_SOURCES}) add_help(exportGcam exportGcam.help.xml) - target_link_libraries(exportGcam utils utilscpp tetgen) + target_link_libraries(exportGcam utils tetgen) install(TARGETS exportGcam DESTINATION bin) if(APPLE) diff --git a/fem_elastic/exportGcam.cpp b/fem_elastic/exportGcam.cpp index b9613368b73..037b54d68cd 100644 --- a/fem_elastic/exportGcam.cpp +++ b/fem_elastic/exportGcam.cpp @@ -20,15 +20,13 @@ As a validation, it will use the gcam to morph again the volumes #include "morph.h" -// OWN -#include "simple_timer.h" - // FS -#include "argparse.hpp" -extern "C" { +#include "argparse.h" +#include "timer.h" + #include "mri.h" #include "gcamorph.h" -} + #include "exportGcam.help.xml.h" @@ -72,7 +70,7 @@ void initOctree2( gmp::VolumeMorph& morph) int main(int ac, const char** av) { - SimpleTimer timer; + Timer timer; IoParams params; try @@ -131,15 +129,13 @@ main(int ac, const char** av) if (params.doTest) { std::cout << " Writing out some tests.\n"; - SimpleTimer t1; + Timer t1; VOL_GEOM vgLike; initVolGeom(&vgLike); getVolGeom(pmorph->m_template, &vgLike); - MRI* mriOut = pmorph->apply_transforms(mriMoving, - true, - &vgLike); - std::cout << " morph completed in " << t1.elapsed_min() << " minutes\n"; + MRI* mriOut = pmorph->apply_transforms(mriMoving, true, &vgLike); + std::cout << " morph completed in " << t1.minutes() << " minutes\n"; //MRIwrite(mriOut, "tmpout1.mgz"); MRIfree(&mriOut); } @@ -179,7 +175,7 @@ main(int ac, const char** av) std::cout << " skipping tmpout2.mgz - using bounding box\n"; } - std::cout << " Export performed in " << timer.elapsed_min() << " minutes \n"; + std::cout << " Export performed in " << timer.minutes() << " minutes \n"; printf("#VMPC# exportGcam VmPeak %d\n",GetVmPeak()); return 0; diff --git a/fem_elastic/fapplyMorph.cpp b/fem_elastic/fapplyMorph.cpp index eff2fc2930c..dcee726d1a1 100644 --- a/fem_elastic/fapplyMorph.cpp +++ b/fem_elastic/fapplyMorph.cpp @@ -17,10 +17,10 @@ #include "morph_utils.h" // FreeSurfer -#include "argparse.hpp" -extern "C" { +#include "argparse.h" + #include "mri.h" -} + #include "applyMorph.help.xml.h" diff --git a/fem_elastic/fcreateMorph.cpp b/fem_elastic/fcreateMorph.cpp index f5856a2e743..4c1fa7dd356 100644 --- a/fem_elastic/fcreateMorph.cpp +++ b/fem_elastic/fcreateMorph.cpp @@ -16,11 +16,11 @@ This binary creates a morph, given transforms #include "transformUtils.h" // FS -#include "argparse.hpp" -extern "C" { +#include "argparse.h" + #include "gcamorph.h" #include "mri.h" -} + #include "createMorph.help.xml.h" diff --git a/fem_elastic/fem_3d.cpp b/fem_elastic/fem_3d.cpp index 1c8b61ec17d..1c1a57fabaf 100644 --- a/fem_elastic/fem_3d.cpp +++ b/fem_elastic/fem_3d.cpp @@ -7,7 +7,7 @@ #include #include "misc.h" -//#include "solver.h" +#include "timer.h" #include "fem_3d.h" @@ -643,8 +643,6 @@ CMesh3d::~CMesh3d() if ( m_poctree ) delete m_poctree; } -#include "simple_timer.h" - int CMesh3d::build_index_src() { @@ -663,7 +661,7 @@ CMesh3d::build_index_src() std::cout << " done building the list\n"; unsigned int count = 0;//, oldPercentage = 0, percentage; - SimpleTimer timer; + Timer timer; for (std::vector::const_iterator cit = m_vpEltBlock.begin(); cit != m_vpEltBlock.end(); ++cit, ++count ) { @@ -671,10 +669,10 @@ CMesh3d::build_index_src() if ( !(count % 100000) ) { std::cout << "\t count inserted = " << count - << " elapsed = " << timer.elapsed() << " seconds " + << " elapsed = " << timer.seconds() << " seconds " << " element count = " << m_poctree->getElementCount() << std::endl; - timer = SimpleTimer(); + timer.reset(); } } diff --git a/fem_elastic/fsurf2vol.cpp b/fem_elastic/fsurf2vol.cpp index 9d48bbfcde5..20d10431ea2 100644 --- a/fem_elastic/fsurf2vol.cpp +++ b/fem_elastic/fsurf2vol.cpp @@ -20,7 +20,7 @@ // the isfinite defined in utils conflicts with vnl #undef isfinite -#include "simple_timer.h" +#include "timer.h" #include "transformUtils.h" #include "morph.h" @@ -38,13 +38,13 @@ #define MORPH_WITH_MESH 1 #define DO_MORPH_REGRESSION 0 -extern "C" -{ + + #include "error.h" #include "mri.h" #include "mrinorm.h" #include "mrisurf.h" -}; +; const char *Progname; @@ -271,7 +271,7 @@ main(int argc, char* argv[]) { - SimpleTimer timer; + Timer timer; PetscErrorCode ierr; @@ -466,7 +466,7 @@ main(int argc, std::cout << " srcPoints size = " << srcPoints.size() << std::endl; - printf("baseline %g",timer.elapsed()/60);PrintMemUsage(stdout); + printf("baseline %g",timer.minutes()); PrintMemUsage(stdout); try { Transform3SPointer ptransform(new gmp::IdentityTransform3d); @@ -476,7 +476,7 @@ main(int argc, for ( int step = noSteps; step > params.iEndStep; --step ) { std::cout << " ======================\n step = " << step << "\n===============\n"; - printf("step %d %g ",step,timer.elapsed()/60);PrintMemUsage(stdout); + printf("step %d %g ",step,timer.minutes());PrintMemUsage(stdout); TSolver solver; // linearly vary the element volume in the given range @@ -489,17 +489,17 @@ main(int argc, DelaunayMesh dmesh(srcPoints, cmin, cmax,deltVol , params.YoungModulus, params.poissonRatio); - printf("preget %g ",timer.elapsed()/60); PrintMemUsage(stdout); + printf("preget %g ",timer.minutes()); PrintMemUsage(stdout); CMesh3d* pmesh = dmesh.get(); - printf("postget %g",timer.elapsed()/60); PrintMemUsage(stdout); + printf("postget %g",timer.minutes()); PrintMemUsage(stdout); // print basic information about the mesh std::cout << " mesh nodes = " << pmesh->get_no_nodes() << " mesh elts = " << pmesh->get_no_elts() << std::endl; - printf("prebuild %g ",timer.elapsed()/60); PrintMemUsage(stdout); + printf("prebuild %g ",timer.minutes()); PrintMemUsage(stdout); pmesh->build_index_src(); - printf("postbuild %g ",timer.elapsed()/60); PrintMemUsage(stdout); + printf("postbuild %g ",timer.minutes()); PrintMemUsage(stdout); solver.set_mesh(pmesh); @@ -510,11 +510,10 @@ main(int argc, // todo - the next timer shows time that could be saved (most of it) // namely at the first iteration the time is what it should always be - SimpleTimer t1; + Timer t1; update_sources( srcPoints, pmesh ); - std::cout << " c0324 time elapsed updating the sources (seconds) = " - << t1.elapsed() << std::endl; + std::cout << " c0324 time elapsed updating the sources (seconds) = " << t1.seconds() << std::endl; if ( !pmesh->orientation_pb(both) ) @@ -766,7 +765,7 @@ main(int argc, ierr = PetscFinalize(); CHKERRQ(ierr); - std::cout << " process performed in " << timer.elapsed()/60. << " minutes\n"; + std::cout << " process performed in " << timer.minutes() << " minutes\n"; printf("surf2vol done ");PrintMemUsage(stdout); printf("#VMPC# fsurf2vol VmPeak %d\n",GetVmPeak()); diff --git a/fem_elastic/mesh.h b/fem_elastic/mesh.h index d8339e80510..5a1b8045f04 100644 --- a/fem_elastic/mesh.h +++ b/fem_elastic/mesh.h @@ -26,10 +26,10 @@ #include "stl_utils.hpp" #if 0 -extern "C" -{ + + #include "fio.h" -}; +; #endif typedef std::stack tStack; diff --git a/fem_elastic/morph.h b/fem_elastic/morph.h index b90a6940650..1d622c807db 100644 --- a/fem_elastic/morph.h +++ b/fem_elastic/morph.h @@ -34,13 +34,13 @@ polymorphic way. #include "fem_3d.h" -extern "C" -{ + + #include "mri.h" #define class xclass #include "gcamorph.h" #undef class -}; +; /* diff --git a/fem_elastic/simple_timer.h b/fem_elastic/simple_timer.h deleted file mode 100644 index eff5cbc8cfc..00000000000 --- a/fem_elastic/simple_timer.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - -Gheorghe Postelnicu, 2007 - -simple timer class - basic time measurements - -*/ -#ifndef _h_simple_timer_h -#define _h_simple_timer_h - - -// use FS timer -extern "C" -{ -#include "timer.h" -}; - -class SimpleTimer -{ -public: - SimpleTimer() - { - TimerStart(&m_start); - } - double elapsed() const - { - return double( TimerStop(const_cast(&m_start) ) ) / 1000.; - } - double elapsed_min() const - { - return this->elapsed() / 60.; - } - double elapsed_hour() const - { - return this->elapsed() / 3600. ; - } -private: - timeb m_start; -}; - -#endif diff --git a/fem_elastic/surf_powell.cpp b/fem_elastic/surf_powell.cpp index 88fdb6779c8..6cece16d813 100644 --- a/fem_elastic/surf_powell.cpp +++ b/fem_elastic/surf_powell.cpp @@ -1,11 +1,11 @@ #include "surf_powell.h" -extern "C" -{ + + #include "numerics.h" #include "matrix.h" -}; +; static float compute_powell_cost(float *p); diff --git a/fem_elastic/surf_powell.h b/fem_elastic/surf_powell.h index ce5803a6941..f6605b26a5d 100644 --- a/fem_elastic/surf_powell.h +++ b/fem_elastic/surf_powell.h @@ -4,14 +4,14 @@ #include "surf_types.h" -extern "C" -{ + + // both /usr/pubsw/packages/petsc/current/include/petscvec.h and mrisurf.h // define NORM_MAX, so undef it to reveal who uses it, if anybody. #undef NORM_MAX #include "mrisurf.h" #undef NORM_MAX -} + // // the energy defined will be the MAX of the norm of the error diff --git a/fem_elastic/surf_utils.h b/fem_elastic/surf_utils.h index d9d131ad37d..1aef1c50e24 100644 --- a/fem_elastic/surf_utils.h +++ b/fem_elastic/surf_utils.h @@ -8,11 +8,11 @@ #include "coords.h" #include "fem_3d.h" -extern "C" -{ + + #include "mri.h" #include "mrisurf.h" -} + enum SurfaceType { diff --git a/fem_elastic/transformUtils.cpp b/fem_elastic/transformUtils.cpp index a28917d059f..0e27f334c79 100644 --- a/fem_elastic/transformUtils.cpp +++ b/fem_elastic/transformUtils.cpp @@ -1,15 +1,7 @@ #include #include #include - -#ifdef __cplusplus -extern "C" -{ -#endif #include // exit -#ifdef __cplusplus -} -#endif #include "transformUtils.h" diff --git a/freeview/DialogLoadTransform.cpp b/freeview/DialogLoadTransform.cpp index ea79325c406..f02cce3468b 100644 --- a/freeview/DialogLoadTransform.cpp +++ b/freeview/DialogLoadTransform.cpp @@ -4,10 +4,10 @@ #include #include -extern "C" -{ + + #include "mri.h" -} + DialogLoadTransform::DialogLoadTransform(QWidget *parent) : diff --git a/freeview/DialogLoadVolume.cpp b/freeview/DialogLoadVolume.cpp index 90fe7a1bf15..a757256e3e6 100644 --- a/freeview/DialogLoadVolume.cpp +++ b/freeview/DialogLoadVolume.cpp @@ -32,10 +32,10 @@ #include #include -extern "C" -{ + + #include "mri.h" -} + DialogLoadVolume::DialogLoadVolume(QWidget *parent) : QDialog(parent), diff --git a/freeview/DialogTransformVolume.cpp b/freeview/DialogTransformVolume.cpp index b2a3481d973..91cc9c14104 100644 --- a/freeview/DialogTransformVolume.cpp +++ b/freeview/DialogTransformVolume.cpp @@ -43,10 +43,10 @@ #define TRANSLATION_INCREMENT 0.5 #define SCALE_INCREMENT 0.05 -extern "C" -{ + + #include "mri.h" -} + DialogTransformVolume::DialogTransformVolume(QWidget *parent) : QDialog(parent), diff --git a/freeview/FSGroupDescriptor.h b/freeview/FSGroupDescriptor.h index b39de9da1c7..d0aa429149b 100644 --- a/freeview/FSGroupDescriptor.h +++ b/freeview/FSGroupDescriptor.h @@ -31,11 +31,11 @@ #include #include -extern "C" -{ + + #include "fsgdf.h" #undef isfinite // conflicts with vnl -} + class FSVolume; diff --git a/freeview/FSLabel.h b/freeview/FSLabel.h index 95267109393..5a00b2ead09 100644 --- a/freeview/FSLabel.h +++ b/freeview/FSLabel.h @@ -31,12 +31,12 @@ #include "vtkMatrix4x4.h" #include -extern "C" -{ + + #include "label.h" #undef uchar // conflicts with Qt #include "mrisutils.h" -} + class FSVolume; class FSSurface; diff --git a/freeview/FSPointSet.h b/freeview/FSPointSet.h index 08442452312..22a486dcab0 100644 --- a/freeview/FSPointSet.h +++ b/freeview/FSPointSet.h @@ -32,10 +32,10 @@ #include #include -extern "C" -{ + + #include "label.h" -} + class FSVolume; diff --git a/freeview/FSSurface.cpp b/freeview/FSSurface.cpp index ad1f84d845f..36b86143491 100644 --- a/freeview/FSSurface.cpp +++ b/freeview/FSSurface.cpp @@ -53,10 +53,10 @@ #include #include -extern "C" -{ + + #include "mri_identify.h" -} + using namespace std; diff --git a/freeview/FSSurface.h b/freeview/FSSurface.h index 193c7266492..c5ff248be4e 100644 --- a/freeview/FSSurface.h +++ b/freeview/FSSurface.h @@ -38,11 +38,11 @@ #include #include -extern "C" -{ + + #include "mrisurf.h" #include "mri.h" -} + #define NUM_OF_VSETS 5 diff --git a/freeview/FSVolume.cpp b/freeview/FSVolume.cpp index f86731799f7..0f394afd4b8 100644 --- a/freeview/FSVolume.cpp +++ b/freeview/FSVolume.cpp @@ -53,15 +53,15 @@ #include #endif -extern "C" -{ + + #include "registerio.h" #include "utils.h" #include "macros.h" #include "mrisegment.h" #include "mri.h" #include "mri2.h" -} + #define NUM_OF_HISTO_BINS 10000 diff --git a/freeview/FSVolume.h b/freeview/FSVolume.h index 2db911888ea..c925569070a 100644 --- a/freeview/FSVolume.h +++ b/freeview/FSVolume.h @@ -33,13 +33,13 @@ #include "CommonDataStruct.h" #include -extern "C" -{ + + #include "mri.h" #include "histo.h" #include "colortab.h" #include "transform.h" -} + class vtkTransform; diff --git a/freeview/LUTDataHolder.h b/freeview/LUTDataHolder.h index 9b1683968ee..34f15c5214b 100644 --- a/freeview/LUTDataHolder.h +++ b/freeview/LUTDataHolder.h @@ -29,10 +29,10 @@ #include #include -extern "C" -{ + + #include "colortab.h" -} + class LUTDataHolder { diff --git a/freeview/LayerConnectomeMatrix.h b/freeview/LayerConnectomeMatrix.h index 4202a62beba..bd4687bf87b 100644 --- a/freeview/LayerConnectomeMatrix.h +++ b/freeview/LayerConnectomeMatrix.h @@ -6,11 +6,11 @@ #include #include -extern "C" -{ + + #include "cmat.h" #include "colortab.h" -} + class LayerMRI; class LayerPropertyConnectomeMatrix; diff --git a/freeview/LayerFCD.h b/freeview/LayerFCD.h index b927f378fc5..1458148b2a2 100644 --- a/freeview/LayerFCD.h +++ b/freeview/LayerFCD.h @@ -4,11 +4,11 @@ #include "LayerVolumeBase.h" #include "vtkSmartPointer.h" -extern "C" -{ + + #include "colortab.h" #include "fcd.h" -} + class LayerPropertyFCD; class QThread; diff --git a/freeview/LayerMRI.cpp b/freeview/LayerMRI.cpp index 1192b25102c..c291555c6de 100644 --- a/freeview/LayerMRI.cpp +++ b/freeview/LayerMRI.cpp @@ -88,11 +88,11 @@ #include "BrushProperty.h" #include "vtkImageResliceMapper.h" -extern "C" -{ + + #include "utils.h" #include "geos.h" -} + #define IMAGE_RESAMPLE_FACTOR 4.0 // must be multiples of 2 diff --git a/freeview/LayerMRI.h b/freeview/LayerMRI.h index 7e7d71a9e0c..bc06dd3a243 100644 --- a/freeview/LayerMRI.h +++ b/freeview/LayerMRI.h @@ -31,11 +31,11 @@ #include #include -extern "C" -{ + + #include "colortab.h" #include "nifti1.h" -} + class vtkImageReslice; class vtkImageMapToColors; diff --git a/freeview/LayerPropertyMRI.h b/freeview/LayerPropertyMRI.h index 4592f5c81a9..c634d587e85 100644 --- a/freeview/LayerPropertyMRI.h +++ b/freeview/LayerPropertyMRI.h @@ -35,10 +35,10 @@ #include #include -extern "C" -{ + + #include "colortab.h" -} + class vtkFreesurferLookupTable; class vtkRGBAColorTransferFunction; diff --git a/freeview/LayerPropertyPointSet.h b/freeview/LayerPropertyPointSet.h index 0888ef973e9..d0bc9f3c63a 100644 --- a/freeview/LayerPropertyPointSet.h +++ b/freeview/LayerPropertyPointSet.h @@ -35,10 +35,10 @@ #include #include -extern "C" -{ + + #include "colortab.h" -} + struct ScalarValues diff --git a/freeview/LayerPropertyROI.h b/freeview/LayerPropertyROI.h index bd494416ae0..37a3ed5d6dc 100644 --- a/freeview/LayerPropertyROI.h +++ b/freeview/LayerPropertyROI.h @@ -34,10 +34,10 @@ #include "LayerProperty.h" #include -extern "C" -{ + + #include "colortab.h" -} + class vtkRGBAColorTransferFunction; diff --git a/freeview/LayerROI.h b/freeview/LayerROI.h index 3c0fd286dc6..e613d5b102a 100644 --- a/freeview/LayerROI.h +++ b/freeview/LayerROI.h @@ -44,9 +44,9 @@ class LayerMRI; class LayerPropertyROI; class LayerSurface; -extern "C" { + #include "label.h" -} + class LayerROI : public LayerVolumeBase { diff --git a/freeview/LayerVolumeTrack.cpp b/freeview/LayerVolumeTrack.cpp index 36d3cc5ae89..0036d12c682 100644 --- a/freeview/LayerVolumeTrack.cpp +++ b/freeview/LayerVolumeTrack.cpp @@ -35,10 +35,10 @@ #include "MyVTKUtils.h" #include #include -extern "C" -{ + + #include "cma.h" -} + LayerVolumeTrack::LayerVolumeTrack( LayerMRI* ref, QObject* parent ) : LayerMRI( ref, parent ), diff --git a/freeview/MyUtils.cpp b/freeview/MyUtils.cpp index a5d6f1132ee..6b474e51b5e 100644 --- a/freeview/MyUtils.cpp +++ b/freeview/MyUtils.cpp @@ -30,10 +30,10 @@ #include #include #include -extern "C" -{ + + #include "matrix.h" -} + using namespace std; diff --git a/freeview/PanelVolume.h b/freeview/PanelVolume.h index b942ea045c6..07dd31483ab 100644 --- a/freeview/PanelVolume.h +++ b/freeview/PanelVolume.h @@ -28,10 +28,10 @@ #include #include -extern "C" -{ + + #include "colortab.h" -} + namespace Ui { diff --git a/freeview/SurfaceAnnotation.h b/freeview/SurfaceAnnotation.h index 3afb2f62d50..8a5072b3ad5 100644 --- a/freeview/SurfaceAnnotation.h +++ b/freeview/SurfaceAnnotation.h @@ -32,10 +32,10 @@ #include #include -extern "C" -{ + + #include "colortab.h" -} + class vtkLookupTable; class vtkRGBAColorTransferFunction; diff --git a/freeview/SurfaceLabel.h b/freeview/SurfaceLabel.h index 64b52d991a8..bf1b0afe4f0 100644 --- a/freeview/SurfaceLabel.h +++ b/freeview/SurfaceLabel.h @@ -33,10 +33,10 @@ #include #include -extern "C" -{ + + #include "label.h" -} + class LayerSurface; class vtkRGBAColorTransferFunction; diff --git a/freeview/SurfaceOverlay.cpp b/freeview/SurfaceOverlay.cpp index 5bcaa6197ae..9d9571cc7a6 100644 --- a/freeview/SurfaceOverlay.cpp +++ b/freeview/SurfaceOverlay.cpp @@ -39,10 +39,10 @@ #include "LayerMRI.h" #include "MyUtils.h" -extern "C" -{ + + #include "utils.h" -} + SurfaceOverlay::SurfaceOverlay ( LayerSurface* surf ) : QObject(), diff --git a/freeview/SurfaceOverlay.h b/freeview/SurfaceOverlay.h index b16942c4c23..2b5ee61561a 100644 --- a/freeview/SurfaceOverlay.h +++ b/freeview/SurfaceOverlay.h @@ -32,10 +32,10 @@ #include #include -extern "C" -{ + + #include "mri.h" -} + class vtkLookupTable; class vtkRGBAColorTransferFunction; diff --git a/freeview/SurfaceSpline.h b/freeview/SurfaceSpline.h index 7383447c6ce..e888effce98 100644 --- a/freeview/SurfaceSpline.h +++ b/freeview/SurfaceSpline.h @@ -5,11 +5,11 @@ #include #include "vtkSmartPointer.h" -extern "C" -{ + + #include "mri.h" #include "colortab.h" -} + class vtkActor; class LayerSurface; diff --git a/freeview/VolumeFilter.cpp b/freeview/VolumeFilter.cpp index 0678ba70264..27cb27dbfb9 100644 --- a/freeview/VolumeFilter.cpp +++ b/freeview/VolumeFilter.cpp @@ -31,10 +31,10 @@ #include "MyVTKUtils.h" #include -extern "C" -{ + + #include "utils.h" -} + VolumeFilter::VolumeFilter( LayerMRI* input, LayerMRI* output, QObject* parent ) : QObject( parent ), diff --git a/freeview/VolumeFilter.h b/freeview/VolumeFilter.h index f3cd3a8e480..9b091f69fb0 100644 --- a/freeview/VolumeFilter.h +++ b/freeview/VolumeFilter.h @@ -29,10 +29,10 @@ #include #include "CommonDataStruct.h" -extern "C" -{ + + #include "mri.h" -} + class LayerMRI; class QTimer; diff --git a/freeview/VolumeFilterClose.cpp b/freeview/VolumeFilterClose.cpp index b17092ce045..36d01e417de 100644 --- a/freeview/VolumeFilterClose.cpp +++ b/freeview/VolumeFilterClose.cpp @@ -29,10 +29,10 @@ #include #include "ProgressCallback.h" -extern "C" -{ + + #include "utils.h" -} + VolumeFilterClose::VolumeFilterClose( LayerMRI* input, LayerMRI* output, QObject* parent ) : VolumeFilter( input, output, parent ) diff --git a/freeview/VolumeFilterConvolve.cpp b/freeview/VolumeFilterConvolve.cpp index 2d3f49f7a42..2a18103643e 100644 --- a/freeview/VolumeFilterConvolve.cpp +++ b/freeview/VolumeFilterConvolve.cpp @@ -30,10 +30,10 @@ #include #include "ProgressCallback.h" -extern "C" -{ + + #include "utils.h" -} + VolumeFilterConvolve::VolumeFilterConvolve( LayerMRI* input, LayerMRI* output, QObject* parent ) : VolumeFilter( input, output, parent ), diff --git a/freeview/VolumeFilterDilate.cpp b/freeview/VolumeFilterDilate.cpp index 48b0ed3ec09..a5b315afa64 100644 --- a/freeview/VolumeFilterDilate.cpp +++ b/freeview/VolumeFilterDilate.cpp @@ -29,10 +29,10 @@ #include #include "ProgressCallback.h" -extern "C" -{ + + #include "utils.h" -} + VolumeFilterDilate::VolumeFilterDilate( LayerMRI* input, LayerMRI* output, QObject* parent ) : VolumeFilter( input, output, parent ) diff --git a/freeview/VolumeFilterErode.cpp b/freeview/VolumeFilterErode.cpp index bd3fb9336d2..fdd395abf20 100644 --- a/freeview/VolumeFilterErode.cpp +++ b/freeview/VolumeFilterErode.cpp @@ -29,10 +29,10 @@ #include #include "ProgressCallback.h" -extern "C" -{ + + #include "utils.h" -} + VolumeFilterErode::VolumeFilterErode( LayerMRI* input, LayerMRI* output, QObject* parent ) : VolumeFilter( input, output, parent ) diff --git a/freeview/VolumeFilterMean.cpp b/freeview/VolumeFilterMean.cpp index 1eccfc2a04e..a529743b747 100644 --- a/freeview/VolumeFilterMean.cpp +++ b/freeview/VolumeFilterMean.cpp @@ -29,10 +29,10 @@ #include #include "ProgressCallback.h" -extern "C" -{ + + #include "utils.h" -} + VolumeFilterMean::VolumeFilterMean( LayerMRI* input, LayerMRI* output, QObject* parent ) : VolumeFilter( input, output, parent ) diff --git a/freeview/VolumeFilterOpen.cpp b/freeview/VolumeFilterOpen.cpp index aae02eb16c4..b1a9d84454d 100644 --- a/freeview/VolumeFilterOpen.cpp +++ b/freeview/VolumeFilterOpen.cpp @@ -29,10 +29,10 @@ #include #include "ProgressCallback.h" -extern "C" -{ + + #include "utils.h" -} + VolumeFilterOpen::VolumeFilterOpen( LayerMRI* input, LayerMRI* output, QObject* parent ) : VolumeFilter( input, output, parent ) diff --git a/freeview/main.cpp b/freeview/main.cpp index 4d2c40af07e..ff5348fd44f 100644 --- a/freeview/main.cpp +++ b/freeview/main.cpp @@ -39,11 +39,11 @@ #include "error.h" #include #include -extern "C" -{ + + #include "fsinit.h" #include "chklc.h" -} + const char* Progname; diff --git a/fslutils/fsl_label2voxel.cpp b/fslutils/fsl_label2voxel.cpp index d2a6282d61a..ac529a89754 100644 --- a/fslutils/fsl_label2voxel.cpp +++ b/fslutils/fsl_label2voxel.cpp @@ -32,11 +32,11 @@ #include #include -extern "C" { + #include "mri.h" #include "macros.h" const char *Progname="fsl_label2voxel"; -} + using namespace std; diff --git a/hiam_make_surfaces/CMakeLists.txt b/hiam_make_surfaces/CMakeLists.txt index 64285333fa9..d8e2a2077a6 100644 --- a/hiam_make_surfaces/CMakeLists.txt +++ b/hiam_make_surfaces/CMakeLists.txt @@ -2,7 +2,7 @@ project(hiam_make_surfaces) include_directories(${FS_INCLUDE_DIRS}) -add_executable(hiam_make_surfaces hiam_make_surfaces.c) +add_executable(hiam_make_surfaces hiam_make_surfaces.cpp) target_link_libraries(hiam_make_surfaces utils) install(TARGETS hiam_make_surfaces DESTINATION bin) diff --git a/hiam_make_surfaces/hiam_make_surfaces.c b/hiam_make_surfaces/hiam_make_surfaces.cpp similarity index 100% rename from hiam_make_surfaces/hiam_make_surfaces.c rename to hiam_make_surfaces/hiam_make_surfaces.cpp diff --git a/hiam_make_template/CMakeLists.txt b/hiam_make_template/CMakeLists.txt index ba22bf8199e..c78ab605254 100644 --- a/hiam_make_template/CMakeLists.txt +++ b/hiam_make_template/CMakeLists.txt @@ -2,7 +2,7 @@ project(hiam_make_template) include_directories(${FS_INCLUDE_DIRS}) -add_executable(hiam_make_template hiam_make_template.c) +add_executable(hiam_make_template hiam_make_template.cpp) target_link_libraries(hiam_make_template utils) install(TARGETS hiam_make_template DESTINATION bin) diff --git a/hiam_make_template/hiam_make_template.c b/hiam_make_template/hiam_make_template.cpp similarity index 94% rename from hiam_make_template/hiam_make_template.c rename to hiam_make_template/hiam_make_template.cpp index b35e992b087..945201b7fda 100644 --- a/hiam_make_template/hiam_make_template.c +++ b/hiam_make_template/hiam_make_template.cpp @@ -52,27 +52,8 @@ const char *Progname ; static int which_norm = NORM_MEAN; -#if 0 -static char *surface_names[] = { - "inflated", - "smoothwm", - "smoothwm" - } ; - -static char *curvature_names[] = { - NULL, - "sulc", - NULL - } ; -#else -static char *surface_names[] = { - "hippocampus" - } ; - -static char *curvature_names[] = { - "hippocampus.curv" - } ; -#endif +static const char *surface_names[] = {"hippocampus"}; +static const char *curvature_names[] = {"hippocampus.curv"}; #define IMAGES_PER_SURFACE 3 /* mean, variance, and dof */ #define SURFACES sizeof(curvature_names) / sizeof(curvature_names[0]) diff --git a/hiam_register/CMakeLists.txt b/hiam_register/CMakeLists.txt index a28f01a58c3..833cd389f0d 100644 --- a/hiam_register/CMakeLists.txt +++ b/hiam_register/CMakeLists.txt @@ -2,7 +2,7 @@ project(hiam_register) include_directories(${FS_INCLUDE_DIRS}) -add_executable(hiam_register hiam_register.c) +add_executable(hiam_register hiam_register.cpp) target_link_libraries(hiam_register utils) install(TARGETS hiam_register DESTINATION bin) diff --git a/hiam_register/hiam_register.c b/hiam_register/hiam_register.cpp similarity index 99% rename from hiam_register/hiam_register.c rename to hiam_register/hiam_register.cpp index 87857cb6132..f0b6c98e00b 100644 --- a/hiam_register/hiam_register.c +++ b/hiam_register/hiam_register.cpp @@ -465,12 +465,11 @@ mrisRegister(MRI_SURFACE *mris, MRI_SP *mrisp_template, MRI_SP *mrisp ; char fname[STRLEN], base_name[STRLEN], path[STRLEN] ; double base_dt ; - struct timeb start ; static int first = 1 ; if (IS_QUADRANGULAR(mris)) MRISremoveTriangleLinks(mris) ; - TimerStart(&start) ; + Timer start; MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ; FileNamePath(mris->fname, path) ; sprintf(base_name, "%s/%s.%s", path, @@ -667,7 +666,7 @@ mrisRegister(MRI_SURFACE *mris, MRI_SP *mrisp_template, #endif MRISPfree(&parms->mrisp) ; MRISPfree(&parms->mrisp_template) ; - msec = TimerStop(&start) ; + msec = start.milliseconds() ; if (Gdiag & DIAG_SHOW) fprintf(stdout, "registration took %2.2f hours\n", (float)msec/(1000.0f*60.0f*60.0f)); diff --git a/hipsstubs/CMakeLists.txt b/hipsstubs/CMakeLists.txt deleted file mode 100644 index aae4209b1c2..00000000000 --- a/hipsstubs/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -project(hipsstubs) - -include_directories(${FS_INCLUDE_DIRS}) - -set(SOURCES hipsrepl.c hipsstubs.c) - -add_library(hipsstubs STATIC ${SOURCES}) diff --git a/hipsstubs/hipsrepl.c b/hipsstubs/hipsrepl.c deleted file mode 100644 index dfa64f43e9f..00000000000 --- a/hipsstubs/hipsrepl.c +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file hipsrepl.c - * @brief replacement routines for some hips functionality - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:08 $ - * $Revision: 1.7 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/*----------------------------------------------------- - INCLUDE FILES --------------------------------------------------------*/ -#include -#include -#include -#include -#include -#include -#include /* for SEEK_ constants */ - -#include "hmem.h" -#include - -#include "hips.h" - -#include "error.h" - -#include "image.h" -int -init_header(IMAGE *I,char *onm,char *snm,int nfr,char *odt,int rw,int cl,int pfmt,int nc,char *desc) { - int bytes ; - - I->num_frame = nfr ; - I->orows = I->rows = rw ; - I->ocols = I->cols = cl ; - I->pixel_format = pfmt ; - bytes = rw*cl*nfr ; - switch (pfmt) { - default: - case PFBYTE: - I->sizepix = sizeof(char) ; - break ; - case PFFLOAT: - I->sizepix = sizeof(float) ; - break ; - case PFDOUBLE: - I->sizepix = sizeof(double) ; - break ; - case PFINT: - I->sizepix = sizeof(int) ; - break ; - case PFSHORT: - I->sizepix = sizeof(short) ; - break ; - case PFRGB: - case PFBGR: - I->sizepix = 3*sizeof(byte); - break; - case PFRGBZ: - case PFZRGB: - case PFBGRZ: - case PFZBGR: - I->sizepix = 4*sizeof(byte); - break; - case PFSTEREO: - I->sizepix = sizeof(byte); - break; - case PFINTPYR: - I->sizepix = sizeof(int); - break; - case PFFLOATPYR: - I->sizepix = sizeof(float); - break; - } - bytes *= I->sizepix ; - I->numpix = I->rows * I->cols ; - I->sizeimage = I->numpix * I->sizepix ; - I->firstpix = I->image ; - I->image = (byte *)calloc(bytes, sizeof(char)) ; - if (!I->image) - ErrorExit(ERROR_NOMEMORY, "init_header: could not allocate %d bytes", - bytes) ; - - return(NO_ERROR) ; -} -int -h_copy(IMAGE *Isrc, IMAGE *Idst) { - int bytes ; - - bytes = Isrc->numpix * Isrc->sizepix ; - memmove(Idst->image, Isrc->image, bytes) ; - return(NO_ERROR) ; -} -int -free_header(IMAGE *I) { - if (I->image) { - free(I->image) ; - } - free(I) ; - return(0) ; -} - diff --git a/hipsstubs/hipsstubs.c b/hipsstubs/hipsstubs.c deleted file mode 100644 index 3f7d2540f4e..00000000000 --- a/hipsstubs/hipsstubs.c +++ /dev/null @@ -1,330 +0,0 @@ -/** - * @file hipsstubs.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.11 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#include -#include - -#include "error.h" - -#if 0 -/* wrote replacements for these (in hipsrepl.c) */ -int init_header(void) ; -int init_header(void) { - return(-1); -} -int h_copy(void) ; -int h_copy(void) { - return(-1); -} -int free_header(void) ; -int free_header(void) { - return(-1); -} -#endif - -#if 1 -int perr(void) ; -int perr(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_canny(void) ; -int h_canny(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_enlarge(void) ; -int h_enlarge(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_reduce(void) ; -int h_reduce(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_invert(void) ; -int h_invert(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -#include -int h_tob(void) ; -int h_tob(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_minmax(void) ; -int h_minmax(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_linscale(void) ; -int h_linscale(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int update_header(void) ; -int update_header(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int free_hdrcon(void) ; -int free_hdrcon(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int *memalloc(size_t, size_t) ; -int *memalloc(size_t a, size_t b) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return (int*)(calloc(a,b)); -} -int *halloc(size_t a, size_t b) ; -int *halloc(size_t a, size_t b) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return (int*)(calloc(a,b)) ; -} -int fwrite_header(void) ; -int fwrite_header(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int fwrite_image(void) ; -int fwrite_image(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int fread_header(void) ; -int fread_header(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int fread_image(void) ; -int fread_image(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_tof(void) ; -int h_tof(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_toc(void) ; -int h_toc(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_fourtr(void) ; -int h_fourtr(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_invfourtr(void) ; -int h_invfourtr(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_divscale(void) ; -int h_divscale(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_mul(void) ; -int h_mul(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_flipquad(void) ; -int h_flipquad(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_softthresh(void) ; -int h_softthresh(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_tod(void) ; -int h_tod(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_todc(void) ; -int h_todc(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_toi(void) ; -int h_toi(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_mulscale(void) ; -int h_mulscale(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_div(void) ; -int h_div(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_add(void) ; -int h_add(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_diff(void) ; -int h_diff(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int alloc_histo(void) ; -int alloc_histo(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_clearhisto(void) ; -int h_clearhisto(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_histo(void) ; -int h_histo(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_histoeq(void) ; -int h_histoeq(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_pixmap(void) ; -int h_pixmap(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_entropycnt(void) ; -int h_entropycnt(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int h_entropy(void) ; -int h_entropy(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -#if 0 -unsigned char *hmalloc(unsigned long i) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(0) ; -} -int WinShowImage(void) ; -int WinShowImage(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int WinSetName(void) ; -int WinSetName(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int WinCreate(void) ; -int WinCreate(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -#endif -int h_median(void) ; -int h_median(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} -int hformatname(void) ; -int hformatname(void) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(-1); -} - -#if 1 -int hipserrno = 0 ; - -int hips_hclip = 0 ; -int hips_lclip = 0 ; -int hips_oldhdr = 0 ; -int hips_cplxtor = 0 ; -int hips_rtocplx = 0 ; -#endif - -void MachThreadInit(void) ; -void MachThreadInit(void) {} -void MachThreadGetTid(void) ; -void MachThreadGetTid(void) {} -void MachThreadKill(void) ; -void MachThreadKill(void) {} -void MachThreadStart(void) ; -void MachThreadStart(void) {} -void MachThreadSuspend(void) ; -void MachThreadSuspend(void) {} -void MachThreadResume(void) ; -void MachThreadResume(void) {} -void MachThreadSleep(void) ; -void MachThreadSleep(void) {} -void MachThreadYield(void) ; -void MachThreadYield(void) {} -void MachThreadExit(void) ; -void MachThreadExit(void) {} - - -#endif -/* getparam(hd,name,fmt,count,valuepointer) */ - -int getparam(void *hd, ...) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(0) ; -} -int setparam(void *hd, ...) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(0) ; -} -void *findparam(void *hd, char *name) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(NULL) ; -} -int clearparam(void *hd, char *name) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(0) ; -} - - -int h_applylut(void *hdi,void *hdo,int count,unsigned char *lut) { - ErrorExit(ERROR_UNSUPPORTED, "HIPS unsupported") ; - return(0) ; -} - - - - diff --git a/histo_compute_joint_density/CMakeLists.txt b/histo_compute_joint_density/CMakeLists.txt index 41a9399b515..db5cce734b5 100644 --- a/histo_compute_joint_density/CMakeLists.txt +++ b/histo_compute_joint_density/CMakeLists.txt @@ -2,7 +2,7 @@ project(histo_compute_joint_density) include_directories(${FS_INCLUDE_DIRS}) -add_executable(histo_compute_joint_density histo_compute_joint_density.c) +add_executable(histo_compute_joint_density histo_compute_joint_density.cpp) target_link_libraries(histo_compute_joint_density utils) install(TARGETS histo_compute_joint_density DESTINATION bin) diff --git a/histo_compute_joint_density/histo_compute_joint_density.c b/histo_compute_joint_density/histo_compute_joint_density.cpp similarity index 97% rename from histo_compute_joint_density/histo_compute_joint_density.c rename to histo_compute_joint_density/histo_compute_joint_density.cpp index ceaac8bca58..314d1eaf33a 100644 --- a/histo_compute_joint_density/histo_compute_joint_density.c +++ b/histo_compute_joint_density/histo_compute_joint_density.cpp @@ -112,7 +112,7 @@ main(int argc, char *argv[]) { MRIvalRange(mri1, &min_val1, &max_val1) ; valid1_min = MAX(valid1_min, min_val1) ; valid1_max = MIN(valid1_max, max_val1) ; - valid1 = calloc(256, sizeof(int)) ; + valid1 = (int *)calloc(256, sizeof(int)) ; for (i = valid1_min ; i <= valid1_max ; i++) valid1[i] = 1 ; @@ -125,7 +125,7 @@ main(int argc, char *argv[]) { mri2 = mri_tmp ; MRIsegmentFree(&mriseg) ; } else { - valid1 = calloc(256, sizeof(int)) ; + valid1 = (int *)calloc(256, sizeof(int)) ; for (i = 0 ; i <= 255 ; i++) valid1[i] = 1 ; } @@ -134,11 +134,11 @@ main(int argc, char *argv[]) { MRIvalRange(mri2, &min_val2, &max_val2) ; valid2_min = MAX(valid2_min, min_val2) ; valid2_max = MIN(valid2_max, max_val2) ; - valid2 = calloc(256, sizeof(int)) ; + valid2 = (int *)calloc(256, sizeof(int)) ; for (i = valid2_min ; i <= valid2_max ; i++) valid2[i] = 1 ; } else { - valid2 = calloc(256, sizeof(int)) ; + valid2 = (int *)calloc(256, sizeof(int)) ; for (i = 0 ; i <= 255 ; i++) valid2[i] = 1 ; } diff --git a/histo_fix_topology/CMakeLists.txt b/histo_fix_topology/CMakeLists.txt index e217bcf292f..1cbe1231d77 100644 --- a/histo_fix_topology/CMakeLists.txt +++ b/histo_fix_topology/CMakeLists.txt @@ -2,7 +2,7 @@ project(histo_fix_topology) include_directories(${FS_INCLUDE_DIRS}) -add_executable(histo_fix_topology histo_fix_topology.c) +add_executable(histo_fix_topology histo_fix_topology.cpp) target_link_libraries(histo_fix_topology utils) install(TARGETS histo_fix_topology DESTINATION bin) diff --git a/histo_fix_topology/histo_fix_topology.c b/histo_fix_topology/histo_fix_topology.cpp similarity index 100% rename from histo_fix_topology/histo_fix_topology.c rename to histo_fix_topology/histo_fix_topology.cpp diff --git a/histo_register_block/CMakeLists.txt b/histo_register_block/CMakeLists.txt index 8f46cfd8d73..3282a25de02 100644 --- a/histo_register_block/CMakeLists.txt +++ b/histo_register_block/CMakeLists.txt @@ -2,7 +2,7 @@ project(histo_register_block) include_directories(${FS_INCLUDE_DIRS}) -add_executable(histo_register_block histo_register_block.c) +add_executable(histo_register_block histo_register_block.cpp) target_link_libraries(histo_register_block utils) install(TARGETS histo_register_block DESTINATION bin) diff --git a/histo_register_block/histo_register_block.c b/histo_register_block/histo_register_block.cpp similarity index 100% rename from histo_register_block/histo_register_block.c rename to histo_register_block/histo_register_block.cpp diff --git a/histo_segment/CMakeLists.txt b/histo_segment/CMakeLists.txt index 6c5239a0f1c..cf1271c8937 100644 --- a/histo_segment/CMakeLists.txt +++ b/histo_segment/CMakeLists.txt @@ -2,7 +2,7 @@ project(histo_segment) include_directories(${FS_INCLUDE_DIRS}) -add_executable(histo_segment histo_segment.c) +add_executable(histo_segment histo_segment.cpp) target_link_libraries(histo_segment utils) install(TARGETS histo_segment DESTINATION bin) diff --git a/histo_segment/histo_segment.c b/histo_segment/histo_segment.cpp similarity index 100% rename from histo_segment/histo_segment.c rename to histo_segment/histo_segment.cpp diff --git a/histo_synthesize/CMakeLists.txt b/histo_synthesize/CMakeLists.txt index ac5cda13d4d..86f77f78628 100644 --- a/histo_synthesize/CMakeLists.txt +++ b/histo_synthesize/CMakeLists.txt @@ -2,7 +2,7 @@ project(histo_synthesize) include_directories(${FS_INCLUDE_DIRS}) -add_executable(histo_synthesize histo_synthesize.c) +add_executable(histo_synthesize histo_synthesize.cpp) target_link_libraries(histo_synthesize utils) install(TARGETS histo_synthesize DESTINATION bin) diff --git a/histo_synthesize/histo_synthesize.c b/histo_synthesize/histo_synthesize.cpp similarity index 99% rename from histo_synthesize/histo_synthesize.c rename to histo_synthesize/histo_synthesize.cpp index cc512c2a209..09721743c2a 100644 --- a/histo_synthesize/histo_synthesize.c +++ b/histo_synthesize/histo_synthesize.cpp @@ -100,7 +100,7 @@ main(int argc, char *argv[]) { char **av ; int ac, nargs ; int msec, minutes, seconds ; - struct timeb start ; + Timer start ; MRI *mri, *histo, *hsynth, *mri_train_src = NULL, *mri_train_dst = NULL ; setRandomSeed(-1L) ; @@ -115,7 +115,7 @@ main(int argc, char *argv[]) { ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; - TimerStart(&start) ; + start.reset() ; ac = argc ; av = argv ; @@ -172,7 +172,7 @@ main(int argc, char *argv[]) { hsynth = HISTOsynthesize(mri, histo, test_slice, train_slice, NULL, wsize, flags, argv[3], mri_train_src, mri_train_dst) ; printf("writing output to %s\n", argv[3]) ; MRIwrite(hsynth, argv[3]) ; - msec = TimerStop(&start) ; + msec = start.milliseconds() ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; diff --git a/include/DICOMRead.h b/include/DICOMRead.h index d238f415839..e1e0e7a1621 100644 --- a/include/DICOMRead.h +++ b/include/DICOMRead.h @@ -27,10 +27,10 @@ #define _DICOMRead_H -#include "dicom/dicom.h" -#include "dicom/lst.h" -#include "dicom/dicom_objects.h" -#include "dicom/condition.h" +#include "dicom.h" +#include "lst.h" +#include "dicom_objects.h" +#include "condition.h" #define NUMBEROFTAGS 24 #define SHORTSIZE 16 diff --git a/include/FsgdfPlot.h b/include/FsgdfPlot.h index f4cfae10f5d..7dd722cb9b9 100644 --- a/include/FsgdfPlot.h +++ b/include/FsgdfPlot.h @@ -25,7 +25,7 @@ #ifndef FSGDFPLOT_H #define FSGDFPLOT_H -extern "C" { + #include "tix.h" #include "fsgdf_wrap.h" @@ -49,7 +49,7 @@ extern "C" { #ifndef Tix_SafeInit int Tix_SafeInit ( Tcl_Interp* interp ); #endif -} + class FsgdfPlot { diff --git a/include/MRISOBBTree.h b/include/MRISOBBTree.h index 677bf8c2adb..3867e088367 100644 --- a/include/MRISOBBTree.h +++ b/include/MRISOBBTree.h @@ -27,25 +27,11 @@ #ifndef MRISOBBTree_h #define MRISOBBTree_h -// The following is usable from C -#ifdef __cplusplus -extern "C" -{ -#endif - #include "mri.h" #include "mrisurf.h" #include "diag.h" #include "error.h" -#ifdef __cplusplus -} -#endif - - -// C++ portion starts here -#ifdef __cplusplus - #include #include #include @@ -889,5 +875,3 @@ class MRISOBBTree }; #endif -#endif - diff --git a/include/MRISdistancefield.h b/include/MRISdistancefield.h index 7c29a08ee47..48f9681e4d3 100644 --- a/include/MRISdistancefield.h +++ b/include/MRISdistancefield.h @@ -28,24 +28,11 @@ #ifndef mrisdistancefield_h #define mrisdistancefield_h -// The following is usable from C -#ifdef __cplusplus -extern "C" -{ -#endif - #include "mri.h" #include "mrisurf.h" #include "diag.h" - MRI *MRISdistancefield(MRIS *mris, MRI *mri_tmp, double max_distance, int signedfield); - -#ifdef __cplusplus -} -#endif - -// C++ portion starts here -#ifdef __cplusplus +MRI *MRISdistancefield(MRIS *mris, MRI *mri_tmp, double max_distance, int signedfield); #include #include "utilsmath.h" @@ -187,5 +174,4 @@ class MRISDistanceField }; #endif -#endif diff --git a/include/annotation.h b/include/annotation.h index 863227ca55e..28eb7dea807 100644 --- a/include/annotation.h +++ b/include/annotation.h @@ -27,6 +27,8 @@ #ifndef ANNOTATION_H #define ANNOTATION_H +#include +#include #ifdef ANNOTATION_SRC char *annotation_table_file = NULL; @@ -36,8 +38,8 @@ extern char *annotation_table_file; int read_annotation_table(void) ; int read_named_annotation_table(char *fname) ; -char* index_to_name(int index); -char* annotation_to_name(int annotation, int *pindex) ; +const char* index_to_name(int index); +const char* annotation_to_name(int annotation, int *pindex) ; int annotation_to_index(int annotation) ; int print_annotation_table(FILE *fp); int print_annotation_colortable(FILE *fp); @@ -46,7 +48,7 @@ LABEL* annotation2label(int annotid, MRIS *Surf); int set_atable_from_ctable(COLOR_TABLE *pct); int MRISdivideAnnotation(MRI_SURFACE *mris, int *nunits) ; int MRISdivideAnnotationUnit(MRI_SURFACE *mris, int annot, int nunits) ; -int MRISmergeAnnotations(MRIS *mris, int nparcs, char **parcnames, char *newparcname); +int MRISmergeAnnotations(MRIS *mris, int nparcs, std::vector parcnames, const char *newparcname); MRI* MRISannot2seg(MRIS *surf, int base); MRI* MRISannot2border(MRIS *surf); int MRISaparc2lobes(MRIS *surf, int a_lobeDivisionType); diff --git a/include/argparse.hpp b/include/argparse.h similarity index 96% rename from include/argparse.hpp rename to include/argparse.h index eb97d4a3dcc..151e573e7c4 100644 --- a/include/argparse.hpp +++ b/include/argparse.h @@ -2,8 +2,8 @@ // by Hilton Bristow, which is developed with the BSD 3-Clause License: // https://github.com/hbristow/argparse -#ifndef ARGPARSE_HPP -#define ARGPARSE_HPP +#ifndef ARGPARSE_H +#define ARGPARSE_H #if __cplusplus >= 201103L #include @@ -17,7 +17,7 @@ typedef std::map IndexMap; #include #include -#include "log.hpp" +#include "log.h" /*! @@ -213,7 +213,7 @@ class ArgumentParser { template T retrieve(const String& name) { String unstripped = unstrip(name); - if (index.count(unstripped) == 0) fs_fatal(1) << "'" << unstripped << "' is not a known argument"; + if (index.count(unstripped) == 0) logFatal(1) << "'" << unstripped << "' is not a known argument"; size_t N = index[unstripped]; T retrieved{}; // try to cast the arguments @@ -229,11 +229,11 @@ class ArgumentParser { fulltype = "std::vector<" + arguments[N].typeName() + ">"; sentence_starter = "These inputs are"; } - fs_fatal(1) << "invalid cast of argument '" << name << "'. " << sentence_starter << " of type '" - << arguments[N].typeName() << "' and should be retrieved via " << fs::term::dim() - << "retrieve<" << fulltype << ">(\"" << name << "\")" << fs::term::reset() << ". " + logFatal(1) << "invalid cast of argument '" << name << "'. " << sentence_starter << " of type '" + << arguments[N].typeName() << "' and should be retrieved via " << term::dim() + << "retrieve<" << fulltype << ">(\"" << name << "\")" << term::reset() << ". " << "To change the expected type, modify the call to " - << fs::term::dim() << "addArgument()" << fs::term::reset(); + << term::dim() << "addArgument()" << term::reset(); } return retrieved; } diff --git a/include/art1.h b/include/art1.h deleted file mode 100644 index 1481226017e..00000000000 --- a/include/art1.h +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @file art1.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)art1.h 1.3 - 8/10/95 -*/ -/*---------------------------------------------------------------------- - - File Name: art1.h - - Description: - - $Header: /space/repo/1/dev/dev/include/art1.h,v 1.3 2011/03/02 00:04:09 nicks Exp $ - $Log: art1.h,v $ - Revision 1.3 2011/03/02 00:04:09 nicks - ENH: new license header mods - - Revision 1.2 2006/12/29 02:08:59 nicks - added license header; ran astyle to set to kr and ansi code styling - - Revision 1.1 1997/03/18 18:17:34 fischl - Initial revision - -----------------------------------------------------------------------*/ - -#ifndef ART1_H -#define ART1_H - - -#include "machine.h" - -typedef struct -{ - int ninputs ; /* # of inputs */ - int noutputs ; /* # of outputs committed so far */ - int max_f2 ; /* size of f2 */ - double beta ; /* for weight initialization */ - double rho ; /* vigilance */ - int class ; /* class of previous recognition */ - double *scratch ; /* for scratch calculations of intersection */ - double *f0 ; /* points to inputs (provided by caller) */ - double *f1 ; /* input vector */ - double *f2 ; - double huge *zj ; /* top down weights */ - int *flags ; /* is node committed, reset */ -} -ART1 ; - -#define ART1_RESET 0x0001 -#define ART1_COMMITTED 0x0002 - -ART1 *Art1Alloc(int ninputs, int noutputs, double rho) ; -ART1 *Art1Read(char *fname) ; -int Art1Write(ART1 *art1, char *fname) ; -int Art1Free(ART1 **art1) ; -int Art1Process(ART1 *art, double *I) ; -int Art1Reset(ART1 *art1) ; -int Art1SetParms(ART1 *art, double rho) ; - - -#endif diff --git a/include/artmap.h b/include/artmap.h deleted file mode 100644 index 56b0c8094b5..00000000000 --- a/include/artmap.h +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file artmap.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/*---------------------------------------------------------------------- - - File Name: artmap.h - - Description: - - $Header: /space/repo/1/dev/dev/include/artmap.h,v 1.3 2011/03/02 00:04:09 nicks Exp $ - $Log: artmap.h,v $ - Revision 1.3 2011/03/02 00:04:09 nicks - ENH: new license header mods - - Revision 1.2 2006/12/29 02:08:59 nicks - added license header; ran astyle to set to kr and ansi code styling - - Revision 1.1 1997/03/18 18:17:39 fischl - Initial revision - -----------------------------------------------------------------------*/ - -#ifndef ARTMAP_H -#define ARTMAP_H - - -#include "machine.h" - -typedef struct -{ - int ninputs ; /* # of inputs */ - int noutputs ; /* # of outputs (size of map field) */ - int max_f2 ; /* size of f2 */ - int f2nodes ; /* actual # of f2 nodes committed */ - int ncommitted ; /* # of committed nodes */ - int learn ; /* in learn mode */ - double beta ; /* for weight initialization */ - double rho ; /* vigilance */ - double rho_bar; /* baseline vigilance */ - int class ; /* class of previous recognition */ - double *scratch ; /* for scratch calculations of intersection */ - double *f0 ; /* points to inputs (provided by caller) */ - double *f1 ; /* input vector */ - double *f2 ; - double huge *zj ; /* top down weights */ - int *flags ; /* is node committed, reset */ - int huge *w ; /* f2->map weights */ - double match ; /* for use in match tracking */ -} -ARTMAP ; - -#define ARTMAP_RESET 0x0001 -#define ARTMAP_COMMITTED 0x0002 - -ARTMAP *ArtmapAlloc(int ninputs, int noutputs, double rho_bar, int max_f2) ; -ARTMAP *ArtmapRead(char *fname) ; -int ArtmapWrite(ARTMAP *artmap, char *fname) ; -int ArtmapFree(ARTMAP **artmap) ; -int ArtmapProcess(ARTMAP *artmap, double *I) ; -int ArtmapLearn(ARTMAP *artmap, double *I, int class) ; - - -#endif diff --git a/include/aseg_edit_svm.h b/include/aseg_edit_svm.h deleted file mode 100644 index b90a19edbbd..00000000000 --- a/include/aseg_edit_svm.h +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @file aseg_edit_svm.h - * @brief prototypes and structs for using SVMs to reclassify aseg voxels - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.2 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/*----------------------------------------------------- - INCLUDE FILES - -------------------------------------------------------*/ -#ifndef ASEG_EDIT_SVM_H -#define ASEG_EDIT_SVM_H - -#include "mri.h" -#include "voxlist.h" - -float **build_svm_training_data(VOXEL_LIST *vl_total, int target_label, - float *svm_classes, MRI **mri_smooth, - MRI **mri_grad, MRI **mri_laplacian, MRI *mri_dtrans, int wsize, int nscales); -float *build_svm_inputs_at_voxel(VOXEL_LIST *vl, int i, int target_label, - MRI **mri_smooth, MRI **mri_grad, MRI **mri_laplacian, MRI *mri_dtrans, - MRI *mri_dtrans_grad, - int wsize, int nscales, float *svm_inputs) ; - -#define NINPUTS(wsize, nscales) (4+(wsize*wsize*wsize)*nscales*(1+1)) // 3+1 = 3 grad components plus image intensity -#endif diff --git a/include/autoencoder.h b/include/autoencoder.h index c86ce9bc3eb..51f52eebcf6 100644 --- a/include/autoencoder.h +++ b/include/autoencoder.h @@ -36,7 +36,6 @@ extern int test ; #include "matrix.h" #include "voxlist.h" #include "transform.h" -#include "rbm.h" #ifndef SIGMOID #define SIGMOID(x) (1.0/(1.0+exp(-(x)))) diff --git a/include/backprop.h b/include/backprop.h deleted file mode 100644 index 565f41a0ea4..00000000000 --- a/include/backprop.h +++ /dev/null @@ -1,124 +0,0 @@ -/** - * @file backprop.h - * @brief back-propagation neural net - * - * backprop files can store multiple networks of varying size. In order to - * accomodate this, I mimic the tiff file structure with a header indicating - * the # of networks, and a pointer to the 1st one. Each one then starts with - * a pointer to the next network, or NULL for the last network in the file. - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.7 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#ifndef BACKPROP_H -#define BACKPROP_H - -#include "machine.h" - -typedef struct -{ - long32 nnets ; /* total # of nets in file */ - long32 magic ; /* magic # for identification */ - long32 first ; /* file offset of first net */ -} -BPFILE_HEADER ; - -#define BP_APPEND 0 -#define BP_WRITE 1 -#define BP_REWRITE 2 -#define BP_MAGIC 4242L - - -/* - for adaptive learning rate: If sse increases by more than ERROR_RATIO, - then update the step size according to: - - learning_rate = learning_rate * TRATE_DECREASE - - otherwise, if the sse decresed, the increase the step size by: - - learning_rate = learning_rate * TRATE_INCREASE. -*/ - - -#define BP_TRATE_DECREASE 0.7f -#define BP_TRATE_INCREASE 1.05f -#define BP_ERROR_RATIO 1.04f - -typedef struct -{ - int nunits ; /* # of neurons in layer */ - int ninputs ; /* # of inputs to this layer */ - float *x ; /* neuron activations */ - float *w ; /* neuron weights */ - float *biases ; /* neuron biases (thresholds) */ - float *db ; /* last bias change for momentum */ - float *deltas ; /* for training */ - float *dw ; /* last weight change for momentum */ -} -LAYER ; - -typedef struct -{ - int ninputs ; /* # of inputs */ - int noutputs ; /* # of outputs (size of map field) */ - int nhidden ; /* # of hidden layers */ - int learn ; /* in learn mode */ - float momentum ; /* momentum coefficient */ - float trate ; /* learning rate */ - float trate_up ; /* adaptive step size increase */ - float trate_down ; /* adaptive step size decrease */ - float error_ratio ; /* ratio of new/old sse for step size modification */ - int nepochs ; /* # of epochs of training */ - int ntrials ; /* # of trials of training in this epoch */ - float old_momentum ; /* original momentum parameter */ - int class ; /* class of previous recognition */ - LAYER hidden ; /* hidden layer */ - LAYER output ; /* output layer */ - float *mean_out ; /* mean output value */ - float *std_out ; /* standard deviation of output values */ - float *errors ; /* output errors */ - float sse ; /* sum squared error */ - int user_bytes ; /* # of bytes in user memory */ - char *user ; /* ad hoc memory for user to use */ -} -BACKPROP ; - -BACKPROP *BackpropAlloc(int ninputs, int noutputs, int nhidden, float alpha, - float trate, float *mean_out, float *std_out) ; -BACKPROP *BackpropCopy(BACKPROP *bp_src, BACKPROP *bp_dst) ; -int BackpropSetParms(BACKPROP *bp, float trate_up, float trate_down, - float error_rate) ; -int BackpropFileNumberOfNets(char *fname) ; -BACKPROP *BackpropRead(char *fname, int netno) ; -int BackpropWrite(BACKPROP *backprop, char *fname, int argc, char *argv[], - char *comments, int mode) ; -int BackpropFree(BACKPROP **backprop) ; -int BackpropProcess(BACKPROP *backprop, float *I) ; -float BackpropLearn(BACKPROP *backprop, float *inputs, float *targets) ; -float BackpropTrainEpoch(BACKPROP *bp, int ntrials, - int (*io_func)(float *inputs, float *targets, - int index, int ninputs, - int noutputs, void *user), - void *user) ; -float BackpropError(BACKPROP *bp, float *targets) ; -int BackpropErrorReset(BACKPROP *bp) ; -int BackpropEpochComplete(BACKPROP *bp) ; - -#endif diff --git a/include/base.h b/include/base.h index 1a16c8df99e..781f3ebcf01 100644 --- a/include/base.h +++ b/include/base.h @@ -40,12 +40,6 @@ #include "proto.h" // malloc is needed from here - -#if defined(__cplusplus) -extern "C" { -#endif - - extern const char *Progname; // various of the utility programs define this global variable to be their name @@ -145,13 +139,6 @@ static float squaref(float x) { return x*x; } #pragma GCC diagnostic ignored "-Wunused-function" static double squared(double x) { return x*x; } - typedef struct FloatXYZ { float x,y,z; } FloatXYZ; - - -#if defined(__cplusplus) -}; -#endif - diff --git a/include/canny.h b/include/canny.h deleted file mode 100644 index b5ba6379416..00000000000 --- a/include/canny.h +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file canny.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/***************************************************** - * Name: canny.h - *****************************************************/ -#ifndef CANNY_H - -#define NOEDGE 0 -#define POSSIBLE_EDGE 254 -#define EDGE 255 - -/*----------------*/ -/* CONVOLVE IMAGE */ -/*--------------- */ - -/* edge detection parameters */ -#define DEFAULT_SIGMA 1.0 -#define DEFAULT_WINDOWSIZE 9 -#define DEFAULT_LFRAC 0.5 -#define DEFAULT_HFRAC 0.9 - -/* POSSIBLE VALUES OF THE FILTERTYPE PARMETER */ - -#define NOSYMMETRY 0 -#define SYMMETRIC 1 -#define ANITSYMMETRIC 2 - -/* POSSIBLE VALUES OF THE BOUNDERY PARAMETER */ - -#define ZERO 0 /* ZEROES THE REGION OUTSIDE OF THE IMAGE */ -#define WRAP 1 /* THE FILTER IS CIRCULAR */ -#define MAKESMALL 2 /* RETURNS A SMALLER IMAGE. */ -#define EXTEND 3 /* EXTENDS THE BOUNDARY PIXELS */ -#define MASKIT 4 /* MASKS THE BOUNDARY TO ZERO */ - -/* POSSIBLE VALUES OF THE STATUS PARAMETER */ - -#define SUCCESS 1 /* SUCCESSFULL EXECUTION */ -#define NO_SUCH_FILTER 2 /* IF THE FILTER TYPE PARAMETER IS NOT ONE OF THE ALLOWED VALS. */ -#define EVENWINDOWSIZE 3 /* IF THE FILTER IS EVENSIZED */ -#define NOSUCHDIRECTION 4 /* Direction is not XDIR of YDIR */ -#define NOSUCHBOUNDERY 5 /* Nonexistant boundery option specified */ - -/* POSSIBLE VALUES OF THE DIRECTION PARAMETER */ - -#define XDIR 1 -#define YDIR 2 - -#include /* dng */ - -/* prototypes */ -void canny(int *magmax, int *hthresh, int *lthresh, int *image, int *xsize, int *ysize, short *shortim, - int *windowsize, double *sigma, int *bordermode, double *hfrac, double *lfrac, int *pflag, - short *gx, short *gy, short *mag, int *hist, int *histsize, unsigned char *nms, - unsigned char *edgemap, float *gm, float *gmp,short *temp) ; -void cleanup(unsigned char *map, int xsize, int ysize) ; -void find_edges(unsigned char *map, short *mag, int xsize, int ysize, int maxmag, float hpixel_fraction, - float lpixel_fraction, int *hgram, int hsize, int *actual_hthresh, int *actual_lthresh); -void follow_edges(unsigned char *edgemapptr, short *edgemagptr) ; -void clear_borders(unsigned char *charimage, int xsize, int ysize) ; -void gauss_filter(short *inimage, int inx, int iny, int direction, int boundary, int masksize, - float sigma, short *grad, int *outx, int *outy, - float *gmask, float *gprimemask, short *tempimage) ; -void copyimage(int *charimage, int ncols, int nrows, short *shortimage) ; -void thin(unsigned char *edges, int height, int width) ; - -int h_canny(struct header *Isrc, struct header *Idst, double sigma, - int mask_size,double lfrac,double hfrac,int dothin); /* dng */ - -#endif - - diff --git a/include/cdflib.h b/include/cdflib.h deleted file mode 100644 index 90ae663a368..00000000000 --- a/include/cdflib.h +++ /dev/null @@ -1,121 +0,0 @@ -/** - * @file cdflib.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef CDFLIB_H -#define CDFLIB_H - -double algdiv(double*,double*); -double alngam(double*); -double alnrel(double*); -double apser(double*,double*,double*,double*); -double basym(double*,double*,double*,double*); -double bcorr(double*,double*); -double betaln(double*,double*); -double bfrac(double*,double*,double*,double*,double*,double*); -void bgrat(double*,double*,double*,double*,double*,double*,int*i); -double bpser(double*,double*,double*,double*); -void bratio(double*,double*,double*,double*,double*,double*,int*); -double brcmp1(int*,double*,double*,double*,double*); -double brcomp(double*,double*,double*,double*); -double bup(double*,double*,double*,double*,int*,double*); -void cdfbet(int*,double*,double*,double*,double*,double*,double*, - int*,double*); -void cdfbin(int*,double*,double*,double*,double*,double*,double*, - int*,double*); -void cdfchi(int*,double*,double*,double*,double*,int*,double*); -void cdfchn(int*,double*,double*,double*,double*,double*,int*,double*); -void cdff(int*,double*,double*,double*,double*,double*,int*,double*); -void cdffnc(int*,double*,double*,double*,double*,double*,double*, - int*s,double*); -void cdfgam(int*,double*,double*,double*,double*,double*,int*,double*); -void cdfnbn(int*,double*,double*,double*,double*,double*,double*, - int*,double*); -void cdfnor(int*,double*,double*,double*,double*,double*,int*,double*); -void cdfpoi(int*,double*,double*,double*,double*,int*,double*); -void cdft(int*,double*,double*,double*,double*,int*,double*); -void cdftnc(int*,double*,double*,double*,double*,double*,int*,double*); -void cumbet(double*,double*,double*,double*,double*,double*); -void cumbin(double*,double*,double*,double*,double*,double*); -void cumchi(double*,double*,double*,double*); -void cumchn(double*,double*,double*,double*,double*); -void cumf(double*,double*,double*,double*,double*); -void cumfnc(double*,double*,double*,double*,double*,double*); -void cumgam(double*,double*,double*,double*); -void cumnbn(double*,double*,double*,double*,double*,double*); -void cumnor(double*,double*,double*); -void cumpoi(double*,double*,double*,double*); -void cumt(double*,double*,double*,double*); -void cumtnc(double*,double*,double*,double*,double*); -double devlpl(double [],int*,double*); -double dinvnr(double *p,double *q); -void dinvr(int*,double*,double*,unsigned long*,unsigned long*); -void dstinv(double*,double*,double*,double*,double*,double*, - double*); -double dt1(double*,double*,double*); -void dzror(int*,double*,double*,double*,double *, - unsigned long*,unsigned long*); -void dstzr(double *zxlo,double *zxhi,double *zabstl,double *zreltl); -double erf1(double*); -double erfc1(int*,double*); -double esum(int*,double*); -double exparg(int*); -double fpser(double*,double*,double*,double*); -double gam1(double*); -void gaminv(double*,double*,double*,double*,double*,int*); -double gamln(double*); -double gamln1(double*); -double Xgamm(double*); -void grat1(double*,double*,double*,double*,double*,double*); -void gratio(double*,double*,double*,double*,int*); -double gsumln(double*,double*); -double psi(double*); -double rcomp(double*,double*); -double rexp(double*); -double rlog(double*); -double rlog1(double*); -double spmpar(int*); -double stvaln(double*); -double fifdint(double); -double fifdmax1(double,double); -double fifdmin1(double,double); -double fifdsign(double,double); -long fifidint(double); -long fifmod(long,long); -void ftnstop(char*); -extern int ipmpar(int*); - -#if 0 -static void E0000(int,int*,double*,double*,unsigned long*, - unsigned long*,double*,double*,double*, - double*,double*,double*,double*); -static void E0001(int,int*,double*,double*,double*,double*, - unsigned long*,unsigned long*,double*,double*, - double*,double*); -#endif - -double sigf(float F, int df1, int df2) ; - -#endif diff --git a/include/chronometer.h b/include/chronometer.h index 74f853f35c7..08d5b186f7d 100644 --- a/include/chronometer.h +++ b/include/chronometer.h @@ -7,42 +7,31 @@ #ifndef CHRONOMETER_H #define CHRONOMETER_H -#if defined(__cplusplus) -extern "C" { -#endif - - // These two system libraries are required +// These two system libraries are required #include #include +//! Timer Datatype +typedef struct _Chronometer { + int running; //!< Whether the timer is running + float accTime; //!< Accumulated time for this timer (ms) + long nStarts; //!< Count of times this timer has been started + struct timeval tStart; //!< When this timer started +} Chronometer; - //! Timer Datatype - typedef struct _Chronometer { - int running; //!< Whether the timer is running - float accTime; //!< Accumulated time for this timer (ms) - long nStarts; //!< Count of times this timer has been started - struct timeval tStart; //!< When this timer started - } Chronometer; +// Prototypes +//! Initialises a timer +void InitChronometer( Chronometer *theChronometer ); +//! Starts a timer +void StartChronometer( Chronometer *theChronometer ); +//! Stops a timer +void StopChronometer( Chronometer *theChronometer ); +//! Resets a timer +void ResetChronometer( Chronometer *theChronometer ); +//! Gets the time for a timer in milliseconds +float GetChronometerValue( const Chronometer *theChronometer ); +//! Gets the average time per start +float GetAverageChronometerValue( const Chronometer *theChronometer ); - // Prototypes - - //! Initialises a timer - void InitChronometer( Chronometer *theChronometer ); - //! Starts a timer - void StartChronometer( Chronometer *theChronometer ); - //! Stops a timer - void StopChronometer( Chronometer *theChronometer ); - //! Resets a timer - void ResetChronometer( Chronometer *theChronometer ); - //! Gets the time for a timer in milliseconds - float GetChronometerValue( const Chronometer *theChronometer ); - //! Gets the average time per start - float GetAverageChronometerValue( const Chronometer *theChronometer ); - -#if defined(__cplusplus) -}; -#endif - - #endif diff --git a/include/cma.h b/include/cma.h index 5a3d8ce4388..7833fc0ebe8 100644 --- a/include/cma.h +++ b/include/cma.h @@ -28,11 +28,6 @@ #ifndef CMA_H #define CMA_H - -#if defined(__cplusplus) -extern "C" { -#endif - #include "stats.h" #include "mri2.h" @@ -656,10 +651,4 @@ MRI **MRIdilateSegWithinTT(MRI *seg, int nDils, COLOR_TABLE *ct, MRI **r); SEGSTAT *Seg2NbrNonBrain(MRI *seg, COLOR_TABLE *ctab, double threshmm); int Seg2NbrNonBrainWrapper(char *subject, char *segname, COLOR_TABLE *ctab, char *statname, double threshmm); -#if defined(__cplusplus) -}; -#endif - - - #endif diff --git a/include/cmat.h b/include/cmat.h index 068b3eea1ba..b8e34a726bb 100644 --- a/include/cmat.h +++ b/include/cmat.h @@ -30,10 +30,6 @@ #ifndef CMAT_H #define CMAT_H -#if defined(__cplusplus) -extern "C" { -#endif - #include "label.h" typedef struct @@ -55,8 +51,4 @@ int CMATtoVoxel(CMAT *cmat, MRI *mri) ; int CMATtoTKreg(CMAT *cmat, MRI *mri) ; int CMATtoScannerRAS(CMAT *cmat, MRI *mri) ; -#if defined(__cplusplus) -}; -#endif - #endif diff --git a/include/cmdargs.h b/include/cmdargs.h index 6d18dee6125..9ae58be1936 100644 --- a/include/cmdargs.h +++ b/include/cmdargs.h @@ -32,10 +32,6 @@ #ifndef CMDARGS_H #define CMDARGS_H -#if defined(__cplusplus) -extern "C" { -#endif - const char * CMDSrcVersion(void); void CMDargNErr(char *option, int n); int CMDsingleDash(char *flag); @@ -47,11 +43,4 @@ int CMDprintUsage(FILE *fp, char *ProgName); int CMDusageExit(char *ProgName); int CMDprintHelp(FILE *fp, char *ProgName); -#if defined(__cplusplus) -}; -#endif - #endif - - - diff --git a/include/colortab.h b/include/colortab.h index 6384dcee426..7cf739d5b59 100644 --- a/include/colortab.h +++ b/include/colortab.h @@ -100,10 +100,10 @@ COLOR_TABLE *CTABdeepCopy(COLOR_TABLE *ct); int CTABrgb2Annotation(int r, int g, int b); /* Return the color table index given the name of the entry*/ -int CTABentryNameToIndex(char *EntryName, COLOR_TABLE *ct); +int CTABentryNameToIndex(const char *EntryName, COLOR_TABLE *ct); /* Return the color table annotation given the name of the entry.*/ -int CTABentryNameToAnnotation(char *EntryName, COLOR_TABLE *ct); +int CTABentryNameToAnnotation(const char *EntryName, COLOR_TABLE *ct); /* Copy the file name. */ int CTABcopyFileName(COLOR_TABLE *ct, char *name, size_t name_len); @@ -177,7 +177,7 @@ int CTABunique(COLOR_TABLE *ct, int nmax); #define RGBToAnnot(r,g,b,annot) \ annot = ((r) & 0xff) | (((g) & 0xff) << 8) | (((b) & 0xff) << 16); -COLOR_TABLE *TissueTypeSchema(COLOR_TABLE *ct, char *schema); +COLOR_TABLE *TissueTypeSchema(COLOR_TABLE *ct, const char *schema); COLOR_TABLE *TissueTypeSchemaDefault(COLOR_TABLE *ct); COLOR_TABLE *TissueTypeSchemaDefaultHead(COLOR_TABLE *ct); int CTABprintASCIItt(COLOR_TABLE *ct, FILE *fp); diff --git a/include/congraph.h b/include/congraph.h deleted file mode 100644 index 3c6ce9560cb..00000000000 --- a/include/congraph.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @file congraph.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)congraph.h 1.2 - 3/21/95 -*/ -/*------------------------------------------------------------------------ - File Name: congraph.h - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: - -------------------------------------------------------------------------*/ -#ifndef CONGRAPH_H -#define CONGRAPH_H - -#include "h_logz.h" - -void ConGraphInit(LOGMAP_INFO *lmi) ; - -#endif diff --git a/include/connect.h b/include/connect.h deleted file mode 100644 index 4da75d37cea..00000000000 --- a/include/connect.h +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @file connect.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)connect.h 1.1 - 3/31/94 -*/ -/*------------------------------------------------------------------------ - File Name: connect.h - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: - -------------------------------------------------------------------------*/ -#ifndef CONNECT_H -#define CONNECT_H - -#include - -#include "h_logz.h" -#include "image.h" -#include "macros.h" -#include "struct.h" - - -typedef struct _s_rle -{ - struct _s_rle *next ; /* next run of continuous pixels */ - int start ; /* starting column of run */ - int len ; /* length of run */ -} -RLE ; - -/* - images are typically in log coordinates, so clips, dx and dy, and row - #s will all be in log space. The centroids are in Cartesian space. -*/ -/* - starty defines the y coordinate of rows[0]. -*/ -typedef struct _s_cobj -{ - int id ; /* the id of this object (also its index) */ - int used ; /* 1 if an object is actually used */ - CLIP clip ; /* bounding box of object (log space) */ - RLE **rows ; /* one link-list of runs for each row in object */ - int nrows ; - struct _s_cobj *child ; /* object that will be merged into this one */ - struct _s_cobj *parent ; /* object that this will be merged into */ - int col_cent ; /* column centroid of the object (Cartesian) */ - int row_cent ; /* row centroid of the object (Cartesian) */ - int log_area ; /* # of log space pixels in this object */ - int tv_area ; /* # of Cartesian pixels in this object */ - int starty ; - int log_col_cent ; /* column center in log space */ - int log_row_cent ; /* row center in log space */ -} -CONNECTED_OBJECT, COBJ ; - -typedef struct -{ - int nobjects ; /* # of objects actually in the table */ - int max_objects ; /* maximum size of table */ - int nrows ; - COBJ *objects ; /* array of objects */ - int *mapped ; /* the object this object is mapped to in matching */ - IMAGE *image ; /* image that was segmented */ - int thresh ; /* threshold for segmentation */ - int white ; /* 1 is white connected, 0 if black connected */ - LOGMAP_INFO *lmi ; /* the logmap info structure used in segmentation */ - int xo, yo ; /* origin of table */ -} -CONNECTED_OBJECT_TABLE, COBJ_TABLE ; - -COBJ_TABLE *ConnectedComponents(LOGMAP_INFO *lmi, IMAGE *image, int white, - int thresh, int xo, int yo) ; -void ConnTableFree(COBJ_TABLE **co) ; -void ConnTableCalculateCentroids(COBJ_TABLE *ctable) ; -int ConnTableMatch(LOGMAP_INFO *lmi, COBJ_TABLE *ct1, COBJ_TABLE *ct2, - int *x, int *y, int dx_old, int dy_old,int use_old); -COBJ * CobjFindMatch(LOGMAP_INFO *lmi, COBJ_TABLE *ctable, int x, int y, - int use_map, int *pdistance, int min_area, - int max_area, int max_dist) ; -COBJ_TABLE *ConnTableMerge(COBJ_TABLE *ct1, COBJ_TABLE *ct2, int dx, int dy) ; -void CobjCopy(COBJ *cSrcObj,COBJ *cDstObj,int dx,int dy,int copy_rles) ; -void CobjTranslate(COBJ *cobj, int dx, int dy) ; -void ConnTableFreeRles(COBJ_TABLE *ctable) ; -void ConnTableCompact(COBJ_TABLE *ct) ; - -#define CONNECT_BLACK 0 -#define CONNECT_WHITE 1 -#define NO_CONTINUITY -1 - -#endif diff --git a/include/connectcomp.h b/include/connectcomp.h index 0e5bc98bc13..ca27435eb46 100644 --- a/include/connectcomp.h +++ b/include/connectcomp.h @@ -201,7 +201,7 @@ typedef MYqueueStruct *MYqueue; void* myMalloc(int size); void* myRealloc(void* ptr, int size); -void myError(char error_text[]); +void myError(const char error_text[]); MYlist myList(int elementSize); MYlist myList1(int elementSize, int capacity); diff --git a/include/cpputils.h b/include/cpputils.h index b0b162ff0e4..9967f5e76bb 100644 --- a/include/cpputils.h +++ b/include/cpputils.h @@ -26,18 +26,7 @@ #ifndef cpputils_h #define cpputils_h -# ifdef __cplusplus -extern "C" -{ -#endif - - -// The following is usable from C MRI* MRISsignedFixedDistanceTransform(MRI_SURFACE *mris, MRI *mri_dist, double distance); MRI* MRISfillInterior2(MRI_SURFACE *mris, MRI* mri_interior); -#ifdef __cplusplus -} -#endif - #endif diff --git a/include/diag.h b/include/diag.h index f803854b917..cd944085a2b 100644 --- a/include/diag.h +++ b/include/diag.h @@ -37,10 +37,6 @@ #ifndef DIAG_H #define DIAG_H -#if defined(__cplusplus) -extern "C" { -#endif - #include #include "image.h" @@ -56,12 +52,12 @@ unsigned long DiagInit int (*vfprint)(FILE *fp, const char *fmt, va_list args), int (*vprint)(const char *fmt, va_list args)) ; -int DiagPrintf(unsigned long diag_bits, char *fmt, ...) ; +int DiagPrintf(unsigned long diag_bits, const char *fmt, ...) ; int DiagFprintf(unsigned long diag_bits, char *fmt, ...) ; void DiagBreak(void) ; /* dummy for break points in debugger */ void DiagHeartbeat(float pct_done) ; void DiagShowPctDone(float pct_done, int nprints) ; -int check_finite(char *where, double what) ; +int check_finite(const char *where, double what) ; /* diagnostic codes */ #define DIAG_SURFACE 0x00000001L /* never in same apps, so can re-use */ @@ -156,13 +152,4 @@ extern FILE *Gstderr ; extern FILE *Gstdin ; extern FILE *Gdiag_fp ; -#if defined(__cplusplus) -}; #endif - -#endif - - - - - diff --git a/include/dmatrix.h b/include/dmatrix.h index c97b0287791..e25928454aa 100644 --- a/include/dmatrix.h +++ b/include/dmatrix.h @@ -26,10 +26,6 @@ #ifndef DMATRIX_H #define DMATRIX_H -#if defined(__cplusplus) -extern "C" { -#endif - #ifdef X #undef X #endif @@ -72,9 +68,4 @@ DVECTOR *DVectorCrossProduct(const DVECTOR *v1, const DVECTOR *v2, DVECTOR *vdst DMATRIX_TYPE DMatrixMaxAbs(DMATRIX *M); DMATRIX *DMatrixDRand48(int rows, int cols, DMATRIX *m); -#if defined(__cplusplus) -}; -#endif - - #endif diff --git a/include/dtk.fs.h b/include/dtk.fs.h index 475a0e19af3..b2e25547cf1 100644 --- a/include/dtk.fs.h +++ b/include/dtk.fs.h @@ -51,7 +51,7 @@ typedef struct { DTK_HDR *hdr; // header DTK_TRACK **trk; // array of tracks (n_count) - MRI *template; // only need geometry + MRI *mri_template; // only need geometry } DTK_TRACK_SET; const char *DTKFSSrcVersion(void); diff --git a/include/error.h b/include/error.h index 1cd78a506fe..33b8805d66b 100644 --- a/include/error.h +++ b/include/error.h @@ -29,11 +29,6 @@ #include #include -#if defined(__cplusplus) -extern "C" { -#endif - - int ErrorInit(char *fname, int (*vfprint)(FILE *fp, const char *fmt, va_list args), int (*vprint)(const char *fmt, va_list args)) ; @@ -65,9 +60,4 @@ int ErrorWriteDoneFile(char *DoneFile, int errorcode); extern int Gerror ; /* global error value */ -#if defined(__cplusplus) -}; -#endif - - #endif diff --git a/include/evschutils.h b/include/evschutils.h index 82bac5e1052..b67c077d112 100644 --- a/include/evschutils.h +++ b/include/evschutils.h @@ -102,8 +102,8 @@ EVSCH *EVSRandSequence(int nEvTypes, int *nEvReps); int EVSRandTiming(EVSCH *EvSch, float *EvDur, float tRes, float tMax, float tPreScan); EVSCH *EVScb1Optimize(int nEvTypes, int *nEvReps, int nSearch); -char *EVScostString(int CostId); -int EVScostId(char *CostString); +const char *EVScostString(int CostId); +int EVScostId(const char *CostString); int EVSdesignMtxStats(MATRIX *Xtask, MATRIX *Xnuis, EVSCH *EvSch, MATRIX *C, MATRIX *W); diff --git a/include/fastmarching.h b/include/fastmarching.h index 3ba26a02fee..2b7a2b78be1 100644 --- a/include/fastmarching.h +++ b/include/fastmarching.h @@ -26,12 +26,6 @@ #ifndef fastmarching_h #define fastmarching_h -// The following is usable from C -#ifdef __cplusplus -extern "C" -{ -#endif - #include "mri.h" #include "mrisurf.h" #include "diag.h" @@ -50,23 +44,16 @@ void MRISextractOutsideDistanceMap(MRIS *mris, float resolution, float max_distance); -#ifdef __cplusplus -} -#endif - -// C++ portion starts here -#ifdef __cplusplus - #include #include #include #include -extern "C" -{ + + #include "mrisurf.h" #include "error.h" -} + #define mapMRI_XYZ(mri,x,y,z) for(int z =0 ; z < mri->depth ; z++) \ for(int y = 0 ; y < mri->height ; y++) \ @@ -586,7 +573,5 @@ class HeapCompare : std::binary_function } }; -#endif // C++ portion ends here - #endif // ifndef fastmarching_h diff --git a/include/fexterns.h b/include/fexterns.h deleted file mode 100644 index f973e2de2f5..00000000000 --- a/include/fexterns.h +++ /dev/null @@ -1,27 +0,0 @@ -/** - * @file fexterns.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -extern FILE *ffopen(); diff --git a/include/fftutils.h b/include/fftutils.h index 27cb4fbe125..caf44edd897 100644 --- a/include/fftutils.h +++ b/include/fftutils.h @@ -36,10 +36,10 @@ void RFFTforward(float* data,int length, float* re, float* im ); void RFFT( float* data, int data_length, int length, int direction ); -void FFTdebugAssert(int b, char *string); +void FFTdebugAssert(int b, const char *string); int FFTisPowerOf2( int x ); int FFTpow2( int exponent ); -float FFTdist(int x,int y,int z,float xsize,float ysize,float zsize,int len); +float FFTdist(int x,int y,int z,int len); int FFTlog2( int x ); void FFTswitch_with_z (float *** vect, int dimension, int is_y); void FFTmodarg_to_reim(float *** re_mod, float *** im_arg, int l); diff --git a/include/fgutil.h b/include/fgutil.h deleted file mode 100644 index c7b52a6166b..00000000000 --- a/include/fgutil.h +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @file fgutil.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* $Id: fgutil.h,v 1.4 2011/03/02 00:04:09 nicks Exp $ */ -#ifndef _FGUTIL_H -#define _FGUTIL_H - -#include "h_logz.h" - -/* if GRAB_LOGMAP is set, then x is # of rings, and y is # of spokes */ -typedef struct -{ - int sizex, sizey; - LOGMAP_INFO *lmi ; - int GrabOpts ; /* bit field of GRAB_ values */ - IMAGE *Icartesian ; /* only used if GrabOpts & GRAB_LOGMAP */ - IMAGE *Ilog ; /* only used if GrabOpts & GRAB_LOGMAP */ - IMAGE *Idsp ; /* image out of DSP */ -} -FGINFO; - -#define GRAB_DEFAULT 0x00 -#define GRAB_FIELD 0x01 /* 640x240 Default is 640x480 */ -#define GRAB_LOGMAP 0x02 /* Default is to return real image */ -#define GRAB_DBUFF 0x04 /* Grab using double buffer - Default is single */ -#define GRAB_EONLY 0x08 /* Grab even field - Default is odd */ -#define GRAB_SUBS 0x10 /* Subsample to true field width */ - -extern int FGInitialize(int GrabOpts, FGINFO *ptr); -extern void FGClose(void); -extern int FGGrab(FGINFO *fgi, char *buffer); -extern int FGsetLogmapType(FGINFO *fgi, int logmap_type) ; - -#endif /* _FGUTIL_H */ diff --git a/include/field_code.h b/include/field_code.h index db38b1f3387..35f94fe63db 100644 --- a/include/field_code.h +++ b/include/field_code.h @@ -71,7 +71,7 @@ #define MAX_OF_TWO(a,b) ((a)>(b) ? (a):(b)) #endif -char *ReturnFieldName(int which_field); +const char *ReturnFieldName(int which_field); int IsDistanceField(int which_field); typedef struct diff --git a/include/filecode.h b/include/filecode.h deleted file mode 100644 index f0ce1d815e0..00000000000 --- a/include/filecode.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @file filecode.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef FILECODE_H -#define FILECODE_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -#define FILECODE_STATSURF 14 -#define FILECODE_SPARSEVOL 15 - -#define FILECODE_VSS 16 -#define FILECODE_VIT 17 -#define FILECODE_VPM 18 -#define FILECODE_ISS 19 -#define FILECODE_VST 20 - -#ifdef __cplusplus -} -#endif /* #ifdef __cplusplus */ - -#endif /* #ifndef FILECODE_H */ - diff --git a/include/fio.h b/include/fio.h index 7c7e319b883..98809fc7c97 100644 --- a/include/fio.h +++ b/include/fio.h @@ -27,10 +27,6 @@ #ifndef FIO_H #define FIO_H -#if defined(__cplusplus) -extern "C" { -#endif - #include "znzlib.h" FILE *MGHopen_file(const char *fname,const char *rwmode) ; @@ -106,8 +102,4 @@ int fio_FileHasCarriageReturn(char *fname); //#define fwriteLong(l, fp) fwrite4((int)l, fp) -#if defined(__cplusplus) -}; -#endif - #endif diff --git a/include/fmarchmesh.h b/include/fmarchmesh.h deleted file mode 100644 index c6f6c0f1366..00000000000 --- a/include/fmarchmesh.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file fmarchmesh.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* Header function for computing geodesic distance on a triangular - * surfmesh - */ - -#ifndef FMARCHING_H -#define FMARCHING_H - -#include -#include "heap.h" -#include "mrisurf.h" - -#define ALIVE 1 -#define NBAND 2 -#define FAWAY 3 - -#undef INFINITY -#define INFINITY 1000000000 - -typedef struct -{ - float x; - float y; - float z; -} -MyVector; - -/* function declarations */ -float *FastMarchMesh(MRI_SURFACE *mesh, int *contour, int numinitvert, float thred); - - -#endif - diff --git a/include/fsgdf_wrap.h b/include/fsgdf_wrap.h index 8768f24bd19..88d30f812d9 100644 --- a/include/fsgdf_wrap.h +++ b/include/fsgdf_wrap.h @@ -59,11 +59,6 @@ #define SWIG_prefix "" #define SWIG_version "0.0" - -#ifdef __cplusplus -extern "C" -{ -#endif #ifdef MAC_TCL #pragma export on #endif @@ -71,8 +66,5 @@ extern "C" #ifdef MAC_TCL #pragma export off #endif -#ifdef __cplusplus -} -#endif #endif diff --git a/include/gca.h b/include/gca.h index 99d8120be16..6b2a9f5dead 100644 --- a/include/gca.h +++ b/include/gca.h @@ -30,10 +30,6 @@ #ifndef GCA_H #define GCA_H -#if defined(__cplusplus) -extern "C" { -#endif - #include "faster_variants.h" #include "mri.h" @@ -650,10 +646,4 @@ double gm_prior(GCA *gca, MRI *mri, TRANSFORM *transform, int x, int y, int z) ; MRI *GCAsampleToVol(MRI *mri, GCA *gca, TRANSFORM *transform, MRI **seg, MRI *out); MRI *GCAsampleToVolWMSAprob(MRI *mri, GCA *gca, TRANSFORM *transform, MRI *out); -#if defined(__cplusplus) -}; -#endif - - - #endif diff --git a/include/gcamcomputeLabelsLinearCPU.h b/include/gcamcomputeLabelsLinearCPU.h index f9cbabc03be..bb8b948f398 100644 --- a/include/gcamcomputeLabelsLinearCPU.h +++ b/include/gcamcomputeLabelsLinearCPU.h @@ -4,15 +4,4 @@ #include "gcamorph.h" #include "mri.h" - -#if defined(__cplusplus) -extern "C" { -#endif - - int GCAMcomputeLabelsLinearCPU(MRI *mri, GCA_MORPH *gcam); - - -#if defined(__cplusplus) -}; -#endif diff --git a/include/gcamorph.h b/include/gcamorph.h index 3dfab051d8c..e5c94b98245 100644 --- a/include/gcamorph.h +++ b/include/gcamorph.h @@ -38,10 +38,6 @@ #include "transform.h" #include "label.h" -#if defined(__cplusplus) -extern "C" { -#endif - #define GCAM_UNLABELED 0x0000 #define GCAM_LABELED 0x0001 #define GCAM_PRESERVE_METRIC_PROPERTIES 0x0002 @@ -634,8 +630,4 @@ double MRIlabelMorphSSE(MRI *mri_source, MRI *mri_atlas, MRI *mri_morph) ; MRI *GCAMtoMRI(GCAM *gcam, MRI *mri); -#if defined(__cplusplus) -}; -#endif - #endif diff --git a/include/gcamorphtestutils.h b/include/gcamorphtestutils.h index 9289e9a5d42..5e1d986debb 100644 --- a/include/gcamorphtestutils.h +++ b/include/gcamorphtestutils.h @@ -29,19 +29,8 @@ #include "gcamorph.h" -#if defined(__cplusplus) -extern "C" { -#endif - - //! Writes a GCAM with one input defined - void WriteGCAMoneInput( const GCAM* src, const char* fName ); - - -#if defined(__cplusplus) -}; -#endif - - +///! Writes a GCAM with one input defined +void WriteGCAMoneInput( const GCAM* src, const char* fName ); #endif diff --git a/include/gcarray.h b/include/gcarray.h deleted file mode 100644 index 73fc3f103bf..00000000000 --- a/include/gcarray.h +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file gcarray.h - * @brief defines the gaussian classifier array - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef GCARRAY_H -#define GCARRAY_H - -#include "gclass.h" -#include "mri.h" - -/* - the classifiers are spaced so that there is scale/2 padding at each - border, then a classifier center every scale pixels. - */ -typedef struct -{ - int scale ; /* size reduction from original full-res. image */ - int width ; - int height ; - int depth ; - int swidth ; /* dimensions of source MRI */ - int sheight ; - int sdepth ; - int nvars ; /* # of inputs */ - GCLASSIFY ****gcs ; - Transform *transform ; - Transform *inverse_transform ; - double xstart ; /* coord. of (0,0,0) in Talairach space */ - double ystart ; - double zstart ; -} -GCARRAY ; - - -GCARRAY *GCarrayAlloc(MRI *mri_template, int scale, int nvars); -GCARRAY *GCarrayTrainAll(GCARRAY *gcarray, char *training_file_name, - int scale, int nvars) ; -int GCarraySetTransform(GCARRAY *gcarray, Transform *transform, - Transform *inverse_transform) ; -int GCarrayFree(GCARRAY **pgcarray) ; -int GCarrayTrain(GCARRAY *gcarray, MRI *mri_src,MRI *mri_norm, - MRI *mri_target); -int GCarrayUpdate(GCARRAY *gcarray, MRI *mri_src,MRI *mri_norm, - MRI *mri_target); -int GCarrayFinish(GCARRAY *gcarray) ; -MRI *GCarrayClassify(GCARRAY *gcarray, MRI *mri_src, MRI *mri_dst, - float conf, MRI *mri_probs, MRI *mri_classes) ; -int GCarrayToVoxel(GCARRAY *gcarray, int xc, int yc, int zc, - int *pxv, int *pyv, int *pzv) ; -int GCarrayVoxelToClass(GCARRAY *gcarray, int xv, int yv, int zv, - int *pxc, int *pyc, int *pzc) ; -GCARRAY *GCarrayRead(char *fname) ; -int GCarrayWrite(GCARRAY *gcarray, char *fname) ; -MRI *GCarrayThreshold(GCARRAY *gcarray, MRI *mri_probs, MRI *mri_classes, - MRI *mri_dst, float threshold) ; - -GCLASSIFY *MRIgetClassifier(GCARRAY *gcarray, MRI *mri, int xv, int yv,int zv); -int GCarrayUpdateMeans(GCARRAY *gcarray, MRI *mris[], MRI *mri_target, - int nimages) ; -int GCarrayComputeMeans(GCARRAY *gcarray) ; -int GCarrayComputeCovariances(GCARRAY *gcarray) ; -int GCarrayUpdateCovariances(GCARRAY *gcarray, MRI *mris[], - MRI *mri_target, int nimages) ; - -#endif diff --git a/include/gclass.h b/include/gclass.h index 49a7688ea53..d8a7bbc0cc1 100644 --- a/include/gclass.h +++ b/include/gclass.h @@ -57,8 +57,8 @@ typedef struct } GAUSSIAN_CLASSIFIER, GCLASSIFY ; -GCLASSIFY *GCalloc(int nclass, int nvars, char *class_names[]) ; -int GCtrain(GCLASSIFY *gc, int class, MATRIX *m_inputs) ; +GCLASSIFY *GCalloc(int nclass, int nvars, const char *class_names[]) ; +int GCtrain(GCLASSIFY *gc, int classnum, MATRIX *m_inputs) ; int GCfree(GCLASSIFY **pgc) ; int GCclassify(GCLASSIFY *gc, MATRIX *m_input, MATRIX *m_priors, float *prisk) ; @@ -66,6 +66,6 @@ int GCasciiWriteInto(FILE *fp, GCLASSIFY *gc) ; GCLASSIFY *GCasciiReadFrom(FILE *fp, GCLASSIFY *gc) ; int GCasciiWriteClassInto(FILE *fp, GCLASS *gcl) ; GCLASS *GCasciiReadClassFrom(FILE *fp, GCLASS *gcl) ; -int GCinit(GCLASSIFY *gc, int class) ; +int GCinit(GCLASSIFY *gc, int classnum) ; #endif diff --git a/include/geodesics.h b/include/geodesics.h index 889a049fa8d..eed360c1b0a 100644 --- a/include/geodesics.h +++ b/include/geodesics.h @@ -5,10 +5,6 @@ #ifndef geodesics #define geodesics -#ifdef __cplusplus -extern "C" { -#endif - #include "mrisurf.h" #define MAX_GEODESICS 8000 @@ -49,8 +45,4 @@ VTXVOLINDEX *VtxVolIndexUnique(VTXVOLINDEX *vvi, int nlist, int *nunique); VTXVOLINDEX *VtxVolIndexPack(Geodesics *geod, int vtxno, MRI *volindex); Geodesics *VtxVolPruneGeod(Geodesics *geod, int vtxno, MRI *volindex); -#ifdef __cplusplus -} -#endif - #endif diff --git a/include/gifti_local.h b/include/gifti.h similarity index 86% rename from include/gifti_local.h rename to include/gifti.h index fd3ca9013a2..22cd4e60109 100644 --- a/include/gifti_local.h +++ b/include/gifti.h @@ -1,5 +1,5 @@ /** - * @file gifti_local.h + * @file gifti.h * @brief local utilities for GIFTI library * * This file has some some extra functions for use with the GIFTI @@ -34,10 +34,7 @@ MRIS* mrisReadGIFTIfile(const char *fname, MRIS *mris); MRIS* mrisReadGIFTIdanum(const char *fname, MRIS *mris, int daNum); MRI* MRISreadGiftiAsMRI(const char *fname, int read_volume); -int MRISwriteGIFTI(MRIS* mris, - int intent_code, - const char *out_fname, - const char *curv_fname); +int MRISwriteGIFTI(MRIS* mris, int intent_code, const char *out_fname, const char *curv_fname); int mriWriteGifti(MRI* mri, const char *out_fname); #endif diff --git a/include/gmm/gmm.h b/include/gmm/gmm.h deleted file mode 100644 index 415a2f1a4af..00000000000 --- a/include/gmm/gmm.h +++ /dev/null @@ -1,53 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm.h - @author Yves Renard - @date October 13, 2002. - @brief Include common gmm files. -*/ -#ifndef GMM_H__ -#define GMM_H__ - -#include "gmm_kernel.h" -#include "gmm_dense_lu.h" -#include "gmm_dense_qr.h" - -#include "gmm_iter_solvers.h" -#include "gmm_condition_number.h" -#include "gmm_inoutput.h" - -#include "gmm_lapack_interface.h" -#include "gmm_superlu_interface.h" - - -#include "gmm_domain_decomp.h" - -#endif // GMM_H__ diff --git a/include/gmm/gmm_MUMPS_interface.h b/include/gmm/gmm_MUMPS_interface.h deleted file mode 100644 index bd955ca7289..00000000000 --- a/include/gmm/gmm_MUMPS_interface.h +++ /dev/null @@ -1,306 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_MUMPS_interface.h - @author Yves Renard , - @author Julien Pommier - @date December 8, 2005. - @brief Interface with MUMPS (LU direct solver for sparse matrices). -*/ -#if defined(GMM_USES_MUMPS) - -#ifndef GMM_MUMPS_INTERFACE_H -#define GMM_MUMPS_INTERFACE_H - -#include "gmm_kernel.h" - - -extern "C" { - -#include -#undef F_INT -#undef F_DOUBLE -#undef F_DOUBLE2 -#include -#undef F_INT -#undef F_DOUBLE -#undef F_DOUBLE2 -#include -#undef F_INT -#undef F_DOUBLE -#undef F_DOUBLE2 -#include -#undef F_INT -#undef F_DOUBLE -#undef F_DOUBLE2 - -} - -namespace gmm { - - template struct ij_sparse_matrix { - std::vector irn; - std::vector jcn; - std::vector a; - - template void store(const L& l, size_type i) { - typename linalg_traits::const_iterator it = vect_const_begin(l), - ite = vect_const_end(l); - for (; it != ite; ++it) - { irn.push_back(i + 1); jcn.push_back(it.index() + 1); a.push_back(*it); } - } - - template void build_from(const L& l, row_major) { - for (size_type i = 0; i < mat_nrows(l); ++i) - store(mat_const_row(l, i), i); - } - - template void build_from(const L& l, col_major) { - for (size_type i = 0; i < mat_ncols(l); ++i) - store(mat_const_col(l, i), i); - irn.swap(jcn); - } - - template ij_sparse_matrix(const L& A) { - size_type nz = nnz(A); - irn.reserve(nz); jcn.reserve(nz); a.reserve(nz); - build_from(A, typename principal_orientation_type::sub_orientation>::potype()); - } - }; - - /* ********************************************************************* */ - /* MUMPS solve interface */ - /* ********************************************************************* */ - - - template struct mumps_interf {}; - - template <> struct mumps_interf { - typedef SMUMPS_STRUC_C MUMPS_STRUC_C; - typedef float value_type; - - static void mumps_c(MUMPS_STRUC_C &id) { smumps_c(&id); } - }; - - template <> struct mumps_interf { - typedef DMUMPS_STRUC_C MUMPS_STRUC_C; - typedef double value_type; - static void mumps_c(MUMPS_STRUC_C &id) { dmumps_c(&id); } - }; - - template <> struct mumps_interf > { - typedef CMUMPS_STRUC_C MUMPS_STRUC_C; - typedef mumps_complex value_type; - static void mumps_c(MUMPS_STRUC_C &id) { cmumps_c(&id); } - }; - - template <> struct mumps_interf > { - typedef ZMUMPS_STRUC_C MUMPS_STRUC_C; - typedef mumps_double_complex value_type; - static void mumps_c(MUMPS_STRUC_C &id) { zmumps_c(&id); } - }; - - - /** MUMPS solve interface - * Works only with sparse or skyline matrices - */ - template - void MUMPS_solve(const MAT &A, const VECTX &X_, const VECTB &B) { - VECTX &X = const_cast(X_); - - typedef typename linalg_traits::value_type T; - typedef typename mumps_interf::value_type MUMPS_T; - GMM_ASSERT2(gmm::mat_nrows(A) == gmm::mat_ncols(A), "Non square matrix"); - - std::vector rhs(gmm::vect_size(B)); gmm::copy(B, rhs); - - ij_sparse_matrix AA(A); - - const int JOB_INIT = -1; - const int JOB_END = -2; - const int USE_COMM_WORLD = -987654; - - typename mumps_interf::MUMPS_STRUC_C id; - -#ifdef GMM_USES_MPI - int rank; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); -#endif - - id.job = JOB_INIT; - id.par = 1; - id.sym = 0; - id.comm_fortran = USE_COMM_WORLD; - mumps_interf::mumps_c(id); - -#ifdef GMM_USES_MPI - if (rank == 0) { -#endif - id.n = gmm::mat_nrows(A); - id.nz = AA.irn.size(); - id.irn = &(AA.irn[0]); - id.jcn = &(AA.jcn[0]); - id.a = (MUMPS_T*)(&(AA.a[0])); - id.rhs = (MUMPS_T*)(&(rhs[0])); -#ifdef GMM_USES_MPI - } -#endif - -#define ICNTL(I) icntl[(I)-1] -#define INFO(I) info[(I)-1] - id.ICNTL(1) = -1; id.ICNTL(2) = -1; id.ICNTL(3) = -1; id.ICNTL(4) = 0; - id.job = 6; - - id.ICNTL(14) += 40; /* small boost to the workspace size as we have encountered some problem - who did not fit in the default settings of mumps.. - by default, ICNTL(14) = 15 or 20 - */ - //cout << "ICNTL(14): " << id.ICNTL(14) << "\n"; - - mumps_interf::mumps_c(id); - if (id.INFO(1) < 0) { - switch (id.INFO(1)) { - case -6 : case -10 : - GMM_ASSERT1(false, "Solve with MUMPS failed: matrix is singular"); - case -13 : - GMM_ASSERT1(false, "Solve with MUMPS failed: not enough memory"); - case -9: - GMM_ASSERT1(false, "Solve with MUMPS failed: error " << id.INFO(1) - << ", increase ICNTL(14)"); - default : - GMM_ASSERT1(false, "Solve with MUMPS failed with error " - << id.INFO(1)); - } - } - - id.job = JOB_END; - mumps_interf::mumps_c(id); - - gmm::copy(rhs, X); - -#undef ICNTL -#undef INFO - - } - - - - /** MUMPS solve interface for distributed matrices - * Works only with sparse or skyline matrices - */ - template - void MUMPS_distributed_matrix_solve(const MAT &A, const VECTX &X_, - const VECTB &B) { - VECTX &X = const_cast(X_); - - typedef typename linalg_traits::value_type T; - typedef typename mumps_interf::value_type MUMPS_T; - GMM_ASSERT2(gmm::mat_nrows(A) == gmm::mat_ncols(A), "Non-square matrix"); - - std::vector rhs(gmm::vect_size(B)); gmm::copy(B, rhs); - - ij_sparse_matrix AA(A); - - const int JOB_INIT = -1; - const int JOB_END = -2; - const int USE_COMM_WORLD = -987654; - - typename mumps_interf::MUMPS_STRUC_C id; - -#ifdef GMM_USES_MPI - int rank; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); -#endif - - id.job = JOB_INIT; - id.par = 1; - id.sym = 0; - id.comm_fortran = USE_COMM_WORLD; - mumps_interf::mumps_c(id); - - id.n = gmm::mat_nrows(A); - id.nz_loc = AA.irn.size(); - id.irn_loc = &(AA.irn[0]); - id.jcn_loc = &(AA.jcn[0]); - id.a_loc = (MUMPS_T*)(&(AA.a[0])); - -#ifdef GMM_USES_MPI - if (rank == 0) { -#endif - id.rhs = (MUMPS_T*)(&(rhs[0])); -#ifdef GMM_USES_MPI - } -#endif - -#define ICNTL(I) icntl[(I)-1] -#define INFO(I) info[(I)-1] - id.ICNTL(1) = -1; id.ICNTL(2) = 6; // id.ICNTL(2) = -1; - id.ICNTL(3) = 6; - // id.ICNTL(3) = -1; - id.ICNTL(4) = 2; - id.ICNTL(5)=0; id.ICNTL(18)=3; - id.job = 6; - mumps_interf::mumps_c(id); - if (id.INFO(1) < 0) { - switch (id.INFO(1)) { - case -6 : case -10 : - GMM_ASSERT1(false, "Solve with MUMPS failed: matrix is singular"); - case -13: - GMM_ASSERT1(false, "Solve with MUMPS failed: not enough memory"); - case -9: - GMM_ASSERT1(false, "Solve with MUMPS failed: error " << id.INFO(1) - << ", increase ICNTL(14)"); - default : - GMM_ASSERT1(false, "Solve with MUMPS failed with error " <::mumps_c(id); -#ifdef GMM_USES_MPI - MPI_Bcast(&(rhs[0]),id.n,gmm::mpi_type(T()),0,MPI_COMM_WORLD); -#endif - gmm::copy(rhs, X); - -#undef ICNTL -#undef INFO - - } - - - - -} - - -#endif // GMM_MUMPS_INTERFACE_H - -#endif // GMM_USES_MUMPS diff --git a/include/gmm/gmm_algobase.h b/include/gmm/gmm_algobase.h deleted file mode 100644 index 9fdebff0317..00000000000 --- a/include/gmm/gmm_algobase.h +++ /dev/null @@ -1,225 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2000-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/** @file gmm_algobase.h - @author Yves Renard - @date September 28, 2000. - @brief Miscelleanous algorithms on containers. -*/ - -#ifndef GMM_ALGOBASE_H__ -#define GMM_ALGOBASE_H__ -#include "gmm_std.h" -#include "gmm_except.h" -#include - -namespace gmm { - - /* ********************************************************************* */ - /* Definitition de classes de comparaison. */ - /* retournant un int. */ - /* ********************************************************************* */ - - template - struct less : public std::binary_function { - inline int operator()(const T& x, const T& y) const - { return (x < y) ? -1 : ((y < x) ? 1 : 0); } - }; - - template<> struct less : public std::binary_function - { int operator()(int x, int y) const { return x-y; } }; - template<> struct less : public std::binary_function - { int operator()(char x, char y) const { return int(x-y); } }; - template<> struct less : public std::binary_function - { int operator()(short x, short y) const { return int(x-y); } }; - template<> struct less - : public std::binary_function { - int operator()(unsigned char x, unsigned char y) const - { return int(x)-int(y); } - }; - - - template - struct greater : public std::binary_function { - inline int operator()(const T& x, const T& y) const - { return (y < x) ? -1 : ((x < y) ? 1 : 0); } - }; - - template<> struct greater : public std::binary_function - { int operator()(int x, int y) const { return y-x; } }; - template<> struct greater : public std::binary_function - { int operator()(char x, char y) const { return int(y-x); } }; - template<> struct greater - : public std::binary_function - { int operator()(short x, short y) const { return int(y-x); } }; - template<> struct greater - : public std::binary_function { - int operator()(unsigned char x, unsigned char y) const - { return int(y)-int(x); } - }; - - template inline T my_abs(T a) { return (a < T(0)) ? T(-a) : a; } - - template - struct approx_less : public std::binary_function { - double eps; - inline int operator()(const T &x, const T &y) const - { if (my_abs(x - y) <= eps) return 0; if (x < y) return -1; return 1; } - approx_less(double e = 1E-13) { eps = e; } - }; - - template - struct approx_greater : public std::binary_function { - double eps; - inline int operator()(const T &x, const T &y) const - { if (my_abs(x - y) <= eps) return 0; if (x > y) return -1; return 1; } - approx_greater(double e = 1E-13) { eps = e; } - }; - - template - int lexicographical_compare(ITER1 b1, const ITER1 &e1, - ITER2 b2, const ITER2 &e2, const COMP &c) { - int i; - for ( ; b1 != e1 && b2 != e2; ++b1, ++b2) - if ((i = c(*b1, *b2)) != 0) return i; - if (b1 != e1) return 1; if (b2 != e2) return -1; return 0; - } - - template > - struct lexicographical_less : public std::binary_function - { - COMP c; - int operator()(const CONT &x, const CONT &y) const { - return gmm::lexicographical_compare(x.begin(), x.end(), - y.begin(), y.end(), c); - } - lexicographical_less(const COMP &d = COMP()) { c = d; } - }; - - template > - struct lexicographical_greater - : public std::binary_function { - COMP c; - int operator()(const CONT &x, const CONT &y) const { - return -gmm::lexicographical_compare(x.begin(), x.end(), - y.begin(), y.end(), c); - } - lexicographical_greater(const COMP &d = COMP()) { c = d; } - }; - - - /* ********************************************************************* */ - /* "Virtual" iterators on sequences. */ - /* The class T represent a class of sequence. */ - /* ********************************************************************* */ - - template struct sequence_iterator { - - typedef T value_type; - typedef value_type* pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef std::forward_iterator_tag iterator_category; - - T Un; - - sequence_iterator(T U0 = T(0)) { Un = U0; } - - sequence_iterator &operator ++() - { ++Un; return *this; } - sequence_iterator operator ++(int) - { sequence_iterator tmp = *this; (*this)++; return tmp; } - - const_reference operator *() const { return Un; } - reference operator *() { return Un; } - - bool operator ==(const sequence_iterator &i) const { return (i.Un==Un);} - bool operator !=(const sequence_iterator &i) const { return (i.Un!=Un);} - }; - - /* ********************************************************************* */ - /* generic algorithms. */ - /* ********************************************************************* */ - - template - ITER2 copy_n(ITER1 first, SIZE count, ITER2 result) { - for ( ; count > 0; --count, ++first, ++result) *result = *first; - return result; - } - - template - typename std::iterator_traits::value_type - mean_value(ITER first, const ITER &last) { - GMM_ASSERT2(first != last, "mean value of empty container"); - size_t n = 1; - typename std::iterator_traits::value_type res = *first++; - while (first != last) { res += *first; ++first; ++n; } - res /= float(n); - return res; - } - - template - typename CONT::value_type - mean_value(const CONT &c) { return mean_value(c.begin(), c.end()); } - - template /* hum ... */ - void minmax_box(typename std::iterator_traits::value_type &pmin, - typename std::iterator_traits::value_type &pmax, - ITER first, const ITER &last) { - typedef typename std::iterator_traits::value_type PT; - if (first != last) { pmin = pmax = *first; ++first; } - while (first != last) { - typename PT::const_iterator b = (*first).begin(), e = (*first).end(); - typename PT::iterator b1 = pmin.begin(), b2 = pmax.begin(); - while (b != e) - { *b1 = std::min(*b1, *b); *b2 = std::max(*b2, *b); ++b; ++b1; ++b2; } - } - } - - template struct sorted_indexes_aux { - const VEC &v; - public: - sorted_indexes_aux(const VEC& v_) : v(v_) {} - template - bool operator()(const IDX &ia, const IDX &ib) const - { return v[ia] < v[ib]; } - }; - - template - void sorted_indexes(const VEC &v, IVEC &iv) { - iv.clear(); iv.resize(v.size()); - for (size_t i=0; i < v.size(); ++i) iv[i] = i; - std::sort(iv.begin(), iv.end(), sorted_indexes_aux(v)); - } - -} - - -#endif /* GMM_ALGOBASE_H__ */ diff --git a/include/gmm/gmm_blas.h b/include/gmm/gmm_blas.h deleted file mode 100644 index 3848fc50d7f..00000000000 --- a/include/gmm/gmm_blas.h +++ /dev/null @@ -1,2283 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_blas.h - @author Yves Renard - @date October 13, 2002. - @brief Basic linear algebra functions. -*/ - -#ifndef GMM_BLAS_H__ -#define GMM_BLAS_H__ - -#include "gmm_scaled.h" -#include "gmm_transposed.h" -#include "gmm_conjugated.h" - -namespace gmm { - - /* ******************************************************************** */ - /* */ - /* Generic algorithms */ - /* */ - /* ******************************************************************** */ - - - /* ******************************************************************** */ - /* Miscellaneous */ - /* ******************************************************************** */ - - /** clear (fill with zeros) a vector or matrix. */ - template inline void clear(L &l) - { linalg_traits::do_clear(l); } - /** @cond DOXY_SHOW_ALL_FUNCTIONS - skip all these redundant definitions in doxygen documentation.. - */ - template inline void clear(const L &l) - { linalg_traits::do_clear(linalg_const_cast(l)); } - - ///@endcond - /** count the number of non-zero entries of a vector or matrix. */ template inline size_type nnz(const L& l) - { return nnz(l, typename linalg_traits::linalg_type()); } - - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template inline size_type nnz(const L& l, abstract_vector) { - typename linalg_traits::const_iterator it = vect_const_begin(l), - ite = vect_const_end(l); - size_type res(0); - for (; it != ite; ++it) ++res; - return res; - } - - template inline size_type nnz(const L& l, abstract_matrix) { - return nnz(l, typename principal_orientation_type::sub_orientation>::potype()); - } - - template inline size_type nnz(const L& l, row_major) { - size_type res(0); - for (size_type i = 0; i < mat_nrows(l); ++i) - res += nnz(mat_const_row(l, i)); - return res; - } - - template inline size_type nnz(const L& l, col_major) { - size_type res(0); - for (size_type i = 0; i < mat_ncols(l); ++i) - res += nnz(mat_const_col(l, i)); - return res; - } - - ///@endcond - - - /** fill a vector or matrix with x. */ - template inline - void fill(L& l, typename gmm::linalg_traits::value_type x) { - typedef typename gmm::linalg_traits::value_type T; - if (x == T(0)) gmm::clear(l); - fill(l, x, typename linalg_traits::linalg_type()); - } - - template inline - void fill(const L& l, typename gmm::linalg_traits::value_type x) { - fill(linalg_const_cast(l), x); - } - - template inline // to be optimized for dense vectors ... - void fill(L& l, typename gmm::linalg_traits::value_type x, - abstract_vector) { - for (size_type i = 0; i < vect_size(l); ++i) l[i] = x; - } - - template inline // to be optimized for dense matrices ... - void fill(L& l, typename gmm::linalg_traits::value_type x, - abstract_matrix) { - for (size_type i = 0; i < mat_nrows(l); ++i) - for (size_type j = 0; j < mat_ncols(l); ++j) - l(i,j) = x; - } - - /** fill a vector or matrix with random value (uniform [0,1]). */ - template inline void fill_random(L& l) - { fill_random(l, typename linalg_traits::linalg_type()); } - - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template inline void fill_random(const L& l) { - fill_random(linalg_const_cast(l), - typename linalg_traits::linalg_type()); - } - - template inline void fill_random(L& l, abstract_vector) { - for (size_type i = 0; i < vect_size(l); ++i) - l[i] = gmm::random(typename linalg_traits::value_type()); - } - - template inline void fill_random(L& l, abstract_matrix) { - for (size_type i = 0; i < mat_nrows(l); ++i) - for (size_type j = 0; j < mat_ncols(l); ++j) - l(i,j) = gmm::random(typename linalg_traits::value_type()); - } - - ///@endcond - /** fill a vector or matrix with random value. - @param l a vector or matrix. - @param cfill probability of a non-zero value. - */ - template inline void fill_random(L& l, double cfill) - { fill_random(l, cfill, typename linalg_traits::linalg_type()); } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template inline void fill_random(const L& l, double cfill) { - fill_random(linalg_const_cast(l), cfill, - typename linalg_traits::linalg_type()); - } - - template inline - void fill_random(L& l, double cfill, abstract_vector) { - typedef typename linalg_traits::value_type T; - size_type ntot = std::min(vect_size(l), - size_type(double(vect_size(l))*cfill) + 1); - for (size_type nb = 0; nb < ntot;) { - size_type i = gmm::irandom(vect_size(l)); - if (l[i] == T(0)) { - l[i] = gmm::random(typename linalg_traits::value_type()); - ++nb; - } - } - } - - template inline - void fill_random(L& l, double cfill, abstract_matrix) { - fill_random(l, cfill, typename principal_orientation_type::sub_orientation>::potype()); - } - - template inline - void fill_random(L& l, double cfill, row_major) { - for (size_type i=0; i < mat_nrows(l); ++i) fill_random(mat_row(l,i),cfill); - } - - template inline - void fill_random(L& l, double cfill, col_major) { - for (size_type j=0; j < mat_ncols(l); ++j) fill_random(mat_col(l,j),cfill); - } - - /* resize a vector */ - template inline - void resize(V &v, size_type n, linalg_false) - { linalg_traits::resize(v, n); } - - template inline - void resize(V &, size_type , linalg_modifiable) - { GMM_ASSERT1(false, "You cannot resize a reference"); } - - template inline - void resize(V &, size_type , linalg_const) - { GMM_ASSERT1(false, "You cannot resize a reference"); } - - ///@endcond - /** resize a vector. */ - template inline - void resize(V &v, size_type n) { - resize(v, n, typename linalg_traits::is_reference()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - /** resize a matrix **/ - template inline - void resize(M &v, size_type m, size_type n, linalg_false) { - linalg_traits::resize(v, m, n); - } - - template inline - void resize(M &, size_type, size_type, linalg_modifiable) - { GMM_ASSERT1(false, "You cannot resize a reference"); } - - template inline - void resize(M &, size_type, size_type, linalg_const) - { GMM_ASSERT1(false, "You cannot resize a reference"); } - - ///@endcond - /** resize a matrix */ - template inline - void resize(M &v, size_type m, size_type n) - { resize(v, m, n, typename linalg_traits::is_reference()); } - ///@cond - - template inline - void reshape(M &v, size_type m, size_type n, linalg_false) - { linalg_traits::reshape(v, m, n); } - - template inline - void reshape(M &, size_type, size_type, linalg_modifiable) - { GMM_ASSERT1(false, "You cannot reshape a reference"); } - - template inline - void reshape(M &, size_type, size_type, linalg_const) - { GMM_ASSERT1(false, "You cannot reshape a reference"); } - - ///@endcond - /** reshape a matrix */ - template inline - void reshape(M &v, size_type m, size_type n) - { reshape(v, m, n, typename linalg_traits::is_reference()); } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - - /* ******************************************************************** */ - /* Scalar product */ - /* ******************************************************************** */ - - ///@endcond - /** scalar product between two vectors */ - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2) { - GMM_ASSERT2(vect_size(v1) == vect_size(v2), "dimensions mismatch"); - return vect_sp(v1, v2, - typename linalg_traits::storage_type(), - typename linalg_traits::storage_type()); - } - - /** scalar product between two vectors, using a matrix. - @param ps the matrix of the scalar product. - @param v1 the first vector - @param v2 the second vector - */ - template inline - typename strongest_value_type3::value_type - vect_sp(const MATSP &ps, const V1 &v1, const V2 &v2) { - return vect_sp_with_mat(ps, v1, v2, - typename linalg_traits::sub_orientation()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template inline - typename strongest_value_type3::value_type - vect_sp_with_mat(const MATSP &ps, const V1 &v1, const V2 &v2, row_major) { - return vect_sp_with_matr(ps, v1, v2, - typename linalg_traits::storage_type()); - } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_matr(const MATSP &ps, const V1 &v1, const V2 &v2, - abstract_sparse) { - GMM_ASSERT2(vect_size(v1) == mat_ncols(ps) && - vect_size(v2) == mat_nrows(ps), "dimensions mismatch"); - size_type nr = mat_nrows(ps); - typename linalg_traits::const_iterator - it = vect_const_begin(v2), ite = vect_const_end(v2); - typename strongest_value_type3::value_type res(0); - for (; it != ite; ++it) - res += vect_sp(mat_const_row(ps, it.index()), v1)* (*it); - return res; - } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_matr(const MATSP &ps, const V1 &v1, const V2 &v2, - abstract_skyline) - { return vect_sp_with_matr(ps, v1, v2, abstract_sparse()); } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_matr(const MATSP &ps, const V1 &v1, const V2 &v2, - abstract_dense) { - GMM_ASSERT2(vect_size(v1) == mat_ncols(ps) && - vect_size(v2) == mat_nrows(ps), "dimensions mismatch"); - typename linalg_traits::const_iterator - it = vect_const_begin(v2), ite = vect_const_end(v2); - typename strongest_value_type3::value_type res(0); - for (size_type i = 0; it != ite; ++i, ++it) - res += vect_sp(mat_const_row(ps, i), v1) * (*it); - return res; - } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_mat(const MATSP &ps, const V1 &v1,const V2 &v2,row_and_col) - { return vect_sp_with_mat(ps, v1, v2, row_major()); } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_mat(const MATSP &ps, const V1 &v1, const V2 &v2,col_major){ - return vect_sp_with_matc(ps, v1, v2, - typename linalg_traits::storage_type()); - } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_matc(const MATSP &ps, const V1 &v1, const V2 &v2, - abstract_sparse) { - GMM_ASSERT2(vect_size(v1) == mat_ncols(ps) && - vect_size(v2) == mat_nrows(ps),"dimensions mismatch"); - typename linalg_traits::const_iterator - it = vect_const_begin(v1), ite = vect_const_end(v1); - typename strongest_value_type3::value_type res(0); - for (; it != ite; ++it) - res += vect_sp(mat_const_col(ps, it.index()), v2) * (*it); - return res; - } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_matc(const MATSP &ps, const V1 &v1, const V2 &v2, - abstract_skyline) - { return vect_sp_with_matc(ps, v1, v2, abstract_sparse()); } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_matc(const MATSP &ps, const V1 &v1, const V2 &v2, - abstract_dense) { - GMM_ASSERT2(vect_size(v1) == mat_ncols(ps) && - vect_size(v2) == mat_nrows(ps), "dimensions mismatch"); - typename linalg_traits::const_iterator - it = vect_const_begin(v1), ite = vect_const_end(v1); - typename strongest_value_type3::value_type res(0); - for (size_type i = 0; it != ite; ++i, ++it) - res += vect_sp(mat_const_col(ps, i), v2) * (*it); - return res; - } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_mat(const MATSP &ps, const V1 &v1,const V2 &v2,col_and_row) - { return vect_sp_with_mat(ps, v1, v2, col_major()); } - - template inline - typename strongest_value_type3::value_type - vect_sp_with_mat(const MATSP &ps, const V1 &v1, const V2 &v2, - abstract_null_type) { - typename temporary_vector::vector_type w(mat_nrows(ps)); - GMM_WARNING2("Warning, a temporary is used in scalar product\n"); - mult(ps, v1, w); - return vect_sp(w, v2); - } - - template inline - typename strongest_numeric_type::value_type, - typename std::iterator_traits::value_type>::T - vect_sp_dense_(IT1 it, IT1 ite, IT2 it2) { - typename strongest_numeric_type::value_type, - typename std::iterator_traits::value_type>::T res(0); - for (; it != ite; ++it, ++it2) res += (*it) * (*it2); - return res; - } - - template inline - typename strongest_numeric_type::value_type, - typename linalg_traits::value_type>::T - vect_sp_sparse_(IT1 it, IT1 ite, const V &v) { - typename strongest_numeric_type::value_type, - typename linalg_traits::value_type>::T res(0); - for (; it != ite; ++it) res += (*it) * v[it.index()]; - return res; - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2, abstract_dense, abstract_dense) { - return vect_sp_dense_(vect_const_begin(v1), vect_const_end(v1), - vect_const_begin(v2)); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2, abstract_skyline, abstract_dense) { - typename linalg_traits::const_iterator it1 = vect_const_begin(v1), - ite = vect_const_end(v1); - typename linalg_traits::const_iterator it2 = vect_const_begin(v2); - return vect_sp_dense_(it1, ite, it2 + it1.index()); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2, abstract_dense, abstract_skyline) { - typename linalg_traits::const_iterator it1 = vect_const_begin(v2), - ite = vect_const_end(v2); - typename linalg_traits::const_iterator it2 = vect_const_begin(v1); - return vect_sp_dense_(it1, ite, it2 + it1.index()); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2, abstract_skyline, abstract_skyline) { - typedef typename strongest_value_type::value_type T; - typename linalg_traits::const_iterator it1 = vect_const_begin(v1), - ite1 = vect_const_end(v1); - typename linalg_traits::const_iterator it2 = vect_const_begin(v2), - ite2 = vect_const_end(v2); - size_type n = std::min(ite1.index(), ite2.index()); - size_type l = std::max(it1.index(), it2.index()); - - if (l < n) { - size_type m = l - it1.index(), p = l - it2.index(), q = m + n - l; - return vect_sp_dense_(it1+m, it1+q, it2 + p); - } - return T(0); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2,abstract_sparse,abstract_dense) { - return vect_sp_sparse_(vect_const_begin(v1), vect_const_end(v1), v2); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2, abstract_sparse, abstract_skyline) { - return vect_sp_sparse_(vect_const_begin(v1), vect_const_end(v1), v2); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2, abstract_skyline, abstract_sparse) { - return vect_sp_sparse_(vect_const_begin(v2), vect_const_end(v2), v1); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2, abstract_dense,abstract_sparse) { - return vect_sp_sparse_(vect_const_begin(v2), vect_const_end(v2), v1); - } - - - template inline - typename strongest_value_type::value_type - vect_sp_sparse_sparse(const V1 &v1, const V2 &v2, linalg_true) { - typename linalg_traits::const_iterator it1 = vect_const_begin(v1), - ite1 = vect_const_end(v1); - typename linalg_traits::const_iterator it2 = vect_const_begin(v2), - ite2 = vect_const_end(v2); - typename strongest_value_type::value_type res(0); - - while (it1 != ite1 && it2 != ite2) { - if (it1.index() == it2.index()) - { res += (*it1) * *it2; ++it1; ++it2; } - else if (it1.index() < it2.index()) ++it1; else ++it2; - } - return res; - } - - template inline - typename strongest_value_type::value_type - vect_sp_sparse_sparse(const V1 &v1, const V2 &v2, linalg_false) { - return vect_sp_sparse_(vect_const_begin(v1), vect_const_end(v1), v2); - } - - template inline - typename strongest_value_type::value_type - vect_sp(const V1 &v1, const V2 &v2,abstract_sparse,abstract_sparse) { - return vect_sp_sparse_sparse(v1, v2, - typename linalg_and::index_sorted, - typename linalg_traits::index_sorted>::bool_type()); - } - - /* ******************************************************************** */ - /* Hermitian product */ - /* ******************************************************************** */ - ///@endcond - /** Hermitian product. */ - template - inline typename strongest_value_type::value_type - vect_hp(const V1 &v1, const V2 &v2) - { return vect_sp(v1, conjugated(v2)); } - - /** Hermitian product with a matrix. */ - template inline - typename strongest_value_type3::value_type - vect_hp(const MATSP &ps, const V1 &v1, const V2 &v2) { - return vect_sp(ps, v1, gmm::conjugated(v2)); - } - - /* ******************************************************************** */ - /* Trace of a matrix */ - /* ******************************************************************** */ - - /** Trace of a matrix */ - template - typename linalg_traits::value_type - mat_trace(const M &m) { - typedef typename linalg_traits::value_type T; - T res(0); - for (size_type i = 0; i < std::max(mat_nrows(m), mat_ncols(m)); ++i) - res += m(i,i); - return res; - } - - /* ******************************************************************** */ - /* Euclidean norm */ - /* ******************************************************************** */ - - /** Euclidean norm of a vector. */ - template - typename number_traits::value_type> - ::magnitude_type - vect_norm2_sqr(const V &v) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - typename linalg_traits::const_iterator - it = vect_const_begin(v), ite = vect_const_end(v); - R res(0); - for (; it != ite; ++it) res += gmm::abs_sqr(*it); - return res; - } - - /** squared Euclidean norm of a vector. */ - template inline - typename number_traits::value_type> - ::magnitude_type - vect_norm2(const V &v) - { return sqrt(vect_norm2_sqr(v)); } - - - /** squared Euclidean distance between two vectors */ - template inline - typename number_traits::value_type> - ::magnitude_type - vect_dist2_sqr(const V1 &v1, const V2 &v2) { // not fully optimized - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - typename linalg_traits::const_iterator - it1 = vect_const_begin(v1), ite1 = vect_const_end(v1); - typename linalg_traits::const_iterator - it2 = vect_const_begin(v2), ite2 = vect_const_end(v2); - size_type k1(0), k2(0); - R res(0); - while (it1 != ite1 && it2 != ite2) { - size_type i1 = index_of_it(it1, k1, - typename linalg_traits::storage_type()); - size_type i2 = index_of_it(it2, k2, - typename linalg_traits::storage_type()); - - if (i1 == i2) { - res += gmm::abs_sqr(*it2 - *it1); ++it1; ++k1; ++it2; ++k2; - } - else if (i1 < i2) { - res += gmm::abs_sqr(*it1); ++it1; ++k1; - } - else { - res += gmm::abs_sqr(*it2); ++it2; ++k2; - } - } - while (it1 != ite1) { res += gmm::abs_sqr(*it1); ++it1; } - while (it2 != ite2) { res += gmm::abs_sqr(*it2); ++it2; } - return res; - } - - /** Euclidean distance between two vectors */ - template inline - typename number_traits::value_type> - ::magnitude_type - vect_dist2(const V1 &v1, const V2 &v2) - { return sqrt(vect_dist2_sqr(v1, v2)); } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template - typename number_traits::value_type> - ::magnitude_type - mat_euclidean_norm_sqr(const M &m, row_major) { - typename number_traits::value_type> - ::magnitude_type res(0); - for (size_type i = 0; i < mat_nrows(m); ++i) - res += vect_norm2_sqr(mat_const_row(m, i)); - return res; - } - - template - typename number_traits::value_type> - ::magnitude_type - mat_euclidean_norm_sqr(const M &m, col_major) { - typename number_traits::value_type> - ::magnitude_type res(0); - for (size_type i = 0; i < mat_ncols(m); ++i) - res += vect_norm2_sqr(mat_const_col(m, i)); - return res; - } - ///@endcond - /** squared Euclidean norm of a matrix. */ - template inline - typename number_traits::value_type> - ::magnitude_type - mat_euclidean_norm_sqr(const M &m) { - return mat_euclidean_norm_sqr(m, - typename principal_orientation_type::sub_orientation>::potype()); - } - - /** Euclidean norm of a matrix. */ - template inline - typename number_traits::value_type> - ::magnitude_type - mat_euclidean_norm(const M &m) - { return gmm::sqrt(mat_euclidean_norm_sqr(m)); } - - /* ******************************************************************** */ - /* vector norm1 */ - /* ******************************************************************** */ - /** 1-norm of a vector */ - template - typename number_traits::value_type> - ::magnitude_type - vect_norm1(const V &v) { - typename linalg_traits::const_iterator - it = vect_const_begin(v), ite = vect_const_end(v); - typename number_traits::value_type> - ::magnitude_type res(0); - for (; it != ite; ++it) res += gmm::abs(*it); - return res; - } - - /* ******************************************************************** */ - /* vector Infinity norm */ - /* ******************************************************************** */ - /** Infinity norm of a vector. */ - template - typename number_traits::value_type> - ::magnitude_type - vect_norminf(const V &v) { - typename linalg_traits::const_iterator - it = vect_const_begin(v), ite = vect_const_end(v); - typename number_traits::value_type> - ::magnitude_type res(0); - for (; it != ite; ++it) res = std::max(res, gmm::abs(*it)); - return res; - } - - /* ******************************************************************** */ - /* matrix norm1 */ - /* ******************************************************************** */ - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template - typename number_traits::value_type> - ::magnitude_type - mat_norm1(const M &m, col_major) { - typename number_traits::value_type> - ::magnitude_type res(0); - for (size_type i = 0; i < mat_ncols(m); ++i) - res = std::max(res, vect_norm1(mat_const_col(m,i))); - return res; - } - - template - typename number_traits::value_type> - ::magnitude_type - mat_norm1(const M &m, row_major) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - typedef typename linalg_traits::storage_type store_type; - - std::vector aux(mat_ncols(m)); - for (size_type i = 0; i < mat_nrows(m); ++i) { - typedef typename linalg_traits::const_sub_row_type row_type; - row_type row = mat_const_row(m, i); - typename linalg_traits::const_iterator - it = vect_const_begin(row), ite = vect_const_end(row); - for (size_type k = 0; it != ite; ++it, ++k) - aux[index_of_it(it, k, store_type())] += gmm::abs(*it); - } - return vect_norminf(aux); - } - - template - typename number_traits::value_type> - ::magnitude_type - mat_norm1(const M &m, col_and_row) - { return mat_norm1(m, col_major()); } - - template - typename number_traits::value_type> - ::magnitude_type - mat_norm1(const M &m, row_and_col) - { return mat_norm1(m, col_major()); } - ///@endcond - /** 1-norm of a matrix */ - template - typename number_traits::value_type> - ::magnitude_type - mat_norm1(const M &m) { - return mat_norm1(m, typename linalg_traits::sub_orientation()); - } - - - /* ******************************************************************** */ - /* matrix Infinity norm */ - /* ******************************************************************** */ - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template - typename number_traits::value_type> - ::magnitude_type - mat_norminf(const M &m, row_major) { - typename number_traits::value_type> - ::magnitude_type res(0); - for (size_type i = 0; i < mat_nrows(m); ++i) - res = std::max(res, vect_norm1(mat_const_row(m,i))); - return res; - } - - template - typename number_traits::value_type> - ::magnitude_type - mat_norminf(const M &m, col_major) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - typedef typename linalg_traits::storage_type store_type; - - std::vector aux(mat_nrows(m)); - for (size_type i = 0; i < mat_ncols(m); ++i) { - typedef typename linalg_traits::const_sub_col_type col_type; - col_type col = mat_const_col(m, i); - typename linalg_traits::const_iterator - it = vect_const_begin(col), ite = vect_const_end(col); - for (size_type k = 0; it != ite; ++it, ++k) - aux[index_of_it(it, k, store_type())] += gmm::abs(*it); - } - return vect_norminf(aux); - } - - template - typename number_traits::value_type> - ::magnitude_type - mat_norminf(const M &m, col_and_row) - { return mat_norminf(m, row_major()); } - - template - typename number_traits::value_type> - ::magnitude_type - mat_norminf(const M &m, row_and_col) - { return mat_norminf(m, row_major()); } - ///@endcond - /** infinity-norm of a matrix.*/ - template - typename number_traits::value_type> - ::magnitude_type - mat_norminf(const M &m) { - return mat_norminf(m, typename linalg_traits::sub_orientation()); - } - - /* ******************************************************************** */ - /* Max norm for matrices */ - /* ******************************************************************** */ - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template - typename number_traits::value_type> - ::magnitude_type - mat_maxnorm(const M &m, row_major) { - typename number_traits::value_type> - ::magnitude_type res(0); - for (size_type i = 0; i < mat_nrows(m); ++i) - res = std::max(res, vect_norminf(mat_const_row(m,i))); - return res; - } - - template - typename number_traits::value_type> - ::magnitude_type - mat_maxnorm(const M &m, col_major) { - typename number_traits::value_type> - ::magnitude_type res(0); - for (size_type i = 0; i < mat_ncols(m); ++i) - res = std::max(res, vect_norminf(mat_const_col(m,i))); - return res; - } - ///@endcond - /** max-norm of a matrix. */ - template - typename number_traits::value_type> - ::magnitude_type - mat_maxnorm(const M &m) { - return mat_maxnorm(m, - typename principal_orientation_type::sub_orientation>::potype()); - } - - /* ******************************************************************** */ - /* Clean */ - /* ******************************************************************** */ - /** Clean a vector or matrix (replace near-zero entries with zeroes). */ - - template inline void clean(L &l, double threshold); - - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template - void clean(L &l, double threshold, abstract_dense, T) { - typedef typename number_traits::magnitude_type R; - typename linalg_traits::iterator it = vect_begin(l), ite = vect_end(l); - for (; it != ite; ++it) - if (gmm::abs(*it) < R(threshold)) *it = T(0); - } - - template - void clean(L &l, double threshold, abstract_skyline, T) - { gmm::clean(l, threshold, abstract_dense(), T()); } - - template - void clean(L &l, double threshold, abstract_sparse, T) { - typedef typename number_traits::magnitude_type R; - typename linalg_traits::iterator it = vect_begin(l), ite = vect_end(l); - std::vector ind; - for (; it != ite; ++it) - if (gmm::abs(*it) < R(threshold)) ind.push_back(it.index()); - for (size_type i = 0; i < ind.size(); ++i) l[ind[i]] = T(0); - } - - template - void clean(L &l, double threshold, abstract_dense, std::complex) { - typename linalg_traits::iterator it = vect_begin(l), ite = vect_end(l); - for (; it != ite; ++it){ - if (gmm::abs((*it).real()) < T(threshold)) - *it = std::complex(T(0), (*it).imag()); - if (gmm::abs((*it).imag()) < T(threshold)) - *it = std::complex((*it).real(), T(0)); - } - } - - template - void clean(L &l, double threshold, abstract_skyline, std::complex) - { gmm::clean(l, threshold, abstract_dense(), std::complex()); } - - template - void clean(L &l, double threshold, abstract_sparse, std::complex) { - typename linalg_traits::iterator it = vect_begin(l), ite = vect_end(l); - std::vector ind; - for (; it != ite; ++it) { - bool r = (gmm::abs((*it).real()) < T(threshold)); - bool i = (gmm::abs((*it).imag()) < T(threshold)); - if (r && i) ind.push_back(it.index()); - else if (r) (*it).real() = T(0); - else if (i) (*it).imag() = T(0); - } - for (size_type i = 0; i < ind.size(); ++i) - l[ind[i]] = std::complex(T(0),T(0)); - } - - template inline void clean(L &l, double threshold, - abstract_vector) { - gmm::clean(l, threshold, typename linalg_traits::storage_type(), - typename linalg_traits::value_type()); - } - - template inline void clean(const L &l, double threshold); - - template void clean(L &l, double threshold, row_major) { - for (size_type i = 0; i < mat_nrows(l); ++i) - gmm::clean(mat_row(l, i), threshold); - } - - template void clean(L &l, double threshold, col_major) { - for (size_type i = 0; i < mat_ncols(l); ++i) - gmm::clean(mat_col(l, i), threshold); - } - - template inline void clean(L &l, double threshold, - abstract_matrix) { - gmm::clean(l, threshold, - typename principal_orientation_type::sub_orientation>::potype()); - } - - template inline void clean(L &l, double threshold) - { clean(l, threshold, typename linalg_traits::linalg_type()); } - - template inline void clean(const L &l, double threshold) - { gmm::clean(linalg_const_cast(l), threshold); } - - /* ******************************************************************** */ - /* Copy */ - /* ******************************************************************** */ - ///@endcond - /** Copy vectors or matrices. - @param l1 source vector or matrix. - @param l2 destination. - */ - template inline - void copy(const L1& l1, L2& l2) { - if ((const void *)(&l1) != (const void *)(&l2)) { - if (same_origin(l1,l2)) - GMM_WARNING2("Warning : a conflict is possible in copy\n"); - - copy(l1, l2, typename linalg_traits::linalg_type(), - typename linalg_traits::linalg_type()); - } - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template inline - void copy(const L1& l1, const L2& l2) { copy(l1, linalg_const_cast(l2)); } - - template inline - void copy(const L1& l1, L2& l2, abstract_vector, abstract_vector) { - GMM_ASSERT2(vect_size(l1) == vect_size(l2), "dimensions mismatch"); - copy_vect(l1, l2, typename linalg_traits::storage_type(), - typename linalg_traits::storage_type()); - } - - template inline - void copy(const L1& l1, L2& l2, abstract_matrix, abstract_matrix) { - size_type m = mat_nrows(l1), n = mat_ncols(l1); - if (!m || !n) return; - GMM_ASSERT2(n==mat_ncols(l2) && m==mat_nrows(l2), "dimensions mismatch"); - copy_mat(l1, l2, typename linalg_traits::sub_orientation(), - typename linalg_traits::sub_orientation()); - } - - template inline - void copy_vect(const V1 &v1, const V2 &v2, C1, C2) - { copy_vect(v1, const_cast(v2), C1(), C2()); } - - - template - void copy_mat_by_row(const L1& l1, L2& l2) { - size_type nbr = mat_nrows(l1); - for (size_type i = 0; i < nbr; ++i) - copy_vect(mat_const_row(l1, i), mat_row(l2, i), - typename linalg_traits::storage_type(), - typename linalg_traits::storage_type()); - } - - template - void copy_mat_by_col(const L1 &l1, L2 &l2) { - size_type nbc = mat_ncols(l1); - for (size_type i = 0; i < nbc; ++i) { - copy_vect(mat_const_col(l1, i), mat_col(l2, i), - typename linalg_traits::storage_type(), - typename linalg_traits::storage_type()); - } - } - - template inline - void copy_mat(const L1& l1, L2& l2, row_major, row_major) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, row_major, row_and_col) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, row_and_col, row_and_col) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, row_and_col, row_major) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, col_and_row, row_major) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, row_major, col_and_row) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, col_and_row, row_and_col) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, row_and_col, col_and_row) - { copy_mat_by_row(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, col_major, col_major) - { copy_mat_by_col(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, col_major, col_and_row) - { copy_mat_by_col(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, col_major, row_and_col) - { copy_mat_by_col(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, row_and_col, col_major) - { copy_mat_by_col(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, col_and_row, col_major) - { copy_mat_by_col(l1, l2); } - - template inline - void copy_mat(const L1& l1, L2& l2, col_and_row, col_and_row) - { copy_mat_by_col(l1, l2); } - - template inline - void copy_mat_mixed_rc(const L1& l1, L2& l2, size_type i) { - copy_mat_mixed_rc(l1, l2, i, typename linalg_traits::storage_type()); - } - - template - void copy_mat_mixed_rc(const L1& l1, L2& l2, size_type i, abstract_sparse) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) - l2(i, it.index()) = *it; - } - - template - void copy_mat_mixed_rc(const L1& l1, L2& l2, size_type i, abstract_skyline) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) - l2(i, it.index()) = *it; - } - - template - void copy_mat_mixed_rc(const L1& l1, L2& l2, size_type i, abstract_dense) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (size_type j = 0; it != ite; ++it, ++j) l2(i, j) = *it; - } - - template inline - void copy_mat_mixed_cr(const L1& l1, L2& l2, size_type i) { - copy_mat_mixed_cr(l1, l2, i, typename linalg_traits::storage_type()); - } - - template - void copy_mat_mixed_cr(const L1& l1, L2& l2, size_type i, abstract_sparse) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) l2(it.index(), i) = *it; - } - - template - void copy_mat_mixed_cr(const L1& l1, L2& l2, size_type i, abstract_skyline) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) l2(it.index(), i) = *it; - } - - template - void copy_mat_mixed_cr(const L1& l1, L2& l2, size_type i, abstract_dense) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (size_type j = 0; it != ite; ++it, ++j) l2(j, i) = *it; - } - - template - void copy_mat(const L1& l1, L2& l2, row_major, col_major) { - clear(l2); - size_type nbr = mat_nrows(l1); - for (size_type i = 0; i < nbr; ++i) - copy_mat_mixed_rc(mat_const_row(l1, i), l2, i); - } - - template - void copy_mat(const L1& l1, L2& l2, col_major, row_major) { - clear(l2); - size_type nbc = mat_ncols(l1); - for (size_type i = 0; i < nbc; ++i) - copy_mat_mixed_cr(mat_const_col(l1, i), l2, i); - } - - template inline - void copy_vect(const L1 &l1, L2 &l2, abstract_dense, abstract_dense) { - std::copy(vect_const_begin(l1), vect_const_end(l1), vect_begin(l2)); - } - - template inline // to be optimised ? - void copy_vect(const L1 &l1, L2 &l2, abstract_skyline, abstract_skyline) { - typename linalg_traits::const_iterator it1 = vect_const_begin(l1), - ite1 = vect_const_end(l1); - while (it1 != ite1 && *it1 == typename linalg_traits::value_type(0)) - ++it1; - - if (ite1 - it1 > 0) { - clear(l2); - typename linalg_traits::iterator it2 = vect_begin(l2), - ite2 = vect_end(l2); - while (*(ite1-1) == typename linalg_traits::value_type(0)) ite1--; - - if (it2 == ite2) { - l2[it1.index()] = *it1; ++it1; - l2[ite1.index()-1] = *(ite1-1); --ite1; - if (it1 < ite1) - { it2 = vect_begin(l2); ++it2; std::copy(it1, ite1, it2); } - } - else { - ptrdiff_t m = it1.index() - it2.index(); - if (m >= 0 && ite1.index() <= ite2.index()) - std::copy(it1, ite1, it2 + m); - else { - if (m < 0) l2[it1.index()] = *it1; - if (ite1.index() > ite2.index()) l2[ite1.index()-1] = *(ite1-1); - it2 = vect_begin(l2); ite2 = vect_end(l2); - m = it1.index() - it2.index(); - std::copy(it1, ite1, it2 + m); - } - } - } - } - - template - void copy_vect(const L1& l1, L2& l2, abstract_sparse, abstract_dense) { - clear(l2); - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) { l2[it.index()] = *it; } - } - - template - void copy_vect(const L1& l1, L2& l2, abstract_sparse, abstract_skyline) { - clear(l2); - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) l2[it.index()] = *it; - } - - template - void copy_vect(const L1& l1, L2& l2, abstract_skyline, abstract_dense) { - typedef typename linalg_traits::value_type T; - typedef typename linalg_traits::const_iterator l1_const_iterator; - typedef typename linalg_traits::iterator l2_iterator; - l1_const_iterator it = vect_const_begin(l1), ite = vect_const_end(l1); - if (it == ite) - gmm::clear(l2); - else { - l2_iterator it2 = vect_begin(l2), ite2 = vect_end(l2); - - size_type i = it.index(), j; - for (j = 0; j < i; ++j, ++it2) *it2 = T(0); - for (; it != ite; ++it, ++it2) *it2 = *it; - for (; it2 != ite2; ++it2) *it2 = T(0); - } - } - - template - void copy_vect(const L1& l1, L2& l2, abstract_sparse, abstract_sparse) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - clear(l2); - for (; it != ite; ++it) - if (*it != (typename linalg_traits::value_type)(0)) - l2[it.index()] = *it; - } - - template - void copy_vect(const L1& l1, L2& l2, abstract_dense, abstract_sparse) { - clear(l2); - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (size_type i = 0; it != ite; ++it, ++i) - if (*it != (typename linalg_traits::value_type)(0)) - l2[i] = *it; - } - - template // to be optimised ... - void copy_vect(const L1& l1, L2& l2, abstract_dense, abstract_skyline) { - clear(l2); - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (size_type i = 0; it != ite; ++it, ++i) - if (*it != (typename linalg_traits::value_type)(0)) - l2[i] = *it; - } - - - template - void copy_vect(const L1& l1, L2& l2, abstract_skyline, abstract_sparse) { - clear(l2); - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) - if (*it != (typename linalg_traits::value_type)(0)) - l2[it.index()] = *it; - } - - /* ******************************************************************** */ - /* Matrix and vector addition */ - /* algorithms are built in order to avoid some conflicts whith */ - /* repeated arguments or with overlapping part of a same object. */ - /* In the latter case, conflicts are still possible. */ - /* ******************************************************************** */ - ///@endcond - /** Add two vectors or matrices - @param l1 - @param l2 contains on output, l2+l1. - */ - template inline - void add(const L1& l1, L2& l2) { - add_spec(l1, l2, typename linalg_traits::linalg_type()); - } - ///@cond - - template inline - void add(const L1& l1, const L2& l2) { add(l1, linalg_const_cast(l2)); } - - template inline - void add_spec(const L1& l1, L2& l2, abstract_vector) { - GMM_ASSERT2(vect_size(l1) == vect_size(l2), "dimensions mismatch"); - add(l1, l2, typename linalg_traits::storage_type(), - typename linalg_traits::storage_type()); - } - - template inline - void add_spec(const L1& l1, L2& l2, abstract_matrix) { - size_type m = mat_nrows(l1), n = mat_ncols(l1); - GMM_ASSERT2(m==mat_nrows(l2) && n==mat_ncols(l2), "dimensions mismatch"); - add(l1, l2, typename linalg_traits::sub_orientation(), - typename linalg_traits::sub_orientation()); - } - - template - void add(const L1& l1, L2& l2, row_major, row_major) { - typename linalg_traits::const_row_iterator it1 = mat_row_begin(l1), - ite = mat_row_end(l1); - typename linalg_traits::row_iterator it2 = mat_row_begin(l2); - for ( ; it1 != ite; ++it1, ++it2) - add(linalg_traits::row(it1), linalg_traits::row(it2)); - } - - template - void add(const L1& l1, L2& l2, col_major, col_major) { - typename linalg_traits::const_col_iterator - it1 = mat_col_const_begin(l1), - ite = mat_col_const_end(l1); - typename linalg_traits::col_iterator it2 = mat_col_begin(l2); - for ( ; it1 != ite; ++it1, ++it2) - add(linalg_traits::col(it1), linalg_traits::col(it2)); - } - - template inline - void add_mat_mixed_rc(const L1& l1, L2& l2, size_type i) { - add_mat_mixed_rc(l1, l2, i, typename linalg_traits::storage_type()); - } - - template - void add_mat_mixed_rc(const L1& l1, L2& l2, size_type i, abstract_sparse) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) l2(i, it.index()) += *it; - } - - template - void add_mat_mixed_rc(const L1& l1, L2& l2, size_type i, abstract_skyline) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) l2(i, it.index()) += *it; - } - - template - void add_mat_mixed_rc(const L1& l1, L2& l2, size_type i, abstract_dense) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (size_type j = 0; it != ite; ++it, ++j) l2(i, j) += *it; - } - - template inline - void add_mat_mixed_cr(const L1& l1, L2& l2, size_type i) { - add_mat_mixed_cr(l1, l2, i, typename linalg_traits::storage_type()); - } - - template - void add_mat_mixed_cr(const L1& l1, L2& l2, size_type i, abstract_sparse) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) l2(it.index(), i) += *it; - } - - template - void add_mat_mixed_cr(const L1& l1, L2& l2, size_type i, abstract_skyline) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (; it != ite; ++it) l2(it.index(), i) += *it; - } - - template - void add_mat_mixed_cr(const L1& l1, L2& l2, size_type i, abstract_dense) { - typename linalg_traits::const_iterator - it = vect_const_begin(l1), ite = vect_const_end(l1); - for (size_type j = 0; it != ite; ++it, ++j) l2(j, i) += *it; - } - - template - void add(const L1& l1, L2& l2, row_major, col_major) { - size_type nbr = mat_nrows(l1); - for (size_type i = 0; i < nbr; ++i) - add_mat_mixed_rc(mat_const_row(l1, i), l2, i); - } - - template - void add(const L1& l1, L2& l2, col_major, row_major) { - size_type nbc = mat_ncols(l1); - for (size_type i = 0; i < nbc; ++i) - add_mat_mixed_cr(mat_const_col(l1, i), l2, i); - } - - template inline - void add(const L1& l1, L2& l2, row_and_col, row_major) - { add(l1, l2, row_major(), row_major()); } - - template inline - void add(const L1& l1, L2& l2, row_and_col, row_and_col) - { add(l1, l2, row_major(), row_major()); } - - template inline - void add(const L1& l1, L2& l2, row_and_col, col_and_row) - { add(l1, l2, row_major(), row_major()); } - - template inline - void add(const L1& l1, L2& l2, col_and_row, row_and_col) - { add(l1, l2, row_major(), row_major()); } - - template inline - void add(const L1& l1, L2& l2, row_major, row_and_col) - { add(l1, l2, row_major(), row_major()); } - - template inline - void add(const L1& l1, L2& l2, col_and_row, row_major) - { add(l1, l2, row_major(), row_major()); } - - template inline - void add(const L1& l1, L2& l2, row_major, col_and_row) - { add(l1, l2, row_major(), row_major()); } - - template inline - void add(const L1& l1, L2& l2, row_and_col, col_major) - { add(l1, l2, col_major(), col_major()); } - - template inline - void add(const L1& l1, L2& l2, col_major, row_and_col) - { add(l1, l2, col_major(), col_major()); } - - template inline - void add(const L1& l1, L2& l2, col_and_row, col_major) - { add(l1, l2, col_major(), col_major()); } - - template inline - void add(const L1& l1, L2& l2, col_and_row, col_and_row) - { add(l1, l2, col_major(), col_major()); } - - template inline - void add(const L1& l1, L2& l2, col_major, col_and_row) - { add(l1, l2, col_major(), col_major()); } - - ///@endcond - /** Addition of two vectors/matrices - @param l1 - @param l2 - @param l3 contains l1+l2 on output - */ - template inline - void add(const L1& l1, const L2& l2, L3& l3) { - add_spec(l1, l2, l3, typename linalg_traits::linalg_type()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template inline - void add(const L1& l1, const L2& l2, const L3& l3) - { add(l1, l2, linalg_const_cast(l3)); } - - template inline - void add_spec(const L1& l1, const L2& l2, L3& l3, abstract_matrix) - { copy(l2, l3); add(l1, l3); } - - template inline - void add_spec(const L1& l1, const L2& l2, L3& l3, abstract_vector) { - GMM_ASSERT2(vect_size(l1) == vect_size(l2) && - vect_size(l1) == vect_size(l3), "dimensions mismatch"); - if ((const void *)(&l1) == (const void *)(&l3)) - add(l2, l3); - else if ((const void *)(&l2) == (const void *)(&l3)) - add(l1, l3); - else - add(l1, l2, l3, typename linalg_traits::storage_type(), - typename linalg_traits::storage_type(), - typename linalg_traits::storage_type()); - } - - template - void add_full_(IT1 it1, IT2 it2, IT3 it3, IT3 ite) { - for (; it3 != ite; ++it3, ++it2, ++it1) *it3 = *it1 + *it2; - } - - template - void add_almost_full_(IT1 it1, IT1 ite1, IT2 it2, IT3 it3, IT3 ite3) { - IT3 it = it3; - for (; it != ite3; ++it, ++it2) *it = *it2; - for (; it1 != ite1; ++it1) - *(it3 + it1.index()) += *it1; - } - - template - void add_to_full_(IT1 it1, IT1 ite1, IT2 it2, IT2 ite2, - IT3 it3, IT3 ite3) { - typedef typename std::iterator_traits::value_type T; - IT3 it = it3; - for (; it != ite3; ++it) *it = T(0); - for (; it1 != ite1; ++it1) *(it3 + it1.index()) = *it1; - for (; it2 != ite2; ++it2) *(it3 + it2.index()) += *it2; - } - - template inline - void add(const L1& l1, const L2& l2, L3& l3, - abstract_dense, abstract_dense, abstract_dense) { - add_full_(vect_const_begin(l1), vect_const_begin(l2), - vect_begin(l3), vect_end(l3)); - } - - // generic function for add(v1, v2, v3). - // Need to be specialized to optimize particular additions. - template - inline void add(const L1& l1, const L2& l2, L3& l3, ST1, ST2, ST3) - { copy(l2, l3); add(l1, l3, ST1(), ST3()); } - - template inline - void add(const L1& l1, const L2& l2, L3& l3, - abstract_sparse, abstract_dense, abstract_dense) { - add_almost_full_(vect_const_begin(l1), vect_const_end(l1), - vect_const_begin(l2), vect_begin(l3), vect_end(l3)); - } - - template inline - void add(const L1& l1, const L2& l2, L3& l3, - abstract_dense, abstract_sparse, abstract_dense) - { add(l2, l1, l3, abstract_sparse(), abstract_dense(), abstract_dense()); } - - template inline - void add(const L1& l1, const L2& l2, L3& l3, - abstract_sparse, abstract_sparse, abstract_dense) { - add_to_full_(vect_const_begin(l1), vect_const_end(l1), - vect_const_begin(l2), vect_const_end(l2), - vect_begin(l3), vect_end(l3)); - } - - - template - void add_spspsp(const L1& l1, const L2& l2, L3& l3, linalg_true) { - typename linalg_traits::const_iterator - it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - typename linalg_traits::const_iterator - it2 = vect_const_begin(l2), ite2 = vect_const_end(l2); - clear(l3); - while (it1 != ite1 && it2 != ite2) { - ptrdiff_t d = it1.index() - it2.index(); - if (d < 0) - { l3[it1.index()] += *it1; ++it1; } - else if (d > 0) - { l3[it2.index()] += *it2; ++it2; } - else - { l3[it1.index()] = *it1 + *it2; ++it1; ++it2; } - } - for (; it1 != ite1; ++it1) l3[it1.index()] += *it1; - for (; it2 != ite2; ++it2) l3[it2.index()] += *it2; - } - - template - void add_spspsp(const L1& l1, const L2& l2, L3& l3, linalg_false) - { copy(l2, l3); add(l2, l3); } - - template - void add(const L1& l1, const L2& l2, L3& l3, - abstract_sparse, abstract_sparse, abstract_sparse) { - add_spspsp(l1, l2, l3, typename linalg_and::index_sorted, - typename linalg_traits::index_sorted>::bool_type()); - } - - template - void add(const L1& l1, L2& l2, abstract_dense, abstract_dense) { - typename linalg_traits::const_iterator it1 = vect_const_begin(l1); - typename linalg_traits::iterator - it2 = vect_begin(l2), ite = vect_end(l2); - for (; it2 != ite; ++it2, ++it1) *it2 += *it1; - } - - template - void add(const L1& l1, L2& l2, abstract_dense, abstract_skyline) { - typedef typename linalg_traits::const_iterator const_l1_iterator; - typedef typename linalg_traits::iterator l2_iterator; - typedef typename linalg_traits::value_type T; - - const_l1_iterator it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - size_type i1 = 0, ie1 = vect_size(l1); - while (it1 != ite1 && *it1 == T(0)) { ++it1; ++i1; } - if (it1 != ite1) { - l2_iterator it2 = vect_begin(l2), ite2 = vect_end(l2); - while (ie1 && *(ite1-1) == T(0)) { ite1--; --ie1; } - - if (it2 == ite2 || i1 < it2.index()) { - l2[i1] = *it1; ++i1; ++it1; - if (it1 == ite1) return; - it2 = vect_begin(l2); ite2 = vect_end(l2); - } - if (ie1 > ite2.index()) { - --ite1; l2[ie1 - 1] = *ite1; - it2 = vect_begin(l2); - } - it2 += i1 - it2.index(); - for (; it1 != ite1; ++it1, ++it2) { *it2 += *it1; } - } - } - - - template - void add(const L1& l1, L2& l2, abstract_skyline, abstract_dense) { - typename linalg_traits::const_iterator it1 = vect_const_begin(l1), - ite1 = vect_const_end(l1); - if (it1 != ite1) { - typename linalg_traits::iterator it2 = vect_begin(l2); - it2 += it1.index(); - for (; it1 != ite1; ++it2, ++it1) *it2 += *it1; - } - } - - - template - void add(const L1& l1, L2& l2, abstract_sparse, abstract_dense) { - typename linalg_traits::const_iterator - it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - for (; it1 != ite1; ++it1) l2[it1.index()] += *it1; - } - - template - void add(const L1& l1, L2& l2, abstract_sparse, abstract_sparse) { - typename linalg_traits::const_iterator - it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - for (; it1 != ite1; ++it1) l2[it1.index()] += *it1; - } - - template - void add(const L1& l1, L2& l2, abstract_sparse, abstract_skyline) { - typename linalg_traits::const_iterator - it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - for (; it1 != ite1; ++it1) l2[it1.index()] += *it1; - } - - - template - void add(const L1& l1, L2& l2, abstract_skyline, abstract_sparse) { - typename linalg_traits::const_iterator - it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - for (; it1 != ite1; ++it1) - if (*it1 != typename linalg_traits::value_type(0)) - l2[it1.index()] += *it1; - } - - template - void add(const L1& l1, L2& l2, abstract_skyline, abstract_skyline) { - typedef typename linalg_traits::const_iterator const_l1_iterator; - typedef typename linalg_traits::iterator l2_iterator; - typedef typename linalg_traits::value_type T1; - typedef typename linalg_traits::value_type T2; - - const_l1_iterator it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - - while (it1 != ite1 && *it1 == T1(0)) ++it1; - if (ite1 != it1) { - l2_iterator it2 = vect_begin(l2), ite2 = vect_end(l2); - while (*(ite1-1) == T1(0)) ite1--; - if (it2 == ite2 || it1.index() < it2.index()) { - l2[it1.index()] = T2(0); - it2 = vect_begin(l2); ite2 = vect_end(l2); - } - if (ite1.index() > ite2.index()) { - l2[ite1.index() - 1] = T2(0); - it2 = vect_begin(l2); - } - it2 += it1.index() - it2.index(); - for (; it1 != ite1; ++it1, ++it2) *it2 += *it1; - } - } - - template - void add(const L1& l1, L2& l2, abstract_dense, abstract_sparse) { - typename linalg_traits::const_iterator - it1 = vect_const_begin(l1), ite1 = vect_const_end(l1); - for (size_type i = 0; it1 != ite1; ++it1, ++i) - if (*it1 != typename linalg_traits::value_type(0)) l2[i] += *it1; - } - - /* ******************************************************************** */ - /* Matrix-vector mult */ - /* ******************************************************************** */ - ///@endcond - /** matrix-vector or matrix-matrix product. - @param l1 a matrix. - @param l2 a vector or matrix. - @param l3 the product l1*l2. - */ - template inline - void mult(const L1& l1, const L2& l2, L3& l3) { - mult_dispatch(l1, l2, l3, typename linalg_traits::linalg_type()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template inline - void mult(const L1& l1, const L2& l2, const L3& l3) - { mult(l1, l2, linalg_const_cast(l3)); } - - template inline - void mult_dispatch(const L1& l1, const L2& l2, L3& l3, abstract_vector) { - size_type m = mat_nrows(l1), n = mat_ncols(l1); - if (!m || !n) { gmm::clear(l3); return; } - GMM_ASSERT2(n==vect_size(l2) && m==vect_size(l3), "dimensions mismatch"); - if (!same_origin(l2, l3)) - mult_spec(l1, l2, l3, typename principal_orientation_type::sub_orientation>::potype()); - else { - GMM_WARNING2("Warning, A temporary is used for mult\n"); - typename temporary_vector::vector_type temp(vect_size(l3)); - mult_spec(l1, l2, temp, typename principal_orientation_type::sub_orientation>::potype()); - copy(temp, l3); - } - } - - template - void mult_by_row(const L1& l1, const L2& l2, L3& l3, abstract_sparse) { - typedef typename linalg_traits::value_type T; - clear(l3); - size_type nr = mat_nrows(l1); - for (size_type i = 0; i < nr; ++i) { - T aux = vect_sp(mat_const_row(l1, i), l2); - if (aux != T(0)) l3[i] = aux; - } - } - - template - void mult_by_row(const L1& l1, const L2& l2, L3& l3, abstract_skyline) { - typedef typename linalg_traits::value_type T; - clear(l3); - size_type nr = mat_nrows(l1); - for (size_type i = 0; i < nr; ++i) { - T aux = vect_sp(mat_const_row(l1, i), l2); - if (aux != T(0)) l3[i] = aux; - } - } - - template - void mult_by_row(const L1& l1, const L2& l2, L3& l3, abstract_dense) { - typename linalg_traits::iterator it=vect_begin(l3), ite=vect_end(l3); - typename linalg_traits::const_row_iterator - itr = mat_row_const_begin(l1); - for (; it != ite; ++it, ++itr) - *it = vect_sp(linalg_traits::row(itr), l2, - typename linalg_traits::storage_type(), - typename linalg_traits::storage_type()); - } - - template - void mult_by_col(const L1& l1, const L2& l2, L3& l3, abstract_dense) { - clear(l3); - size_type nc = mat_ncols(l1); - for (size_type i = 0; i < nc; ++i) - add(scaled(mat_const_col(l1, i), l2[i]), l3); - } - - template - void mult_by_col(const L1& l1, const L2& l2, L3& l3, abstract_sparse) { - typedef typename linalg_traits::value_type T; - clear(l3); - typename linalg_traits::const_iterator it = vect_const_begin(l2), - ite = vect_const_end(l2); - for (; it != ite; ++it) - if (*it != T(0)) add(scaled(mat_const_col(l1, it.index()), *it), l3); - } - - template - void mult_by_col(const L1& l1, const L2& l2, L3& l3, abstract_skyline) { - typedef typename linalg_traits::value_type T; - clear(l3); - typename linalg_traits::const_iterator it = vect_const_begin(l2), - ite = vect_const_end(l2); - for (; it != ite; ++it) - if (*it != T(0)) add(scaled(mat_const_col(l1, it.index()), *it), l3); - } - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, row_major) - { mult_by_row(l1, l2, l3, typename linalg_traits::storage_type()); } - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, col_major) - { mult_by_col(l1, l2, l3, typename linalg_traits::storage_type()); } - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, abstract_null_type) - { mult_ind(l1, l2, l3, typename linalg_traits::storage_type()); } - - template - void mult_ind(const L1& l1, const L2& l2, L3& l3, abstract_indirect) { - GMM_ASSERT1(false, "gmm::mult(m, ., .) undefined for this kind of matrix"); - } - - template inline - void mult(const L1& l1, const L2& l2, const L3& l3, L4& l4) { - size_type m = mat_nrows(l1), n = mat_ncols(l1); - copy(l3, l4); - if (!m || !n) { gmm::copy(l3, l4); return; } - GMM_ASSERT2(n==vect_size(l2) && m==vect_size(l4), "dimensions mismatch"); - if (!same_origin(l2, l4)) { - mult_add_spec(l1, l2, l4, typename principal_orientation_type::sub_orientation>::potype()); - } - else { - GMM_WARNING2("Warning, A temporary is used for mult\n"); - typename temporary_vector::vector_type temp(vect_size(l2)); - copy(l2, temp); - mult_add_spec(l1,temp, l4, typename principal_orientation_type::sub_orientation>::potype()); - } - } - - template inline - void mult(const L1& l1, const L2& l2, const L3& l3, const L4& l4) - { mult(l1, l2, l3, linalg_const_cast(l4)); } - - ///@endcond - /** Multiply-accumulate. l3 += l1*l2; */ - template inline - void mult_add(const L1& l1, const L2& l2, L3& l3) { - size_type m = mat_nrows(l1), n = mat_ncols(l1); - if (!m || !n) return; - GMM_ASSERT2(n==vect_size(l2) && m==vect_size(l3), "dimensions mismatch"); - if (!same_origin(l2, l3)) { - mult_add_spec(l1, l2, l3, typename principal_orientation_type::sub_orientation>::potype()); - } - else { - GMM_WARNING2("Warning, A temporary is used for mult\n"); - typename temporary_vector::vector_type temp(vect_size(l2)); - copy(l2, temp); - mult_add_spec(l1,temp, l3, typename principal_orientation_type::sub_orientation>::potype()); - } - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template inline - void mult_add(const L1& l1, const L2& l2, const L3& l3) - { mult_add(l1, l2, linalg_const_cast(l3)); } - - template - void mult_add_by_row(const L1& l1, const L2& l2, L3& l3, abstract_sparse) { - typedef typename linalg_traits::value_type T; - size_type nr = mat_nrows(l1); - for (size_type i = 0; i < nr; ++i) { - T aux = vect_sp(mat_const_row(l1, i), l2); - if (aux != T(0)) l3[i] += aux; - } - } - - template - void mult_add_by_row(const L1& l1, const L2& l2, L3& l3, abstract_skyline) { - typedef typename linalg_traits::value_type T; - size_type nr = mat_nrows(l1); - for (size_type i = 0; i < nr; ++i) { - T aux = vect_sp(mat_const_row(l1, i), l2); - if (aux != T(0)) l3[i] += aux; - } - } - - template - void mult_add_by_row(const L1& l1, const L2& l2, L3& l3, abstract_dense) { - typename linalg_traits::iterator it=vect_begin(l3), ite=vect_end(l3); - typename linalg_traits::const_row_iterator - itr = mat_row_const_begin(l1); - for (; it != ite; ++it, ++itr) - *it += vect_sp(linalg_traits::row(itr), l2); - } - - template - void mult_add_by_col(const L1& l1, const L2& l2, L3& l3, abstract_dense) { - size_type nc = mat_ncols(l1); - for (size_type i = 0; i < nc; ++i) - add(scaled(mat_const_col(l1, i), l2[i]), l3); - } - - template - void mult_add_by_col(const L1& l1, const L2& l2, L3& l3, abstract_sparse) { - typename linalg_traits::const_iterator it = vect_const_begin(l2), - ite = vect_const_end(l2); - for (; it != ite; ++it) - if (*it != typename linalg_traits::value_type(0)) - add(scaled(mat_const_col(l1, it.index()), *it), l3); - } - - template - void mult_add_by_col(const L1& l1, const L2& l2, L3& l3, abstract_skyline) { - typename linalg_traits::const_iterator it = vect_const_begin(l2), - ite = vect_const_end(l2); - for (; it != ite; ++it) - if (*it != typename linalg_traits::value_type(0)) - add(scaled(mat_const_col(l1, it.index()), *it), l3); - } - - template inline - void mult_add_spec(const L1& l1, const L2& l2, L3& l3, row_major) - { mult_add_by_row(l1, l2, l3, typename linalg_traits::storage_type()); } - - template inline - void mult_add_spec(const L1& l1, const L2& l2, L3& l3, col_major) - { mult_add_by_col(l1, l2, l3, typename linalg_traits::storage_type()); } - - template inline - void mult_add_spec(const L1& l1, const L2& l2, L3& l3, abstract_null_type) - { mult_ind(l1, l2, l3, typename linalg_traits::storage_type()); } - - template - void transposed_mult(const L1& l1, const L2& l2, const L3& l3) - { mult(gmm::transposed(l1), l2, l3); } - - - /* ******************************************************************** */ - /* Matrix-matrix mult */ - /* ******************************************************************** */ - - - struct g_mult {}; // generic mult, less optimized - struct c_mult {}; // col x col -> col mult - struct r_mult {}; // row x row -> row mult - struct rcmult {}; // row x col -> col mult - struct crmult {}; // col x row -> row mult - - - template struct mult_t; - #define DEFMU__ template<> struct mult_t - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef g_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef crmult t; }; - DEFMU__ { typedef g_mult t; }; - DEFMU__ { typedef crmult t; }; - DEFMU__ { typedef crmult t; }; - DEFMU__ { typedef g_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef crmult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef crmult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef rcmult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef c_mult t; }; - DEFMU__ { typedef r_mult t; }; - DEFMU__ { typedef r_mult t; }; - - template - void mult_dispatch(const L1& l1, const L2& l2, L3& l3, abstract_matrix) { - typedef typename temporary_matrix::matrix_type temp_mat_type; - size_type m = mat_nrows(l1), n = mat_ncols(l1), k = mat_ncols(l2); - if (n == 0) { gmm::clear(l3); return; } - GMM_ASSERT2(n == mat_nrows(l2) && m == mat_nrows(l3) && k == mat_ncols(l3), - "dimensions mismatch"); - - if (same_origin(l2, l3) || same_origin(l1, l3)) { - GMM_WARNING2("A temporary is used for mult"); - temp_mat_type temp(mat_nrows(l3), mat_ncols(l3)); - mult_spec(l1, l2, temp, typename mult_t< - typename linalg_traits::sub_orientation, - typename linalg_traits::sub_orientation, - typename linalg_traits::sub_orientation>::t()); - copy(temp, l3); - } - else - mult_spec(l1, l2, l3, typename mult_t< - typename linalg_traits::sub_orientation, - typename linalg_traits::sub_orientation, - typename linalg_traits::sub_orientation>::t()); - } - - // Completely generic but inefficient - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, g_mult) { - typedef typename linalg_traits::value_type T; - GMM_WARNING2("Inefficient generic matrix-matrix mult is used"); - for (size_type i = 0; i < mat_nrows(l3) ; ++i) - for (size_type j = 0; j < mat_ncols(l3) ; ++j) { - T a(0); - for (size_type k = 0; k < mat_nrows(l2) ; ++k) a += l1(i, k)*l2(k, j); - l3(i, j) = a; - } - } - - // row x col matrix-matrix mult - - template - void mult_row_col_with_temp(const L1& l1, const L2& l2, L3& l3, col_major) { - typedef typename temporary_col_matrix::matrix_type temp_col_mat; - temp_col_mat temp(mat_nrows(l1), mat_ncols(l1)); - copy(l1, temp); - mult(temp, l2, l3); - } - - template - void mult_row_col_with_temp(const L1& l1, const L2& l2, L3& l3, row_major) { - typedef typename temporary_row_matrix::matrix_type temp_row_mat; - temp_row_mat temp(mat_nrows(l2), mat_ncols(l2)); - copy(l2, temp); - mult(l1, temp, l3); - } - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, rcmult) { - if (is_sparse(l1) && is_sparse(l2)) { - GMM_WARNING3("Inefficient row matrix - col matrix mult for " - "sparse matrices, using temporary"); - mult_row_col_with_temp(l1, l2, l3, - typename principal_orientation_type::sub_orientation>::potype()); - } - else { - typename linalg_traits::const_col_iterator - it2b = linalg_traits::col_begin(l2), it2, - ite = linalg_traits::col_end(l2); - size_type i,j, k = mat_nrows(l1); - - for (i = 0; i < k; ++i) { - typename linalg_traits::const_sub_row_type r1=mat_const_row(l1, i); - for (it2 = it2b, j = 0; it2 != ite; ++it2, ++j) - l3(i,j) = vect_sp(r1, linalg_traits::col(it2)); - } - } - } - - // row - row matrix-matrix mult - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, r_mult) { - mult_spec(l1, l2, l3,r_mult(),typename linalg_traits::storage_type()); - } - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, r_mult, abstract_dense) { - // optimizable - clear(l3); - size_type nn = mat_nrows(l3), mm = mat_nrows(l2); - for (size_type i = 0; i < nn; ++i) { - for (size_type j = 0; j < mm; ++j) { - add(scaled(mat_const_row(l2, j), l1(i, j)), mat_row(l3, i)); - } - } - } - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, r_mult, abstract_sparse) { - // optimizable - clear(l3); - size_type nn = mat_nrows(l3); - for (size_type i = 0; i < nn; ++i) { - typename linalg_traits::const_sub_row_type rl1=mat_const_row(l1, i); - typename linalg_traits::const_sub_row_type>:: - const_iterator it = vect_const_begin(rl1), ite = vect_const_end(rl1); - for (; it != ite; ++it) - add(scaled(mat_const_row(l2, it.index()), *it), mat_row(l3, i)); - } - } - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, r_mult, abstract_skyline) - { mult_spec(l1, l2, l3, r_mult(), abstract_sparse()); } - - // col - col matrix-matrix mult - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, c_mult) { - mult_spec(l1, l2,l3,c_mult(),typename linalg_traits::storage_type(), - typename linalg_traits::sub_orientation()); - } - - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, c_mult, - abstract_dense, ORIEN) { - typedef typename linalg_traits::value_type T; - size_type nn = mat_ncols(l3), mm = mat_ncols(l1); - - for (size_type i = 0; i < nn; ++i) { - clear(mat_col(l3, i)); - for (size_type j = 0; j < mm; ++j) { - T b = l2(j, i); - if (b != T(0)) add(scaled(mat_const_col(l1, j), b), mat_col(l3, i)); - } - } - } - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, c_mult, - abstract_sparse, ORIEN) { - // optimizable - clear(l3); - size_type nn = mat_ncols(l3); - for (size_type i = 0; i < nn; ++i) { - typename linalg_traits::const_sub_col_type rc2=mat_const_col(l2, i); - typename linalg_traits::const_sub_col_type>:: - const_iterator it = vect_const_begin(rc2), ite = vect_const_end(rc2); - for (; it != ite; ++it) - add(scaled(mat_const_col(l1, it.index()), *it), mat_col(l3, i)); - } - } - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, c_mult, - abstract_sparse, row_major) { - typedef typename linalg_traits::value_type T; - GMM_WARNING3("Inefficient matrix-matrix mult for sparse matrices"); - clear(l3); - size_type mm = mat_nrows(l2), nn = mat_ncols(l3); - for (size_type i = 0; i < nn; ++i) - for (size_type j = 0; j < mm; ++j) { - T a = l2(i,j); - if (a != T(0)) add(scaled(mat_const_col(l1, j), a), mat_col(l3, i)); - } - } - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, c_mult, - abstract_skyline, ORIEN) - { mult_spec(l1, l2, l3, c_mult(), abstract_sparse(), ORIEN()); } - - - // col - row matrix-matrix mult - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, crmult) - { mult_spec(l1,l2,l3,crmult(), typename linalg_traits::storage_type()); } - - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, crmult, abstract_dense) { - // optimizable - clear(l3); - size_type nn = mat_ncols(l1), mm = mat_nrows(l1); - for (size_type i = 0; i < nn; ++i) { - for (size_type j = 0; j < mm; ++j) - add(scaled(mat_const_row(l2, i), l1(j, i)), mat_row(l3, j)); - } - } - - template - void mult_spec(const L1& l1, const L2& l2, L3& l3, crmult, abstract_sparse) { - // optimizable - clear(l3); - size_type nn = mat_ncols(l1); - for (size_type i = 0; i < nn; ++i) { - typename linalg_traits::const_sub_col_type rc1=mat_const_col(l1, i); - typename linalg_traits::const_sub_col_type>:: - const_iterator it = vect_const_begin(rc1), ite = vect_const_end(rc1); - for (; it != ite; ++it) - add(scaled(mat_const_row(l2, i), *it), mat_row(l3, it.index())); - } - } - - template inline - void mult_spec(const L1& l1, const L2& l2, L3& l3, crmult, abstract_skyline) - { mult_spec(l1, l2, l3, crmult(), abstract_sparse()); } - - - /* ******************************************************************** */ - /* Symmetry test. */ - /* ******************************************************************** */ - - ///@endcond - /** test if A is symmetric. - @param A a matrix. - @param tol a threshold. - */ - template inline - bool is_symmetric(const MAT &A, magnitude_of_linalg(MAT) tol - = magnitude_of_linalg(MAT)(-1)) { - typedef magnitude_of_linalg(MAT) R; - if (tol < R(0)) tol = default_tol(R()) * mat_maxnorm(A); - if (mat_nrows(A) != mat_ncols(A)) return false; - return is_symmetric(A, tol, typename linalg_traits::storage_type()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template - bool is_symmetric(const MAT &A, magnitude_of_linalg(MAT) tol, - abstract_dense) { - size_type m = mat_nrows(A); - for (size_type i = 1; i < m; ++i) - for (size_type j = 0; j < i; ++j) - if (gmm::abs(A(i, j)-A(j, i)) > tol) return false; - return true; - } - - template - bool is_symmetric(const MAT &A, magnitude_of_linalg(MAT) tol, - abstract_sparse) { - return is_symmetric(A, tol, typename principal_orientation_type::sub_orientation>::potype()); - } - - template - bool is_symmetric(const MAT &A, magnitude_of_linalg(MAT) tol, - row_major) { - for (size_type i = 0; i < mat_nrows(A); ++i) { - typedef typename linalg_traits::const_sub_row_type row_type; - row_type row = mat_const_row(A, i); - typename linalg_traits::const_iterator - it = vect_const_begin(row), ite = vect_const_end(row); - for (; it != ite; ++it) - if (gmm::abs(*it - A(it.index(), i)) > tol) return false; - } - return true; - } - - template - bool is_symmetric(const MAT &A, magnitude_of_linalg(MAT) tol, - col_major) { - for (size_type i = 0; i < mat_ncols(A); ++i) { - typedef typename linalg_traits::const_sub_col_type col_type; - col_type col = mat_const_col(A, i); - typename linalg_traits::const_iterator - it = vect_const_begin(col), ite = vect_const_end(col); - for (; it != ite; ++it) - if (gmm::abs(*it - A(i, it.index())) > tol) return false; - } - return true; - } - - template - bool is_symmetric(const MAT &A, magnitude_of_linalg(MAT) tol, - abstract_skyline) - { return is_symmetric(A, tol, abstract_sparse()); } - - ///@endcond - /** test if A is Hermitian. - @param A a matrix. - @param tol a threshold. - */ - template inline - bool is_hermitian(const MAT &A, magnitude_of_linalg(MAT) tol - = magnitude_of_linalg(MAT)(-1)) { - typedef magnitude_of_linalg(MAT) R; - if (tol < R(0)) tol = default_tol(R()) * mat_maxnorm(A); - if (mat_nrows(A) != mat_ncols(A)) return false; - return is_hermitian(A, tol, typename linalg_traits::storage_type()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template - bool is_hermitian(const MAT &A, magnitude_of_linalg(MAT) tol, - abstract_dense) { - size_type m = mat_nrows(A); - for (size_type i = 1; i < m; ++i) - for (size_type j = 0; j < i; ++j) - if (gmm::abs(A(i, j)-gmm::conj(A(j, i))) > tol) return false; - return true; - } - - template - bool is_hermitian(const MAT &A, magnitude_of_linalg(MAT) tol, - abstract_sparse) { - return is_hermitian(A, tol, typename principal_orientation_type::sub_orientation>::potype()); - } - - template - bool is_hermitian(const MAT &A, magnitude_of_linalg(MAT) tol, - row_major) { - for (size_type i = 0; i < mat_nrows(A); ++i) { - typedef typename linalg_traits::const_sub_row_type row_type; - row_type row = mat_const_row(A, i); - typename linalg_traits::const_iterator - it = vect_const_begin(row), ite = vect_const_end(row); - for (; it != ite; ++it) - if (gmm::abs(gmm::conj(*it) - A(it.index(), i)) > tol) return false; - } - return true; - } - - template - bool is_hermitian(const MAT &A, magnitude_of_linalg(MAT) tol, - col_major) { - for (size_type i = 0; i < mat_ncols(A); ++i) { - typedef typename linalg_traits::const_sub_col_type col_type; - col_type col = mat_const_col(A, i); - typename linalg_traits::const_iterator - it = vect_const_begin(col), ite = vect_const_end(col); - for (; it != ite; ++it) - if (gmm::abs(gmm::conj(*it) - A(i, it.index())) > tol) return false; - } - return true; - } - - template - bool is_hermitian(const MAT &A, magnitude_of_linalg(MAT) tol, - abstract_skyline) - { return is_hermitian(A, tol, abstract_sparse()); } - ///@endcond -} - - -#endif // GMM_BLAS_H__ diff --git a/include/gmm/gmm_blas_interface.h b/include/gmm/gmm_blas_interface.h deleted file mode 100644 index 785e40392e7..00000000000 --- a/include/gmm/gmm_blas_interface.h +++ /dev/null @@ -1,855 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_blas_interface.h - @author Caroline Lecalvez, Caroline.Lecalvez@gmm.insa-tlse.fr, Yves Renard - @date October 7, 2003. - @brief gmm interface for fortran BLAS. -*/ - -#if defined(GETFEM_USES_BLAS) || defined(GMM_USES_BLAS) \ - || defined(GMM_USES_LAPACK) || defined(GMM_USES_ATLAS) - -#ifndef GMM_BLAS_INTERFACE_H -#define GMM_BLAS_INTERFACE_H - -#include "gmm_blas.h" -#include "gmm_interface.h" -#include "gmm_matrix.h" - -namespace gmm { - -#define GMMLAPACK_TRACE(f) - // #define GMMLAPACK_TRACE(f) cout << "function " << f << " called" << endl; - - /* ********************************************************************* */ - /* Operations interfaced for T = float, double, std::complex */ - /* or std::complex : */ - /* */ - /* vect_norm2(std::vector) */ - /* */ - /* vect_sp(std::vector, std::vector) */ - /* vect_sp(scaled(std::vector), std::vector) */ - /* vect_sp(std::vector, scaled(std::vector)) */ - /* vect_sp(scaled(std::vector), scaled(std::vector)) */ - /* */ - /* vect_hp(std::vector, std::vector) */ - /* vect_hp(scaled(std::vector), std::vector) */ - /* vect_hp(std::vector, scaled(std::vector)) */ - /* vect_hp(scaled(std::vector), scaled(std::vector)) */ - /* */ - /* add(std::vector, std::vector) */ - /* add(scaled(std::vector, a), std::vector) */ - /* */ - /* mult(dense_matrix, dense_matrix, dense_matrix) */ - /* mult(transposed(dense_matrix), dense_matrix, dense_matrix) */ - /* mult(dense_matrix, transposed(dense_matrix), dense_matrix) */ - /* mult(transposed(dense_matrix), transposed(dense_matrix), */ - /* dense_matrix) */ - /* mult(conjugated(dense_matrix), dense_matrix, dense_matrix) */ - /* mult(dense_matrix, conjugated(dense_matrix), dense_matrix) */ - /* mult(conjugated(dense_matrix), conjugated(dense_matrix), */ - /* dense_matrix) */ - /* */ - /* mult(dense_matrix, std::vector, std::vector) */ - /* mult(transposed(dense_matrix), std::vector, std::vector) */ - /* mult(conjugated(dense_matrix), std::vector, std::vector) */ - /* mult(dense_matrix, scaled(std::vector), std::vector) */ - /* mult(transposed(dense_matrix), scaled(std::vector), */ - /* std::vector) */ - /* mult(conjugated(dense_matrix), scaled(std::vector), */ - /* std::vector) */ - /* */ - /* mult_add(dense_matrix, std::vector, std::vector) */ - /* mult_add(transposed(dense_matrix), std::vector, std::vector) */ - /* mult_add(conjugated(dense_matrix), std::vector, std::vector) */ - /* mult_add(dense_matrix, scaled(std::vector), std::vector) */ - /* mult_add(transposed(dense_matrix), scaled(std::vector), */ - /* std::vector) */ - /* mult_add(conjugated(dense_matrix), scaled(std::vector), */ - /* std::vector) */ - /* */ - /* mult(dense_matrix, std::vector, std::vector, std::vector) */ - /* mult(transposed(dense_matrix), std::vector, std::vector, */ - /* std::vector) */ - /* mult(conjugated(dense_matrix), std::vector, std::vector, */ - /* std::vector) */ - /* mult(dense_matrix, scaled(std::vector), std::vector, */ - /* std::vector) */ - /* mult(transposed(dense_matrix), scaled(std::vector), */ - /* std::vector, std::vector) */ - /* mult(conjugated(dense_matrix), scaled(std::vector), */ - /* std::vector, std::vector) */ - /* mult(dense_matrix, std::vector, scaled(std::vector), */ - /* std::vector) */ - /* mult(transposed(dense_matrix), std::vector, */ - /* scaled(std::vector), std::vector) */ - /* mult(conjugated(dense_matrix), std::vector, */ - /* scaled(std::vector), std::vector) */ - /* mult(dense_matrix, scaled(std::vector), scaled(std::vector), */ - /* std::vector) */ - /* mult(transposed(dense_matrix), scaled(std::vector), */ - /* scaled(std::vector), std::vector) */ - /* mult(conjugated(dense_matrix), scaled(std::vector), */ - /* scaled(std::vector), std::vector) */ - /* */ - /* lower_tri_solve(dense_matrix, std::vector, k, b) */ - /* upper_tri_solve(dense_matrix, std::vector, k, b) */ - /* lower_tri_solve(transposed(dense_matrix), std::vector, k, b) */ - /* upper_tri_solve(transposed(dense_matrix), std::vector, k, b) */ - /* lower_tri_solve(conjugated(dense_matrix), std::vector, k, b) */ - /* upper_tri_solve(conjugated(dense_matrix), std::vector, k, b) */ - /* */ - /* ********************************************************************* */ - - /* ********************************************************************* */ - /* Basic defines. */ - /* ********************************************************************* */ - -# define BLAS_S float -# define BLAS_D double -# define BLAS_C std::complex -# define BLAS_Z std::complex - - /* ********************************************************************* */ - /* BLAS functions used. */ - /* ********************************************************************* */ - extern "C" void daxpy_(const int *n, const double *alpha, const double *x, const int *incx, double *y, const int *incy); - extern "C" { - void sgemm_(...); void dgemm_(...); void cgemm_(...); void zgemm_(...); - void sgemv_(...); void dgemv_(...); void cgemv_(...); void zgemv_(...); - void strsv_(...); void dtrsv_(...); void ctrsv_(...); void ztrsv_(...); - void saxpy_(...); /*void daxpy_(...); */void caxpy_(...); void zaxpy_(...); - BLAS_S sdot_ (...); BLAS_D ddot_ (...); - BLAS_C cdotu_(...); BLAS_Z zdotu_(...); - BLAS_C cdotc_(...); BLAS_Z zdotc_(...); - BLAS_S snrm2_(...); BLAS_D dnrm2_(...); - BLAS_S scnrm2_(...); BLAS_D dznrm2_(...); - } - - /* ********************************************************************* */ - /* vect_norm2(x). */ - /* ********************************************************************* */ - - # define nrm2_interface(param1, trans1, blas_name, base_type) \ - inline number_traits::magnitude_type \ - vect_norm2(param1(base_type)) { \ - GMMLAPACK_TRACE("nrm2_interface"); \ - int inc(1), n(int(vect_size(x))); trans1(base_type); \ - return blas_name(&n, &x[0], &inc); \ - } - -# define nrm2_p1(base_type) const std::vector &x -# define nrm2_trans1(base_type) - - nrm2_interface(nrm2_p1, nrm2_trans1, snrm2_ , BLAS_S) - nrm2_interface(nrm2_p1, nrm2_trans1, dnrm2_ , BLAS_D) - nrm2_interface(nrm2_p1, nrm2_trans1, scnrm2_, BLAS_C) - nrm2_interface(nrm2_p1, nrm2_trans1, dznrm2_, BLAS_Z) - - /* ********************************************************************* */ - /* vect_sp(x, y). */ - /* ********************************************************************* */ - - # define dot_interface(param1, trans1, mult1, param2, trans2, mult2, \ - blas_name, base_type) \ - inline base_type vect_sp(param1(base_type), param2(base_type)) { \ - GMMLAPACK_TRACE("dot_interface"); \ - trans1(base_type); trans2(base_type); int inc(1), n(int(vect_size(y)));\ - return mult1 mult2 blas_name(&n, &x[0], &inc, &y[0], &inc); \ - } - -# define dot_p1(base_type) const std::vector &x -# define dot_trans1(base_type) -# define dot_p1_s(base_type) \ - const scaled_vector_const_ref, base_type > &x_ -# define dot_trans1_s(base_type) \ - std::vector &x = \ - const_cast &>(*(linalg_origin(x_))); \ - base_type a(x_.r) - -# define dot_p2(base_type) const std::vector &y -# define dot_trans2(base_type) -# define dot_p2_s(base_type) \ - const scaled_vector_const_ref, base_type > &y_ -# define dot_trans2_s(base_type) \ - std::vector &y = \ - const_cast &>(*(linalg_origin(y_))); \ - base_type b(y_.r) - - dot_interface(dot_p1, dot_trans1, , dot_p2, dot_trans2, , sdot_ , BLAS_S) - dot_interface(dot_p1, dot_trans1, , dot_p2, dot_trans2, , ddot_ , BLAS_D) - dot_interface(dot_p1, dot_trans1, , dot_p2, dot_trans2, , cdotu_, BLAS_C) - dot_interface(dot_p1, dot_trans1, , dot_p2, dot_trans2, , zdotu_, BLAS_Z) - - dot_interface(dot_p1_s, dot_trans1_s, a*, dot_p2, dot_trans2, ,sdot_ ,BLAS_S) - dot_interface(dot_p1_s, dot_trans1_s, a*, dot_p2, dot_trans2, ,ddot_ ,BLAS_D) - dot_interface(dot_p1_s, dot_trans1_s, a*, dot_p2, dot_trans2, ,cdotu_,BLAS_C) - dot_interface(dot_p1_s, dot_trans1_s, a*, dot_p2, dot_trans2, ,zdotu_,BLAS_Z) - - dot_interface(dot_p1, dot_trans1, , dot_p2_s, dot_trans2_s, b*,sdot_ ,BLAS_S) - dot_interface(dot_p1, dot_trans1, , dot_p2_s, dot_trans2_s, b*,ddot_ ,BLAS_D) - dot_interface(dot_p1, dot_trans1, , dot_p2_s, dot_trans2_s, b*,cdotu_,BLAS_C) - dot_interface(dot_p1, dot_trans1, , dot_p2_s, dot_trans2_s, b*,zdotu_,BLAS_Z) - - dot_interface(dot_p1_s,dot_trans1_s,a*,dot_p2_s,dot_trans2_s,b*,sdot_ , - BLAS_S) - dot_interface(dot_p1_s,dot_trans1_s,a*,dot_p2_s,dot_trans2_s,b*,ddot_ , - BLAS_D) - dot_interface(dot_p1_s,dot_trans1_s,a*,dot_p2_s,dot_trans2_s,b*,cdotu_, - BLAS_C) - dot_interface(dot_p1_s,dot_trans1_s,a*,dot_p2_s,dot_trans2_s,b*,zdotu_, - BLAS_Z) - - - /* ********************************************************************* */ - /* vect_hp(x, y). */ - /* ********************************************************************* */ - - # define dotc_interface(param1, trans1, mult1, param2, trans2, mult2, \ - blas_name, base_type) \ - inline base_type vect_hp(param1(base_type), param2(base_type)) { \ - GMMLAPACK_TRACE("dotc_interface"); \ - trans1(base_type); trans2(base_type); int inc(1), n(int(vect_size(y)));\ - return mult1 mult2 blas_name(&n, &x[0], &inc, &y[0], &inc); \ - } - -# define dotc_p1(base_type) const std::vector &x -# define dotc_trans1(base_type) -# define dotc_p1_s(base_type) \ - const scaled_vector_const_ref, base_type > &x_ -# define dotc_trans1_s(base_type) \ - std::vector &x = \ - const_cast &>(*(linalg_origin(x_))); \ - base_type a(x_.r) - -# define dotc_p2(base_type) const std::vector &y -# define dotc_trans2(base_type) -# define dotc_p2_s(base_type) \ - const scaled_vector_const_ref, base_type > &y_ -# define dotc_trans2_s(base_type) \ - std::vector &y = \ - const_cast &>(*(linalg_origin(y_))); \ - base_type b(gmm::conj(y_.r)) - - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2, dotc_trans2, ,sdot_ ,BLAS_S) - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2, dotc_trans2, ,ddot_ ,BLAS_D) - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2, dotc_trans2, ,cdotc_,BLAS_C) - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2, dotc_trans2, ,zdotc_,BLAS_Z) - - dotc_interface(dotc_p1_s, dotc_trans1_s, a*, dotc_p2, dotc_trans2, ,sdot_, - BLAS_S) - dotc_interface(dotc_p1_s, dotc_trans1_s, a*, dotc_p2, dotc_trans2, ,ddot_ , - BLAS_D) - dotc_interface(dotc_p1_s, dotc_trans1_s, a*, dotc_p2, dotc_trans2, ,cdotc_, - BLAS_C) - dotc_interface(dotc_p1_s, dotc_trans1_s, a*, dotc_p2, dotc_trans2, ,zdotc_, - BLAS_Z) - - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2_s, dotc_trans2_s, b*,sdot_ , - BLAS_S) - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2_s, dotc_trans2_s, b*,ddot_ , - BLAS_D) - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2_s, dotc_trans2_s, b*,cdotc_, - BLAS_C) - dotc_interface(dotc_p1, dotc_trans1, , dotc_p2_s, dotc_trans2_s, b*,zdotc_, - BLAS_Z) - - dotc_interface(dotc_p1_s,dotc_trans1_s,a*,dotc_p2_s,dotc_trans2_s,b*,sdot_ , - BLAS_S) - dotc_interface(dotc_p1_s,dotc_trans1_s,a*,dotc_p2_s,dotc_trans2_s,b*,ddot_ , - BLAS_D) - dotc_interface(dotc_p1_s,dotc_trans1_s,a*,dotc_p2_s,dotc_trans2_s,b*,cdotc_, - BLAS_C) - dotc_interface(dotc_p1_s,dotc_trans1_s,a*,dotc_p2_s,dotc_trans2_s,b*,zdotc_, - BLAS_Z) - - /* ********************************************************************* */ - /* add(x, y). */ - /* ********************************************************************* */ - -# define axpy_interface(param1, trans1, blas_name, base_type) \ - inline void add(param1(base_type), std::vector &y) { \ - GMMLAPACK_TRACE("axpy_interface"); \ - int inc(1), n(int(vect_size(y))); trans1(base_type); \ - blas_name(&n, &a, &x[0], &inc, &y[0], &inc); \ - } - -# define axpy_p1(base_type) const std::vector &x -# define axpy_trans1(base_type) base_type a(1) -# define axpy_p1_s(base_type) \ - const scaled_vector_const_ref, base_type > &x_ -# define axpy_trans1_s(base_type) \ - std::vector &x = \ - const_cast &>(*(linalg_origin(x_))); \ - base_type a(x_.r) - - axpy_interface(axpy_p1, axpy_trans1, saxpy_, BLAS_S) - axpy_interface(axpy_p1, axpy_trans1, daxpy_, BLAS_D) - axpy_interface(axpy_p1, axpy_trans1, caxpy_, BLAS_C) - axpy_interface(axpy_p1, axpy_trans1, zaxpy_, BLAS_Z) - - axpy_interface(axpy_p1_s, axpy_trans1_s, saxpy_, BLAS_S) - axpy_interface(axpy_p1_s, axpy_trans1_s, daxpy_, BLAS_D) - axpy_interface(axpy_p1_s, axpy_trans1_s, caxpy_, BLAS_C) - axpy_interface(axpy_p1_s, axpy_trans1_s, zaxpy_, BLAS_Z) - - - /* ********************************************************************* */ - /* mult_add(A, x, z). */ - /* ********************************************************************* */ - -# define gemv_interface(param1, trans1, param2, trans2, blas_name, \ - base_type, orien) \ - inline void mult_add_spec(param1(base_type), param2(base_type), \ - std::vector &z, orien) { \ - GMMLAPACK_TRACE("gemv_interface"); \ - trans1(base_type); trans2(base_type); base_type beta(1); \ - int m(int(mat_nrows(A))), lda(m), n(int(mat_ncols(A))), inc(1); \ - if (m && n) blas_name(&t, &m, &n, &alpha, &A(0,0), &lda, &x[0], &inc, \ - &beta, &z[0], &inc); \ - else gmm::clear(z); \ - } - - // First parameter -# define gem_p1_n(base_type) const dense_matrix &A -# define gem_trans1_n(base_type) const char t = 'N' -# define gem_p1_t(base_type) \ - const transposed_col_ref *> &A_ -# define gem_trans1_t(base_type) dense_matrix &A = \ - const_cast &>(*(linalg_origin(A_))); \ - const char t = 'T' -# define gem_p1_tc(base_type) \ - const transposed_col_ref *> &A_ -# define gem_p1_c(base_type) \ - const conjugated_col_matrix_const_ref > &A_ -# define gem_trans1_c(base_type) dense_matrix &A = \ - const_cast &>(*(linalg_origin(A_))); \ - const char t = 'C' - - // second parameter -# define gemv_p2_n(base_type) const std::vector &x -# define gemv_trans2_n(base_type) base_type alpha(1) -# define gemv_p2_s(base_type) \ - const scaled_vector_const_ref, base_type > &x_ -# define gemv_trans2_s(base_type) std::vector &x = \ - const_cast &>(*(linalg_origin(x_))); \ - base_type alpha(x_.r) - - // Z <- AX + Z. - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, col_major) - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, col_major) - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, col_major) - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, col_major) - - // Z <- transposed(A)X + Z. - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, row_major) - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, row_major) - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, row_major) - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, row_major) - - // Z <- transposed(const A)X + Z. - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, row_major) - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, row_major) - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, row_major) - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, row_major) - - // Z <- conjugated(A)X + Z. - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, row_major) - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, row_major) - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, row_major) - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, row_major) - - // Z <- A scaled(X) + Z. - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, col_major) - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, col_major) - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, col_major) - gemv_interface(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, col_major) - - // Z <- transposed(A) scaled(X) + Z. - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, row_major) - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, row_major) - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, row_major) - gemv_interface(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, row_major) - - // Z <- transposed(const A) scaled(X) + Z. - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, row_major) - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, row_major) - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, row_major) - gemv_interface(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, row_major) - - // Z <- conjugated(A) scaled(X) + Z. - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, row_major) - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, row_major) - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, row_major) - gemv_interface(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, row_major) - - - /* ********************************************************************* */ - /* mult(A, x, y). */ - /* ********************************************************************* */ - -# define gemv_interface2(param1, trans1, param2, trans2, blas_name, \ - base_type, orien) \ - inline void mult_spec(param1(base_type), param2(base_type), \ - std::vector &z, orien) { \ - GMMLAPACK_TRACE("gemv_interface2"); \ - trans1(base_type); trans2(base_type); base_type beta(0); \ - int m(int(mat_nrows(A))), lda(m), n(int(mat_ncols(A))), inc(1); \ - if (m && n) \ - blas_name(&t, &m, &n, &alpha, &A(0,0), &lda, &x[0], &inc, &beta, \ - &z[0], &inc); \ - else gmm::clear(z); \ - } - - // Y <- AX. - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, col_major) - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, col_major) - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, col_major) - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, col_major) - - // Y <- transposed(A)X. - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, row_major) - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, row_major) - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, row_major) - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, row_major) - - // Y <- transposed(const A)X. - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, row_major) - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, row_major) - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, row_major) - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, row_major) - - // Y <- conjugated(A)X. - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, sgemv_, - BLAS_S, row_major) - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, dgemv_, - BLAS_D, row_major) - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, cgemv_, - BLAS_C, row_major) - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_n, gemv_trans2_n, zgemv_, - BLAS_Z, row_major) - - // Y <- A scaled(X). - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, col_major) - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, col_major) - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, col_major) - gemv_interface2(gem_p1_n, gem_trans1_n, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, col_major) - - // Y <- transposed(A) scaled(X). - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, row_major) - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, row_major) - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, row_major) - gemv_interface2(gem_p1_t, gem_trans1_t, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, row_major) - - // Y <- transposed(const A) scaled(X). - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, row_major) - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, row_major) - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, row_major) - gemv_interface2(gem_p1_tc, gem_trans1_t, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, row_major) - - // Y <- conjugated(A) scaled(X). - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, sgemv_, - BLAS_S, row_major) - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, dgemv_, - BLAS_D, row_major) - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, cgemv_, - BLAS_C, row_major) - gemv_interface2(gem_p1_c, gem_trans1_c, gemv_p2_s, gemv_trans2_s, zgemv_, - BLAS_Z, row_major) - - /* ********************************************************************* */ - /* dense matrix x dense matrix multiplication. */ - /* ********************************************************************* */ - -# define gemm_interface_nn(blas_name, base_type) \ - inline void mult_spec(const dense_matrix &A, \ - const dense_matrix &B, \ - dense_matrix &C, c_mult) { \ - GMMLAPACK_TRACE("gemm_interface_nn"); \ - const char t = 'N'; \ - int m(int(mat_nrows(A))), lda = m, k(int(mat_ncols(A))); \ - int n(int(mat_ncols(B))); \ - int ldb = k, ldc = m; \ - base_type alpha(1), beta(0); \ - if (m && k && n) \ - blas_name(&t, &t, &m, &n, &k, &alpha, \ - &A(0,0), &lda, &B(0,0), &ldb, &beta, &C(0,0), &ldc); \ - else gmm::clear(C); \ - } - - gemm_interface_nn(sgemm_, BLAS_S) - gemm_interface_nn(dgemm_, BLAS_D) - gemm_interface_nn(cgemm_, BLAS_C) - gemm_interface_nn(zgemm_, BLAS_Z) - - /* ********************************************************************* */ - /* transposed(dense matrix) x dense matrix multiplication. */ - /* ********************************************************************* */ - -# define gemm_interface_tn(blas_name, base_type, is_const) \ - inline void mult_spec( \ - const transposed_col_ref *> &A_,\ - const dense_matrix &B, \ - dense_matrix &C, rcmult) { \ - GMMLAPACK_TRACE("gemm_interface_tn"); \ - dense_matrix &A \ - = const_cast &>(*(linalg_origin(A_))); \ - const char t = 'T', u = 'N'; \ - int m(int(mat_ncols(A))), k(int(mat_nrows(A))), n(int(mat_ncols(B))); \ - int lda = k, ldb = k, ldc = m; \ - base_type alpha(1), beta(0); \ - if (m && k && n) \ - blas_name(&t, &u, &m, &n, &k, &alpha, \ - &A(0,0), &lda, &B(0,0), &ldb, &beta, &C(0,0), &ldc); \ - else gmm::clear(C); \ - } - - gemm_interface_tn(sgemm_, BLAS_S,) - gemm_interface_tn(dgemm_, BLAS_D,) - gemm_interface_tn(cgemm_, BLAS_C,) - gemm_interface_tn(zgemm_, BLAS_Z,) - gemm_interface_tn(sgemm_, BLAS_S, const) - gemm_interface_tn(dgemm_, BLAS_D, const) - gemm_interface_tn(cgemm_, BLAS_C, const) - gemm_interface_tn(zgemm_, BLAS_Z, const) - - /* ********************************************************************* */ - /* dense matrix x transposed(dense matrix) multiplication. */ - /* ********************************************************************* */ - -# define gemm_interface_nt(blas_name, base_type, is_const) \ - inline void mult_spec(const dense_matrix &A, \ - const transposed_col_ref *> &B_,\ - dense_matrix &C, r_mult) { \ - GMMLAPACK_TRACE("gemm_interface_nt"); \ - dense_matrix &B \ - = const_cast &>(*(linalg_origin(B_))); \ - const char t = 'N', u = 'T'; \ - int m(int(mat_nrows(A))), lda = m, k(int(mat_ncols(A))); \ - int n(int(mat_nrows(B))); \ - int ldb = n, ldc = m; \ - base_type alpha(1), beta(0); \ - if (m && k && n) \ - blas_name(&t, &u, &m, &n, &k, &alpha, \ - &A(0,0), &lda, &B(0,0), &ldb, &beta, &C(0,0), &ldc); \ - else gmm::clear(C); \ - } - - gemm_interface_nt(sgemm_, BLAS_S,) - gemm_interface_nt(dgemm_, BLAS_D,) - gemm_interface_nt(cgemm_, BLAS_C,) - gemm_interface_nt(zgemm_, BLAS_Z,) - gemm_interface_nt(sgemm_, BLAS_S, const) - gemm_interface_nt(dgemm_, BLAS_D, const) - gemm_interface_nt(cgemm_, BLAS_C, const) - gemm_interface_nt(zgemm_, BLAS_Z, const) - - /* ********************************************************************* */ - /* transposed(dense matrix) x transposed(dense matrix) multiplication. */ - /* ********************************************************************* */ - -# define gemm_interface_tt(blas_name, base_type, isA_const, isB_const) \ - inline void mult_spec( \ - const transposed_col_ref *> &A_,\ - const transposed_col_ref *> &B_,\ - dense_matrix &C, r_mult) { \ - GMMLAPACK_TRACE("gemm_interface_tt"); \ - dense_matrix &A \ - = const_cast &>(*(linalg_origin(A_))); \ - dense_matrix &B \ - = const_cast &>(*(linalg_origin(B_))); \ - const char t = 'T', u = 'T'; \ - int m(int(mat_ncols(A))), k(int(mat_nrows(A))), n(int(mat_nrows(B))); \ - int lda = k, ldb = n, ldc = m; \ - base_type alpha(1), beta(0); \ - if (m && k && n) \ - blas_name(&t, &u, &m, &n, &k, &alpha, \ - &A(0,0), &lda, &B(0,0), &ldb, &beta, &C(0,0), &ldc); \ - else gmm::clear(C); \ - } - - gemm_interface_tt(sgemm_, BLAS_S,,) - gemm_interface_tt(dgemm_, BLAS_D,,) - gemm_interface_tt(cgemm_, BLAS_C,,) - gemm_interface_tt(zgemm_, BLAS_Z,,) - gemm_interface_tt(sgemm_, BLAS_S, const,) - gemm_interface_tt(dgemm_, BLAS_D, const,) - gemm_interface_tt(cgemm_, BLAS_C, const,) - gemm_interface_tt(zgemm_, BLAS_Z, const,) - gemm_interface_tt(sgemm_, BLAS_S,, const) - gemm_interface_tt(dgemm_, BLAS_D,, const) - gemm_interface_tt(cgemm_, BLAS_C,, const) - gemm_interface_tt(zgemm_, BLAS_Z,, const) - gemm_interface_tt(sgemm_, BLAS_S, const, const) - gemm_interface_tt(dgemm_, BLAS_D, const, const) - gemm_interface_tt(cgemm_, BLAS_C, const, const) - gemm_interface_tt(zgemm_, BLAS_Z, const, const) - - - /* ********************************************************************* */ - /* conjugated(dense matrix) x dense matrix multiplication. */ - /* ********************************************************************* */ - -# define gemm_interface_cn(blas_name, base_type) \ - inline void mult_spec( \ - const conjugated_col_matrix_const_ref > &A_,\ - const dense_matrix &B, \ - dense_matrix &C, rcmult) { \ - GMMLAPACK_TRACE("gemm_interface_cn"); \ - dense_matrix &A \ - = const_cast &>(*(linalg_origin(A_))); \ - const char t = 'C', u = 'N'; \ - int m(int(mat_ncols(A))), k(int(mat_nrows(A))), n(int(mat_ncols(B))); \ - int lda = k, ldb = k, ldc = m; \ - base_type alpha(1), beta(0); \ - if (m && k && n) \ - blas_name(&t, &u, &m, &n, &k, &alpha, \ - &A(0,0), &lda, &B(0,0), &ldb, &beta, &C(0,0), &ldc); \ - else gmm::clear(C); \ - } - - gemm_interface_cn(sgemm_, BLAS_S) - gemm_interface_cn(dgemm_, BLAS_D) - gemm_interface_cn(cgemm_, BLAS_C) - gemm_interface_cn(zgemm_, BLAS_Z) - - /* ********************************************************************* */ - /* dense matrix x conjugated(dense matrix) multiplication. */ - /* ********************************************************************* */ - -# define gemm_interface_nc(blas_name, base_type) \ - inline void mult_spec(const dense_matrix &A, \ - const conjugated_col_matrix_const_ref > &B_,\ - dense_matrix &C, c_mult, row_major) { \ - GMMLAPACK_TRACE("gemm_interface_nc"); \ - dense_matrix &B \ - = const_cast &>(*(linalg_origin(B_))); \ - const char t = 'N', u = 'C'; \ - int m(int(mat_nrows(A))), lda = m, k(int(mat_ncols(A))); \ - int n(int(mat_nrows(B))), ldb = n, ldc = m; \ - base_type alpha(1), beta(0); \ - if (m && k && n) \ - blas_name(&t, &u, &m, &n, &k, &alpha, \ - &A(0,0), &lda, &B(0,0), &ldb, &beta, &C(0,0), &ldc); \ - else gmm::clear(C); \ - } - - gemm_interface_nc(sgemm_, BLAS_S) - gemm_interface_nc(dgemm_, BLAS_D) - gemm_interface_nc(cgemm_, BLAS_C) - gemm_interface_nc(zgemm_, BLAS_Z) - - /* ********************************************************************* */ - /* conjugated(dense matrix) x conjugated(dense matrix) multiplication. */ - /* ********************************************************************* */ - -# define gemm_interface_cc(blas_name, base_type) \ - inline void mult_spec( \ - const conjugated_col_matrix_const_ref > &A_,\ - const conjugated_col_matrix_const_ref > &B_,\ - dense_matrix &C, r_mult) { \ - GMMLAPACK_TRACE("gemm_interface_cc"); \ - dense_matrix &A \ - = const_cast &>(*(linalg_origin(A_))); \ - dense_matrix &B \ - = const_cast &>(*(linalg_origin(B_))); \ - const char t = 'C', u = 'C'; \ - int m(int(mat_ncols(A))), k(int(mat_nrows(A))), lda = k; \ - int n(int(mat_nrows(B))), ldb = n, ldc = m; \ - base_type alpha(1), beta(0); \ - if (m && k && n) \ - blas_name(&t, &u, &m, &n, &k, &alpha, \ - &A(0,0), &lda, &B(0,0), &ldb, &beta, &C(0,0), &ldc); \ - else gmm::clear(C); \ - } - - gemm_interface_cc(sgemm_, BLAS_S) - gemm_interface_cc(dgemm_, BLAS_D) - gemm_interface_cc(cgemm_, BLAS_C) - gemm_interface_cc(zgemm_, BLAS_Z) - - /* ********************************************************************* */ - /* Tri solve. */ - /* ********************************************************************* */ - -# define trsv_interface(f_name, loru, param1, trans1, blas_name, base_type)\ - inline void f_name(param1(base_type), std::vector &x, \ - size_type k, bool is_unit) { \ - GMMLAPACK_TRACE("trsv_interface"); \ - loru; trans1(base_type); char d = is_unit ? 'U' : 'N'; \ - int lda(int(mat_nrows(A))), inc(1), n = int(k); \ - if (lda) blas_name(&l, &t, &d, &n, &A(0,0), &lda, &x[0], &inc); \ - } - -# define trsv_upper const char l = 'U' -# define trsv_lower const char l = 'L' - - // X <- LOWER(A)^{-1}X. - trsv_interface(lower_tri_solve, trsv_lower, gem_p1_n, gem_trans1_n, - strsv_, BLAS_S) - trsv_interface(lower_tri_solve, trsv_lower, gem_p1_n, gem_trans1_n, - dtrsv_, BLAS_D) - trsv_interface(lower_tri_solve, trsv_lower, gem_p1_n, gem_trans1_n, - ctrsv_, BLAS_C) - trsv_interface(lower_tri_solve, trsv_lower, gem_p1_n, gem_trans1_n, - ztrsv_, BLAS_Z) - - // X <- UPPER(A)^{-1}X. - trsv_interface(upper_tri_solve, trsv_upper, gem_p1_n, gem_trans1_n, - strsv_, BLAS_S) - trsv_interface(upper_tri_solve, trsv_upper, gem_p1_n, gem_trans1_n, - dtrsv_, BLAS_D) - trsv_interface(upper_tri_solve, trsv_upper, gem_p1_n, gem_trans1_n, - ctrsv_, BLAS_C) - trsv_interface(upper_tri_solve, trsv_upper, gem_p1_n, gem_trans1_n, - ztrsv_, BLAS_Z) - - // X <- LOWER(transposed(A))^{-1}X. - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_t, gem_trans1_t, - strsv_, BLAS_S) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_t, gem_trans1_t, - dtrsv_, BLAS_D) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_t, gem_trans1_t, - ctrsv_, BLAS_C) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_t, gem_trans1_t, - ztrsv_, BLAS_Z) - - // X <- UPPER(transposed(A))^{-1}X. - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_t, gem_trans1_t, - strsv_, BLAS_S) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_t, gem_trans1_t, - dtrsv_, BLAS_D) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_t, gem_trans1_t, - ctrsv_, BLAS_C) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_t, gem_trans1_t, - ztrsv_, BLAS_Z) - - // X <- LOWER(transposed(const A))^{-1}X. - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_tc, gem_trans1_t, - strsv_, BLAS_S) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_tc, gem_trans1_t, - dtrsv_, BLAS_D) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_tc, gem_trans1_t, - ctrsv_, BLAS_C) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_tc, gem_trans1_t, - ztrsv_, BLAS_Z) - - // X <- UPPER(transposed(const A))^{-1}X. - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_tc, gem_trans1_t, - strsv_, BLAS_S) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_tc, gem_trans1_t, - dtrsv_, BLAS_D) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_tc, gem_trans1_t, - ctrsv_, BLAS_C) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_tc, gem_trans1_t, - ztrsv_, BLAS_Z) - - // X <- LOWER(conjugated(A))^{-1}X. - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_c, gem_trans1_c, - strsv_, BLAS_S) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_c, gem_trans1_c, - dtrsv_, BLAS_D) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_c, gem_trans1_c, - ctrsv_, BLAS_C) - trsv_interface(lower_tri_solve, trsv_upper, gem_p1_c, gem_trans1_c, - ztrsv_, BLAS_Z) - - // X <- UPPER(conjugated(A))^{-1}X. - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_c, gem_trans1_c, - strsv_, BLAS_S) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_c, gem_trans1_c, - dtrsv_, BLAS_D) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_c, gem_trans1_c, - ctrsv_, BLAS_C) - trsv_interface(upper_tri_solve, trsv_lower, gem_p1_c, gem_trans1_c, - ztrsv_, BLAS_Z) - -} - -#endif // GMM_BLAS_INTERFACE_H - -#endif // GMM_USES_BLAS diff --git a/include/gmm/gmm_condition_number.h b/include/gmm/gmm_condition_number.h deleted file mode 100644 index 2a2aa2ac5da..00000000000 --- a/include/gmm/gmm_condition_number.h +++ /dev/null @@ -1,142 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_condition_number.h - @author Yves Renard , Julien Pommier - @date August 27, 2003. - @brief computation of the condition number of dense matrices. -*/ -#ifndef GMM_CONDITION_NUMBER_H__ -#define GMM_CONDITION_NUMBER_H__ - -#include "gmm_dense_qr.h" - -namespace gmm { - - /** computation of the condition number of dense matrices using SVD. - - Uses symmetric_qr_algorithm => dense matrices only. - - @param M a matrix. - @param emin smallest (in magnitude) eigenvalue - @param emax largest eigenvalue. - */ - template - typename number_traits::value_type>::magnitude_type - condition_number(const MAT& M, - typename number_traits::value_type>::magnitude_type& emin, - typename number_traits::value_type>::magnitude_type& emax) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - size_type m = mat_nrows(M), n = mat_ncols(M); - emax = emin = R(0); - std::vector eig(m+n); - - if (m+n == 0) return R(0); - if (is_hermitian(M)) { - eig.resize(m); - gmm::symmetric_qr_algorithm(M, eig); - } - else { - dense_matrix B(m+n, m+n); // not very efficient ?? - gmm::copy(conjugated(M), sub_matrix(B, sub_interval(m, n), sub_interval(0, m))); - gmm::copy(M, sub_matrix(B, sub_interval(0, m), - sub_interval(m, n))); - gmm::symmetric_qr_algorithm(B, eig); - } - emin = emax = gmm::abs(eig[0]); - for (size_type i = 1; i < eig.size(); ++i) { - R e = gmm::abs(eig[i]); - emin = std::min(emin, e); - emax = std::max(emax, e); - } - // cout << "emin = " << emin << " emax = " << emax << endl; - if (emin == R(0)) return gmm::default_max(R()); - return emax / emin; - } - - template - typename number_traits::value_type>::magnitude_type - condition_number(const MAT& M) { - typename number_traits::value_type>::magnitude_type emax, emin; - return condition_number(M, emin, emax); - } - - template - typename number_traits::value_type>::magnitude_type - Frobenius_condition_number_sqr(const MAT& M) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - size_type m = mat_nrows(M), n = mat_ncols(M); - dense_matrix B(std::min(m,n), std::min(m,n)); - if (m < n) mult(M,gmm::conjugated(M),B); - else mult(gmm::conjugated(M),M,B); - R trB = abs(mat_trace(B)); - lu_inverse(B); - return trB*abs(mat_trace(B)); - } - - template - typename number_traits::value_type>::magnitude_type - Frobenius_condition_number(const MAT& M) - { return sqrt(Frobenius_condition_number_sqr(M)); } - - /** estimation of the condition number (TO BE DONE...) - */ - template - typename number_traits::value_type>::magnitude_type - condest(const MAT& M, - typename number_traits::value_type>::magnitude_type& emin, - typename number_traits::value_type>::magnitude_type& emax) { - return condition_number(M, emin, emax); - } - - template - typename number_traits::value_type>::magnitude_type - condest(const MAT& M) { - typename number_traits::value_type>::magnitude_type emax, emin; - return condest(M, emin, emax); - } -} - -#endif diff --git a/include/gmm/gmm_conjugated.h b/include/gmm/gmm_conjugated.h deleted file mode 100644 index 905b6464d4f..00000000000 --- a/include/gmm/gmm_conjugated.h +++ /dev/null @@ -1,395 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_conjugated.h - @author Yves Renard - @date September 18, 2003. - @brief handle conjugation of complex matrices/vectors. -*/ -#ifndef GMM_CONJUGATED_H__ -#define GMM_CONJUGATED_H__ - -#include "gmm_def.h" - -namespace gmm { - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - /* ********************************************************************* */ - /* Conjugated references on vectors */ - /* ********************************************************************* */ - - template struct conjugated_const_iterator { - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::difference_type difference_type; - typedef typename std::iterator_traits::iterator_category - iterator_category; - - IT it; - - conjugated_const_iterator(void) {} - conjugated_const_iterator(const IT &i) : it(i) {} - - inline size_type index(void) const { return it.index(); } - conjugated_const_iterator operator ++(int) - { conjugated_const_iterator tmp = *this; ++it; return tmp; } - conjugated_const_iterator operator --(int) - { conjugated_const_iterator tmp = *this; --it; return tmp; } - conjugated_const_iterator &operator ++() { ++it; return *this; } - conjugated_const_iterator &operator --() { --it; return *this; } - conjugated_const_iterator &operator +=(difference_type i) - { it += i; return *this; } - conjugated_const_iterator &operator -=(difference_type i) - { it -= i; return *this; } - conjugated_const_iterator operator +(difference_type i) const - { conjugated_const_iterator itb = *this; return (itb += i); } - conjugated_const_iterator operator -(difference_type i) const - { conjugated_const_iterator itb = *this; return (itb -= i); } - difference_type operator -(const conjugated_const_iterator &i) const - { return difference_type(it - i.it); } - - value_type operator *() const { return gmm::conj(*it); } - value_type operator [](size_type ii) const { return gmm::conj(it[ii]); } - - bool operator ==(const conjugated_const_iterator &i) const - { return (i.it == it); } - bool operator !=(const conjugated_const_iterator &i) const - { return (i.it != it); } - bool operator < (const conjugated_const_iterator &i) const - { return (it < i.it); } - }; - - template struct conjugated_vector_const_ref { - typedef conjugated_vector_const_ref this_type; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::const_iterator iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::origin_type origin_type; - - iterator begin_, end_; - const origin_type *origin; - size_type size_; - - conjugated_vector_const_ref(const V &v) - : begin_(vect_const_begin(v)), end_(vect_const_end(v)), - origin(linalg_origin(v)), - size_(vect_size(v)) {} - - reference operator[](size_type i) const - { return gmm::conj(linalg_traits::access(origin, begin_, end_, i)); } - }; - - template struct linalg_traits > { - typedef conjugated_vector_const_ref this_type; - typedef typename linalg_traits::origin_type origin_type; - typedef linalg_const is_reference; - typedef abstract_vector linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef value_type reference; - typedef abstract_null_type iterator; - typedef conjugated_const_iterator::const_iterator> const_iterator; - typedef typename linalg_traits::storage_type storage_type; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type size(const this_type &v) { return v.size_; } - static iterator begin(this_type &v) { return iterator(v.begin_); } - static const_iterator begin(const this_type &v) - { return const_iterator(v.begin_); } - static iterator end(this_type &v) - { return iterator(v.end_); } - static const_iterator end(const this_type &v) - { return const_iterator(v.end_); } - static value_type access(const origin_type *o, const const_iterator &it, - const const_iterator &ite, size_type i) - { return gmm::conj(linalg_traits::access(o, it.it, ite.it, i)); } - static const origin_type* origin(const this_type &v) { return v.origin; } - }; - - template std::ostream &operator << - (std::ostream &o, const conjugated_vector_const_ref& m) - { gmm::write(o,m); return o; } - - /* ********************************************************************* */ - /* Conjugated references on matrices */ - /* ********************************************************************* */ - - template struct conjugated_row_const_iterator { - typedef conjugated_row_const_iterator iterator; - typedef typename linalg_traits::const_row_iterator ITER; - typedef typename linalg_traits::value_type value_type; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - - ITER it; - - iterator operator ++(int) { iterator tmp = *this; it++; return tmp; } - iterator operator --(int) { iterator tmp = *this; it--; return tmp; } - iterator &operator ++() { it++; return *this; } - iterator &operator --() { it--; return *this; } - iterator &operator +=(difference_type i) { it += i; return *this; } - iterator &operator -=(difference_type i) { it -= i; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const - { return it - i.it; } - - ITER operator *() const { return it; } - ITER operator [](int i) { return it + i; } - - bool operator ==(const iterator &i) const { return (it == i.it); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (it < i.it); } - - conjugated_row_const_iterator(void) {} - conjugated_row_const_iterator(const ITER &i) : it(i) { } - - }; - - template struct conjugated_row_matrix_const_ref { - - typedef conjugated_row_matrix_const_ref this_type; - typedef typename linalg_traits::const_row_iterator iterator; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::origin_type origin_type; - - iterator begin_, end_; - const origin_type *origin; - size_type nr, nc; - - conjugated_row_matrix_const_ref(const M &m) - : begin_(mat_row_begin(m)), end_(mat_row_end(m)), - origin(linalg_origin(m)), nr(mat_ncols(m)), nc(mat_nrows(m)) {} - - value_type operator()(size_type i, size_type j) const - { return gmm::conj(linalg_traits::access(begin_+j, i)); } - }; - - template - struct linalg_traits > { - typedef conjugated_row_matrix_const_ref this_type; - typedef typename linalg_traits::origin_type origin_type; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef value_type reference; - typedef typename linalg_traits::storage_type storage_type; - typedef typename linalg_traits::const_sub_row_type vector_type; - typedef conjugated_vector_const_ref sub_col_type; - typedef conjugated_vector_const_ref const_sub_col_type; - typedef conjugated_row_const_iterator col_iterator; - typedef conjugated_row_const_iterator const_col_iterator; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_row_iterator; - typedef abstract_null_type row_iterator; - typedef col_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static inline size_type ncols(const this_type &m) { return m.nc; } - static inline size_type nrows(const this_type &m) { return m.nr; } - static inline const_sub_col_type col(const const_col_iterator &it) - { return conjugated(linalg_traits::row(it.it)); } - static inline const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m.begin_); } - static inline const_col_iterator col_end(const this_type &m) - { return const_col_iterator(m.end_); } - static inline const origin_type* origin(const this_type &m) - { return m.origin; } - static value_type access(const const_col_iterator &it, size_type i) - { return gmm::conj(linalg_traits::access(it.it, i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const conjugated_row_matrix_const_ref& m) - { gmm::write(o,m); return o; } - - - template struct conjugated_col_const_iterator { - typedef conjugated_col_const_iterator iterator; - typedef typename linalg_traits::const_col_iterator ITER; - typedef typename linalg_traits::value_type value_type; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - - ITER it; - - iterator operator ++(int) { iterator tmp = *this; it++; return tmp; } - iterator operator --(int) { iterator tmp = *this; it--; return tmp; } - iterator &operator ++() { it++; return *this; } - iterator &operator --() { it--; return *this; } - iterator &operator +=(difference_type i) { it += i; return *this; } - iterator &operator -=(difference_type i) { it -= i; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const - { return it - i.it; } - - ITER operator *() const { return it; } - ITER operator [](int i) { return it + i; } - - bool operator ==(const iterator &i) const { return (it == i.it); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (it < i.it); } - - conjugated_col_const_iterator(void) {} - conjugated_col_const_iterator(const ITER &i) : it(i) { } - - }; - - template struct conjugated_col_matrix_const_ref { - - typedef conjugated_col_matrix_const_ref this_type; - typedef typename linalg_traits::const_col_iterator iterator; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::origin_type origin_type; - - iterator begin_, end_; - const origin_type *origin; - size_type nr, nc; - - conjugated_col_matrix_const_ref(const M &m) - : begin_(mat_col_begin(m)), end_(mat_col_end(m)), - origin(linalg_origin(m)), nr(mat_ncols(m)), nc(mat_nrows(m)) {} - - value_type operator()(size_type i, size_type j) const - { return gmm::conj(linalg_traits::access(begin_+i, j)); } - }; - - template - struct linalg_traits > { - typedef conjugated_col_matrix_const_ref this_type; - typedef typename linalg_traits::origin_type origin_type; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef value_type reference; - typedef typename linalg_traits::storage_type storage_type; - typedef typename linalg_traits::const_sub_col_type vector_type; - typedef conjugated_vector_const_ref sub_row_type; - typedef conjugated_vector_const_ref const_sub_row_type; - typedef conjugated_col_const_iterator row_iterator; - typedef conjugated_col_const_iterator const_row_iterator; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_col_iterator; - typedef abstract_null_type col_iterator; - typedef row_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static inline size_type nrows(const this_type &m) { return m.nr; } - static inline size_type ncols(const this_type &m) { return m.nc; } - static inline const_sub_row_type row(const const_row_iterator &it) - { return conjugated(linalg_traits::col(it.it)); } - static inline const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m.begin_); } - static inline const_row_iterator row_end(const this_type &m) - { return const_row_iterator(m.end_); } - static inline const origin_type* origin(const this_type &m) - { return m.origin; } - static value_type access(const const_row_iterator &it, size_type i) - { return gmm::conj(linalg_traits::access(it.it, i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const conjugated_col_matrix_const_ref& m) - { gmm::write(o,m); return o; } - - - template struct conjugated_return__ { - typedef conjugated_row_matrix_const_ref return_type; - }; - template struct conjugated_return__ { - typedef conjugated_col_matrix_const_ref return_type; - }; - template struct conjugated_return_ { - typedef const L & return_type; - }; - template - struct conjugated_return_, abstract_vector> { - typedef conjugated_vector_const_ref return_type; - }; - template - struct conjugated_return_ { - typedef typename conjugated_return__::sub_orientation>::potype - >::return_type return_type; - }; - template struct conjugated_return { - typedef typename - conjugated_return_::value_type, - typename linalg_traits::linalg_type - >::return_type return_type; - }; - - ///@endcond - /** return a conjugated view of the input matrix or vector. */ - template inline - typename conjugated_return::return_type - conjugated(const L &v) { - return conjugated(v, typename linalg_traits::value_type(), - typename linalg_traits::linalg_type()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - template inline - const L & conjugated(const L &v, T, LT) { return v; } - - template inline - conjugated_vector_const_ref conjugated(const L &v, std::complex, - abstract_vector) - { return conjugated_vector_const_ref(v); } - - template inline - typename conjugated_return__::sub_orientation>::potype>::return_type - conjugated(const L &v, T, abstract_matrix) { - return conjugated(v, typename principal_orientation_type::sub_orientation>::potype()); - } - - template inline - conjugated_row_matrix_const_ref conjugated(const L &v, row_major) - { return conjugated_row_matrix_const_ref(v); } - - template inline - conjugated_col_matrix_const_ref conjugated(const L &v, col_major) - { return conjugated_col_matrix_const_ref(v); } - - ///@endcond - - -} - -#endif // GMM_CONJUGATED_H__ diff --git a/include/gmm/gmm_def.h b/include/gmm/gmm_def.h deleted file mode 100644 index deb6ef414bd..00000000000 --- a/include/gmm/gmm_def.h +++ /dev/null @@ -1,1117 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_def.h - @author Yves Renard - @date October 13, 2002. - @brief Basic definitions and tools of GMM. -*/ -#ifndef GMM_DEF_H__ -#define GMM_DEF_H__ - -#include "gmm_ref.h" -#include - -#ifndef M_PI -# define M_E 2.7182818284590452354 /* e */ -# define M_LOG2E 1.4426950408889634074 /* 1/ln(2) */ -# define M_LOG10E 0.43429448190325182765 /* 1/ln(10) */ -# define M_LN2 0.69314718055994530942 /* ln(2) */ -# define M_LN10 2.30258509299404568402 /* ln(10) */ -# define M_PI 3.14159265358979323846 /* pi */ -# define M_PI_2 1.57079632679489661923 /* pi/2 */ -# define M_PI_4 0.78539816339744830962 /* pi/4 */ -# define M_1_PI 0.31830988618379067154 /* 1/pi */ -# define M_2_PI 0.63661977236758134308 /* 2/pi */ -# define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */ -# define M_SQRT2 1.41421356237309504880 /* sqrt(2) */ -# define M_SQRT1_2 0.70710678118654752440 /* sqrt(2)/2 */ -#endif - -#ifndef M_PIl -# define M_PIl 3.1415926535897932384626433832795029L /* pi */ -# define M_PI_2l 1.5707963267948966192313216916397514L /* pi/2 */ -# define M_PI_4l 0.7853981633974483096156608458198757L /* pi/4 */ -# define M_1_PIl 0.3183098861837906715377675267450287L /* 1/pi */ -# define M_2_PIl 0.6366197723675813430755350534900574L /* 2/pi */ -# define M_2_SQRTPIl 1.1283791670955125738961589031215452L /* 2/sqrt(pi) */ -#endif - -namespace gmm { - - typedef size_t size_type; - - /* ******************************************************************** */ - /* Specifier types */ - /* ******************************************************************** */ - /* not perfectly null, required by aCC 3.33 */ - struct abstract_null_type { - abstract_null_type(int=0) {} - template void operator()(A,B,C) {} - }; // specify an information lake. - - struct linalg_true {}; - struct linalg_false {}; - - template struct linalg_and - { typedef linalg_false bool_type; }; - template <> struct linalg_and - { typedef linalg_true bool_type; }; - template struct linalg_or - { typedef linalg_true bool_type; }; - template <> struct linalg_and - { typedef linalg_false bool_type; }; - - struct linalg_const {}; // A reference is either linalg_const, - struct linalg_modifiable {}; // linalg_modifiable or linalg_false. - - struct abstract_vector {}; // The object is a vector - struct abstract_matrix {}; // The object is a matrix - - struct abstract_sparse {}; // sparse matrix or vector - struct abstract_skyline {}; // 'sky-line' matrix or vector - struct abstract_dense {}; // dense matrix or vector - struct abstract_indirect {}; // matrix given by the product with a vector - - struct row_major {}; // matrix with a row access. - struct col_major {}; // matrix with a column access - struct row_and_col {}; // both accesses but row preference - struct col_and_row {}; // both accesses but column preference - - template struct transposed_type; - template<> struct transposed_type {typedef col_major t_type;}; - template<> struct transposed_type {typedef row_major t_type;}; - template<> struct transposed_type {typedef col_and_row t_type;}; - template<> struct transposed_type {typedef row_and_col t_type;}; - - template struct principal_orientation_type - { typedef abstract_null_type potype; }; - template<> struct principal_orientation_type - { typedef row_major potype; }; - template<> struct principal_orientation_type - { typedef col_major potype; }; - template<> struct principal_orientation_type - { typedef row_major potype; }; - template<> struct principal_orientation_type - { typedef col_major potype; }; - - // template struct linalg_traits; - template struct linalg_traits { - typedef abstract_null_type this_type; - typedef abstract_null_type linalg_type; - typedef abstract_null_type value_type; - typedef abstract_null_type is_reference; - typedef abstract_null_type& reference; - typedef abstract_null_type* iterator; - typedef const abstract_null_type* const_iterator; - typedef abstract_null_type index_sorted; - typedef abstract_null_type storage_type; - typedef abstract_null_type origin_type; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_row_iterator; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_col_iterator; - typedef abstract_null_type col_iterator; - typedef abstract_null_type sub_orientation; - }; - - template struct vect_ref_type; - template struct vect_ref_type

{ - typedef typename linalg_traits::reference access_type; - typedef typename linalg_traits::iterator iterator; - }; - template struct vect_ref_type { - typedef typename linalg_traits::value_type access_type; - typedef typename linalg_traits::const_iterator iterator; - }; - - template struct const_pointer; - template struct const_pointer

- { typedef const P* pointer; }; - template struct const_pointer - { typedef const P* pointer; }; - - template struct modifiable_pointer; - template struct modifiable_pointer

- { typedef P* pointer; }; - template struct modifiable_pointer - { typedef P* pointer; }; - - template struct const_reference; - template struct const_reference - { typedef const R &reference; }; - template struct const_reference - { typedef const R &reference; }; - - - inline bool is_sparse(abstract_sparse) { return true; } - inline bool is_sparse(abstract_dense) { return false; } - inline bool is_sparse(abstract_skyline) { return true; } - inline bool is_sparse(abstract_indirect) { return false; } - - template inline bool is_sparse(const L &) - { return is_sparse(typename linalg_traits::storage_type()); } - - inline bool is_row_matrix_(row_major) { return true; } - inline bool is_row_matrix_(col_major) { return false; } - inline bool is_row_matrix_(row_and_col) { return true; } - inline bool is_row_matrix_(col_and_row) { return true; } - - template inline bool is_row_matrix(const L &) - { return is_row_matrix_(typename linalg_traits::sub_orientation()); } - - inline bool is_col_matrix_(row_major) { return false; } - inline bool is_col_matrix_(col_major) { return true; } - inline bool is_col_matrix_(row_and_col) { return true; } - inline bool is_col_matrix_(col_and_row) { return true; } - - template inline bool is_col_matrix(const L &) - { return is_col_matrix_(typename linalg_traits::sub_orientation()); } - - inline bool is_col_matrix(row_major) { return false; } - inline bool is_col_matrix(col_major) { return true; } - inline bool is_row_matrix(row_major) { return true; } - inline bool is_row_matrix(col_major) { return false; } - - template inline bool is_const_reference(L) { return false; } - inline bool is_const_reference(linalg_const) { return true; } - - - template struct is_gmm_interfaced_ { - typedef linalg_true result; - }; - - template<> struct is_gmm_interfaced_ { - typedef linalg_false result; - }; - - template struct is_gmm_interfaced { - typedef typename is_gmm_interfaced_::this_type >::result result; - }; - - /* ******************************************************************** */ - /* types to deal with const object representing a modifiable reference */ - /* ******************************************************************** */ - - template struct mref_type_ - { typedef abstract_null_type return_type; }; - template struct mref_type_ - { typedef L & return_type; }; - template struct mref_type_ - { typedef const L & return_type; }; - template struct mref_type_ - { typedef const L & return_type; }; - template struct mref_type_ - { typedef const L & return_type; }; - template struct mref_type_ - { typedef L & return_type; }; - template struct mref_type_ - { typedef L & return_type; }; - - template struct mref_type { - typedef typename std::iterator_traits::value_type L; - typedef typename mref_type_::is_reference>::return_type return_type; - }; - - template typename mref_type::return_type - linalg_cast(const L &l) - { return const_cast::return_type>(l); } - - template typename mref_type::return_type linalg_cast(L &l) - { return const_cast::return_type>(l); } - - template struct cref_type_ - { typedef abstract_null_type return_type; }; - template struct cref_type_ - { typedef L & return_type; }; - template struct cref_type { - typedef typename cref_type_::is_reference>::return_type return_type; - }; - - template typename cref_type::return_type - linalg_const_cast(const L &l) - { return const_cast::return_type>(l); } - - - // To be used to select between a reference or a const refercence for - // the return type of a function - // select_return return C1 if L is a const reference, - // C2 otherwise. - // select_return return C2 if L is a modifiable reference - // C1 otherwise. - template struct select_return_ { - typedef abstract_null_type return_type; - }; - template - struct select_return_ { typedef C1 return_type; }; - template - struct select_return_ { typedef C2 return_type; }; - template struct select_return { - typedef typename std::iterator_traits::value_type L; - typedef typename select_return_::return_type>::return_type return_type; - }; - - - // To be used to select between a reference or a const refercence inside - // a structure or a linagl_traits - // select_ref return C1 if L is a const reference, - // C2 otherwise. - // select_ref return C2 in any case. - template struct select_ref_ - { typedef abstract_null_type ref_type; }; - template - struct select_ref_ { typedef C1 ref_type; }; - template - struct select_ref_ { typedef C2 ref_type; }; - template struct select_ref { - typedef typename std::iterator_traits::value_type L; - typedef typename select_ref_::return_type>::ref_type ref_type; - }; - template - struct select_ref - { typedef C1 ref_type; }; - - - template struct is_a_reference_ - { typedef linalg_true reference; }; - template<> struct is_a_reference_ - { typedef linalg_false reference; }; - - template struct is_a_reference { - typedef typename is_a_reference_::is_reference> - ::reference reference; - }; - - - template inline bool is_original_linalg(const L &) - { return is_original_linalg(typename is_a_reference::reference()); } - inline bool is_original_linalg(linalg_false) { return true; } - inline bool is_original_linalg(linalg_true) { return false; } - - - template struct which_reference - { typedef abstract_null_type is_reference; }; - template struct which_reference - { typedef linalg_modifiable is_reference; }; - template struct which_reference - { typedef linalg_const is_reference; }; - - - template struct select_orientation_ - { typedef abstract_null_type return_type; }; - template - struct select_orientation_ - { typedef C1 return_type; }; - template - struct select_orientation_ - { typedef C2 return_type; }; - template struct select_orientation { - typedef typename select_orientation_::sub_orientation>::potype>::return_type return_type; - }; - - /* ******************************************************************** */ - /* Operations on scalars */ - /* ******************************************************************** */ - - template inline T sqr(T a) { return T(a * a); } - template inline T abs(T a) { return (a < T(0)) ? T(-a) : a; } - template inline T abs(std::complex a) - { T x = a.real(), y = a.imag(); return T(::sqrt(x*x+y*y)); } - template inline T abs_sqr(T a) { return T(a*a); } - template inline T abs_sqr(std::complex a) - { return gmm::sqr(a.real()) + gmm::sqr(a.imag()); } - template inline T pos(T a) { return (a < T(0)) ? T(0) : a; } - template inline T neg(T a) { return (a < T(0)) ? T(-a) : T(0); } - template inline T sgn(T a) { return (a < T(0)) ? T(-1) : T(1); } - inline double random() { return double(rand())/(RAND_MAX+0.5); } - template inline T random(T) - { return T(rand()*2.0)/(T(RAND_MAX)+T(1)/T(2)) - T(1); } - template inline std::complex random(std::complex) - { return std::complex(gmm::random(T()), gmm::random(T())); } - template inline T irandom(T max) - { return T(gmm::random() * double(max)); } - template inline T conj(T a) { return a; } - template inline std::complex conj(std::complex a) - { return std::conj(a); } - template inline T real(T a) { return a; } - template inline T real(std::complex a) { return a.real(); } - template inline T imag(T ) { return T(0); } - template inline T imag(std::complex a) { return a.imag(); } - template inline T sqrt(T a) { return T(::sqrt(a)); } - template inline std::complex sqrt(std::complex a) { - T x = a.real(), y = a.imag(); - if (x == T(0)) { - T t = T(::sqrt(gmm::abs(y) / T(2))); - return std::complex(t, y < T(0) ? -t : t); - } - T t = T(::sqrt(T(2) * (gmm::abs(a) + gmm::abs(x)))), u = t / T(2); - return x > T(0) ? std::complex(u, y / t) - : std::complex(gmm::abs(y) / t, y < T(0) ? -u : u); - } - using std::swap; - - - template struct number_traits { - typedef T magnitude_type; - }; - - template struct number_traits > { - typedef T magnitude_type; - }; - - template inline T conj_product(T a, T b) { return a * b; } - template inline - std::complex conj_product(std::complex a, std::complex b) - { return std::conj(a) * b; } // to be optimized ? - - template inline bool is_complex(T) { return false; } - template inline bool is_complex(std::complex ) - { return true; } - -# define magnitude_of_linalg(M) typename number_traits::value_type>::magnitude_type - - template inline std::complex operator*(const std::complex& a, int b) { - return a*T(b); - } - template inline std::complex operator*(int b, const std::complex& a) { - return a*T(b); - } - - /* ******************************************************************** */ - /* types promotion */ - /* ******************************************************************** */ - - /* should be completed for more specific cases etc */ - template - struct strongest_numeric_type_aux { - typedef T1 T; - }; - template - struct strongest_numeric_type_aux { - typedef T2 T; - }; - - template - struct strongest_numeric_type { - typedef typename - strongest_numeric_type_auxsizeof(T2))>::T T; - }; - template - struct strongest_numeric_type > { - typedef typename number_traits::magnitude_type R1; - typedef std::complex::T > T; - }; - template - struct strongest_numeric_type,T2 > { - typedef typename number_traits::magnitude_type R2; - typedef std::complex::T > T; - }; - template - struct strongest_numeric_type,std::complex > { - typedef std::complex::T > T; - }; - - template<> struct strongest_numeric_type { typedef float T; }; - template<> struct strongest_numeric_type { typedef float T; }; - template<> struct strongest_numeric_type { typedef float T; }; - template<> struct strongest_numeric_type { typedef float T; }; - template<> struct strongest_numeric_type { typedef double T; }; - template<> struct strongest_numeric_type { typedef double T; }; - - template - struct strongest_value_type { - typedef typename - strongest_numeric_type::value_type, - typename linalg_traits::value_type>::T - value_type; - }; - template - struct strongest_value_type3 { - typedef typename - strongest_value_type::value_type>::value_type - value_type; - }; - - - - /* ******************************************************************** */ - /* Basic vectors used */ - /* ******************************************************************** */ - - template struct dense_vector_type - { typedef std::vector vector_type; }; - - template class wsvector; - template class rsvector; - template struct sparse_vector_type - { typedef wsvector vector_type; }; - - template class slvector; - template class dense_matrix; - template class row_matrix; - template class col_matrix; - - - /* ******************************************************************** */ - /* Selects a temporary vector type */ - /* V if V is a valid vector type, */ - /* wsvector if V is a reference on a sparse vector, */ - /* std::vector if V is a reference on a dense vector. */ - /* ******************************************************************** */ - - - template - struct temporary_vector_ { - typedef abstract_null_type vector_type; - }; - template - struct temporary_vector_ - { typedef wsvector::value_type> vector_type; }; - template - struct temporary_vector_ - { typedef slvector::value_type> vector_type; }; - template - struct temporary_vector_ - { typedef std::vector::value_type> vector_type; }; - template - struct temporary_vector_ - { typedef V vector_type; }; - template - struct temporary_vector_ - { typedef std::vector::value_type> vector_type; }; - template - struct temporary_vector_ - { typedef wsvector::value_type> vector_type; }; - - template struct temporary_vector { - typedef typename temporary_vector_::reference, - typename linalg_traits::storage_type, - typename linalg_traits::linalg_type, - V>::vector_type vector_type; - }; - - /* ******************************************************************** */ - /* Selects a temporary matrix type */ - /* M if M is a valid matrix type, */ - /* row_matrix if M is a reference on a sparse matrix, */ - /* dense_matrix if M is a reference on a dense matrix. */ - /* ******************************************************************** */ - - - template - struct temporary_matrix_ { typedef abstract_null_type matrix_type; }; - template - struct temporary_matrix_ { - typedef typename linalg_traits::value_type T; - typedef row_matrix > matrix_type; - }; - template - struct temporary_matrix_ { - typedef typename linalg_traits::value_type T; - typedef row_matrix > matrix_type; - }; - template - struct temporary_matrix_ - { typedef dense_matrix::value_type> matrix_type; }; - template - struct temporary_matrix_ - { typedef V matrix_type; }; - - template struct temporary_matrix { - typedef typename temporary_matrix_::reference, - typename linalg_traits::storage_type, - typename linalg_traits::linalg_type, - V>::matrix_type matrix_type; - }; - - - template - struct temporary_col_matrix_ { typedef abstract_null_type matrix_type; }; - template - struct temporary_col_matrix_ { - typedef typename linalg_traits::value_type T; - typedef col_matrix > matrix_type; - }; - template - struct temporary_col_matrix_ { - typedef typename linalg_traits::value_type T; - typedef col_matrix > matrix_type; - }; - template - struct temporary_col_matrix_ - { typedef dense_matrix::value_type> matrix_type; }; - - template struct temporary_col_matrix { - typedef typename temporary_col_matrix_< - typename linalg_traits::storage_type, - typename linalg_traits::linalg_type, - V>::matrix_type matrix_type; - }; - - - - - template - struct temporary_row_matrix_ { typedef abstract_null_type matrix_type; }; - template - struct temporary_row_matrix_ { - typedef typename linalg_traits::value_type T; - typedef row_matrix > matrix_type; - }; - template - struct temporary_row_matrix_ { - typedef typename linalg_traits::value_type T; - typedef row_matrix > matrix_type; - }; - template - struct temporary_row_matrix_ - { typedef dense_matrix::value_type> matrix_type; }; - - template struct temporary_row_matrix { - typedef typename temporary_row_matrix_< - typename linalg_traits::storage_type, - typename linalg_traits::linalg_type, - V>::matrix_type matrix_type; - }; - - - - /* ******************************************************************** */ - /* Selects a temporary dense vector type */ - /* V if V is a valid dense vector type, */ - /* std::vector if V is a reference or another type of vector */ - /* ******************************************************************** */ - - template - struct temporary_dense_vector_ { typedef abstract_null_type vector_type; }; - template - struct temporary_dense_vector_ - { typedef std::vector::value_type> vector_type; }; - template - struct temporary_dense_vector_ - { typedef std::vector::value_type> vector_type; }; - template - struct temporary_dense_vector_ - { typedef std::vector::value_type> vector_type; }; - template - struct temporary_dense_vector_ - { typedef V vector_type; }; - - template struct temporary_dense_vector { - typedef typename temporary_dense_vector_::reference, - typename linalg_traits::storage_type, V>::vector_type vector_type; - }; - - /* ******************************************************************** */ - /* Selects a temporary sparse vector type */ - /* V if V is a valid sparse vector type, */ - /* wsvector if V is a reference or another type of vector */ - /* ******************************************************************** */ - - template - struct temporary_sparse_vector_ { typedef abstract_null_type vector_type; }; - template - struct temporary_sparse_vector_ - { typedef wsvector::value_type> vector_type; }; - template - struct temporary_sparse_vector_ - { typedef V vector_type; }; - template - struct temporary_sparse_vector_ - { typedef wsvector::value_type> vector_type; }; - template - struct temporary_sparse_vector_ - { typedef wsvector::value_type> vector_type; }; - - template struct temporary_sparse_vector { - typedef typename temporary_sparse_vector_::reference, - typename linalg_traits::storage_type, V>::vector_type vector_type; - }; - - /* ******************************************************************** */ - /* Selects a temporary sky-line vector type */ - /* V if V is a valid sky-line vector type, */ - /* slvector if V is a reference or another type of vector */ - /* ******************************************************************** */ - - template - struct temporary_skyline_vector_ - { typedef abstract_null_type vector_type; }; - template - struct temporary_skyline_vector_ - { typedef slvector::value_type> vector_type; }; - template - struct temporary_skyline_vector_ - { typedef V vector_type; }; - template - struct temporary_skyline_vector_ - { typedef slvector::value_type> vector_type; }; - template - struct temporary_skyline_vector_ - { typedef slvector::value_type> vector_type; }; - - template struct temporary_skylines_vector { - typedef typename temporary_skyline_vector_::reference, - typename linalg_traits::storage_type, V>::vector_type vector_type; - }; - - /* ********************************************************************* */ - /* Definition & Comparison of origins. */ - /* ********************************************************************* */ - - template - typename select_return::origin_type *, - typename linalg_traits::origin_type *, - L *>::return_type - linalg_origin(L &l) - { return linalg_traits::origin(linalg_cast(l)); } - - template - typename select_return::origin_type *, - typename linalg_traits::origin_type *, - const L *>::return_type - linalg_origin(const L &l) - { return linalg_traits::origin(linalg_cast(l)); } - - template - bool same_porigin(PT1, PT2) { return false; } - - template - bool same_porigin(PT pt1, PT pt2) { return (pt1 == pt2); } - - template - bool same_origin(const L1 &l1, const L2 &l2) - { return same_porigin(linalg_origin(l1), linalg_origin(l2)); } - - - /* ******************************************************************** */ - /* Miscellaneous */ - /* ******************************************************************** */ - - template inline size_type vect_size(const V &v) - { return linalg_traits::size(v); } - - template inline size_type mat_nrows(const MAT &m) - { return linalg_traits::nrows(m); } - - template inline size_type mat_ncols(const MAT &m) - { return linalg_traits::ncols(m); } - - - template inline - typename select_return::const_iterator, - typename linalg_traits::iterator, V *>::return_type - vect_begin(V &v) - { return linalg_traits::begin(linalg_cast(v)); } - - template inline - typename select_return::const_iterator, - typename linalg_traits::iterator, const V *>::return_type - vect_begin(const V &v) - { return linalg_traits::begin(linalg_cast(v)); } - - template inline - typename linalg_traits::const_iterator - vect_const_begin(const V &v) - { return linalg_traits::begin(v); } - - template inline - typename select_return::const_iterator, - typename linalg_traits::iterator, V *>::return_type - vect_end(V &v) - { return linalg_traits::end(linalg_cast(v)); } - - template inline - typename select_return::const_iterator, - typename linalg_traits::iterator, const V *>::return_type - vect_end(const V &v) - { return linalg_traits::end(linalg_cast(v)); } - - template inline - typename linalg_traits::const_iterator - vect_const_end(const V &v) - { return linalg_traits::end(v); } - - template inline - typename select_return::const_row_iterator, - typename linalg_traits::row_iterator, M *>::return_type - mat_row_begin(M &m) { return linalg_traits::row_begin(linalg_cast(m)); } - - template inline - typename select_return::const_row_iterator, - typename linalg_traits::row_iterator, const M *>::return_type - mat_row_begin(const M &m) - { return linalg_traits::row_begin(linalg_cast(m)); } - - template inline typename linalg_traits::const_row_iterator - mat_row_const_begin(const M &m) - { return linalg_traits::row_begin(m); } - - template inline - typename select_return::const_row_iterator, - typename linalg_traits::row_iterator, M *>::return_type - mat_row_end(M &v) { - return linalg_traits::row_end(linalg_cast(v)); - } - - template inline - typename select_return::const_row_iterator, - typename linalg_traits::row_iterator, const M *>::return_type - mat_row_end(const M &v) { - return linalg_traits::row_end(linalg_cast(v)); - } - - template inline - typename linalg_traits::const_row_iterator - mat_row_const_end(const M &v) - { return linalg_traits::row_end(v); } - - template inline - typename select_return::const_col_iterator, - typename linalg_traits::col_iterator, M *>::return_type - mat_col_begin(M &v) { - return linalg_traits::col_begin(linalg_cast(v)); - } - - template inline - typename select_return::const_col_iterator, - typename linalg_traits::col_iterator, const M *>::return_type - mat_col_begin(const M &v) { - return linalg_traits::col_begin(linalg_cast(v)); - } - - template inline - typename linalg_traits::const_col_iterator - mat_col_const_begin(const M &v) - { return linalg_traits::col_begin(v); } - - template inline - typename linalg_traits::const_col_iterator - mat_col_const_end(const M &v) - { return linalg_traits::col_end(v); } - - template inline - typename select_return::const_col_iterator, - typename linalg_traits::col_iterator, - M *>::return_type - mat_col_end(M &m) - { return linalg_traits::col_end(linalg_cast(m)); } - - template inline - typename select_return::const_col_iterator, - typename linalg_traits::col_iterator, - const M *>::return_type - mat_col_end(const M &m) - { return linalg_traits::col_end(linalg_cast(m)); } - - template inline - typename select_return::const_sub_row_type, - typename linalg_traits::sub_row_type, - const MAT *>::return_type - mat_row(const MAT &m, size_type i) - { return linalg_traits::row(mat_row_begin(m) + i); } - - template inline - typename select_return::const_sub_row_type, - typename linalg_traits::sub_row_type, - MAT *>::return_type - mat_row(MAT &m, size_type i) - { return linalg_traits::row(mat_row_begin(m) + i); } - - template inline - typename linalg_traits::const_sub_row_type - mat_const_row(const MAT &m, size_type i) - { return linalg_traits::row(mat_row_const_begin(m) + i); } - - template inline - typename select_return::const_sub_col_type, - typename linalg_traits::sub_col_type, - const MAT *>::return_type - mat_col(const MAT &m, size_type i) - { return linalg_traits::col(mat_col_begin(m) + i); } - - - template inline - typename select_return::const_sub_col_type, - typename linalg_traits::sub_col_type, - MAT *>::return_type - mat_col(MAT &m, size_type i) - { return linalg_traits::col(mat_col_begin(m) + i); } - - template inline - typename linalg_traits::const_sub_col_type - mat_const_col(const MAT &m, size_type i) - { return linalg_traits::col(mat_col_const_begin(m) + i); } - - /* ********************************************************************* */ - /* Set to begin end set to end for iterators on non-const sparse vectors.*/ - /* ********************************************************************* */ - - template inline - void set_to_begin(IT &it, ORG o, VECT *, linalg_false) - { it = vect_begin(*o); } - - template inline - void set_to_begin(IT &it, ORG o, const VECT *, linalg_false) - { it = vect_const_begin(*o); } - - template inline - void set_to_end(IT &it, ORG o, VECT *, linalg_false) - { it = vect_end(*o); } - - template inline - void set_to_end(IT &it, ORG o, const VECT *, linalg_false) - { it = vect_const_end(*o); } - - - template inline - void set_to_begin(IT &, ORG, VECT *, linalg_const) { } - - template inline - void set_to_begin(IT &, ORG, const VECT *, linalg_const) { } - - template inline - void set_to_end(IT &, ORG, VECT *, linalg_const) { } - - template inline - void set_to_end(IT &, ORG, const VECT *, linalg_const) { } - - - template inline - void set_to_begin(IT &, ORG, VECT *v, linalg_modifiable) - { GMM_ASSERT3(!is_sparse(*v), "internal_error"); v = 0; } - - template inline - void set_to_begin(IT &, ORG, const VECT *v, linalg_modifiable) - { GMM_ASSERT3(!is_sparse(*v), "internal_error"); v = 0; } - - template inline - void set_to_end(IT &, ORG, VECT *v, linalg_modifiable) - { GMM_ASSERT3(!is_sparse(*v), "internal_error"); v = 0; } - - template inline - void set_to_end(IT &, ORG, const VECT *v, linalg_modifiable) - { GMM_ASSERT3(!is_sparse(*v), "internal_error"); v = 0; } - - /* ******************************************************************** */ - /* General index for certain algorithms. */ - /* ******************************************************************** */ - - template - size_type index_of_it(const IT &it, size_type, abstract_sparse) - { return it.index(); } - template - size_type index_of_it(const IT &it, size_type, abstract_skyline) - { return it.index(); } - template - size_type index_of_it(const IT &, size_type k, abstract_dense) - { return k; } - - /* ********************************************************************* */ - /* Numeric limits. */ - /* ********************************************************************* */ - - template inline T default_tol(T) { - using namespace std; - static T tol(10); - if (tol == T(10)) { - if (numeric_limits::is_specialized) - tol = numeric_limits::epsilon(); - else { - int i=sizeof(T)/4; while(i-- > 0) tol*=T(1E-8); - GMM_WARNING1("The numeric type " << typeid(T).name() - << " has no numeric_limits defined !!\n" - << "Taking " << tol << " as default tolerance"); - } - } - return tol; - } - template inline T default_tol(std::complex) - { return default_tol(T()); } - - template inline T default_min(T) { - using namespace std; - static T mi(10); - if (mi == T(10)) { - if (numeric_limits::is_specialized) - mi = std::numeric_limits::min(); - else { - mi = T(0); - GMM_WARNING1("The numeric type " << typeid(T).name() - << " has no numeric_limits defined !!\n" - << "Taking 0 as default minimum"); - } - } - return mi; - } - template inline T default_min(std::complex) - { return default_min(T()); } - - template inline T default_max(T) { - using namespace std; - static T mi(10); - if (mi == T(10)) { - if (numeric_limits::is_specialized) - mi = std::numeric_limits::max(); - else { - mi = T(1); - GMM_WARNING1("The numeric type " << typeid(T).name() - << " has no numeric_limits defined !!\n" - << "Taking 1 as default maximum !"); - } - } - return mi; - } - template inline T default_max(std::complex) - { return default_max(T()); } - - - /* - use safe_divide to avoid NaNs when dividing very small complex - numbers, for example - std::complex(1e-23,1e-30)/std::complex(1e-23,1e-30) - */ - template inline T safe_divide(T a, T b) { return a/b; } - template inline std::complex - safe_divide(std::complex a, std::complex b) { - T m = std::max(gmm::abs(b.real()), gmm::abs(b.imag())); - a = std::complex(a.real()/m, a.imag()/m); - b = std::complex(b.real()/m, b.imag()/m); - return a / b; - } - - - /* ******************************************************************** */ - /* Write */ - /* ******************************************************************** */ - - template struct cast_char_type { typedef T return_type; }; - template <> struct cast_char_type { typedef int return_type; }; - template <> struct cast_char_type - { typedef unsigned int return_type; }; - template inline typename cast_char_type::return_type - cast_char(const T &c) { return typename cast_char_type::return_type(c); } - - - template inline void write(std::ostream &o, const L &l) - { write(o, l, typename linalg_traits::linalg_type()); } - - template void write(std::ostream &o, const L &l, - abstract_vector) { - o << "vector(" << vect_size(l) << ") ["; - write(o, l, typename linalg_traits::storage_type()); - o << " ]"; - } - - template void write(std::ostream &o, const L &l, - abstract_sparse) { - typename linalg_traits::const_iterator it = vect_const_begin(l), - ite = vect_const_end(l); - for (; it != ite; ++it) - o << " (r" << it.index() << "," << cast_char(*it) << ")"; - } - - template void write(std::ostream &o, const L &l, - abstract_dense) { - typename linalg_traits::const_iterator it = vect_const_begin(l), - ite = vect_const_end(l); - if (it != ite) o << " " << cast_char(*it++); - for (; it != ite; ++it) o << ", " << cast_char(*it); - } - - template void write(std::ostream &o, const L &l, - abstract_skyline) { - typedef typename linalg_traits::const_iterator const_iterator; - const_iterator it = vect_const_begin(l), ite = vect_const_end(l); - if (it != ite) { - o << ""; - if (it != ite) o << " " << cast_char(*it++); - for (; it != ite; ++it) { o << ", " << cast_char(*it); } - } - } - - template inline void write(std::ostream &o, const L &l, - abstract_matrix) { - write(o, l, typename linalg_traits::sub_orientation()); - } - - - template void write(std::ostream &o, const L &l, - row_major) { - o << "matrix(" << mat_nrows(l) << ", " << mat_ncols(l) << ")" << endl; - for (size_type i = 0; i < mat_nrows(l); ++i) { - o << "("; - write(o, mat_const_row(l, i), typename linalg_traits::storage_type()); - o << " )\n"; - } - } - - template inline - void write(std::ostream &o, const L &l, row_and_col) - { write(o, l, row_major()); } - - template inline - void write(std::ostream &o, const L &l, col_and_row) - { write(o, l, row_major()); } - - template void write(std::ostream &o, const L &l, col_major) { - o << "matrix(" << mat_nrows(l) << ", " << mat_ncols(l) << ")" << endl; - for (size_type i = 0; i < mat_nrows(l); ++i) { - o << "("; - if (is_sparse(l)) { // not optimized ... - for (size_type j = 0; j < mat_ncols(l); ++j) - if (l(i,j) != typename linalg_traits::value_type(0)) - o << " (r" << j << ", " << l(i,j) << ")"; - } - else { - if (mat_ncols(l) != 0) o << ' ' << l(i, 0); - for (size_type j = 1; j < mat_ncols(l); ++j) o << ", " << l(i, j); - } - o << " )\n"; - } - } - -} - -#endif // GMM_DEF_H__ diff --git a/include/gmm/gmm_dense_Householder.h b/include/gmm/gmm_dense_Householder.h deleted file mode 100644 index 3c776653924..00000000000 --- a/include/gmm/gmm_dense_Householder.h +++ /dev/null @@ -1,316 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_dense_Householder.h - @author Caroline Lecalvez - @author Yves Renard - @date June 5, 2003. - @brief Householder for dense matrices. -*/ - -#ifndef GMM_DENSE_HOUSEHOLDER_H -#define GMM_DENSE_HOUSEHOLDER_H - -#include "gmm_kernel.h" - -namespace gmm { - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - /* ********************************************************************* */ - /* Rank one update (complex and real version) */ - /* ********************************************************************* */ - - template - inline void rank_one_update(Matrix &A, const VecX& x, - const VecY& y, row_major) { - typedef typename linalg_traits::value_type T; - size_type N = mat_nrows(A); - GMM_ASSERT2(N <= vect_size(x) && mat_ncols(A) <= vect_size(y), - "dimensions mismatch"); - typename linalg_traits::const_iterator itx = vect_const_begin(x); - for (size_type i = 0; i < N; ++i, ++itx) { - typedef typename linalg_traits::sub_row_type row_type; - row_type row = mat_row(A, i); - typename linalg_traits::iterator - it = vect_begin(row), ite = vect_end(row); - typename linalg_traits::const_iterator ity = vect_const_begin(y); - T tx = *itx; - for (; it != ite; ++it, ++ity) *it += conj_product(*ity, tx); - } - } - - template - inline void rank_one_update(Matrix &A, const VecX& x, - const VecY& y, col_major) { - typedef typename linalg_traits::value_type T; - size_type M = mat_ncols(A); - GMM_ASSERT2(mat_nrows(A) <= vect_size(x) && M <= vect_size(y), - "dimensions mismatch"); - typename linalg_traits::const_iterator ity = vect_const_begin(y); - for (size_type i = 0; i < M; ++i, ++ity) { - typedef typename linalg_traits::sub_col_type col_type; - col_type col = mat_col(A, i); - typename linalg_traits::iterator - it = vect_begin(col), ite = vect_end(col); - typename linalg_traits::const_iterator itx = vect_const_begin(x); - T ty = *ity; - for (; it != ite; ++it, ++itx) *it += conj_product(ty, *itx); - } - } - - ///@endcond - template - inline void rank_one_update(const Matrix &AA, const VecX& x, - const VecY& y) { - Matrix& A = const_cast(AA); - rank_one_update(A, x, y, typename principal_orientation_type::sub_orientation>::potype()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - /* ********************************************************************* */ - /* Rank two update (complex and real version) */ - /* ********************************************************************* */ - - template - inline void rank_two_update(Matrix &A, const VecX& x, - const VecY& y, row_major) { - typedef typename linalg_traits::value_type value_type; - size_type N = mat_nrows(A); - GMM_ASSERT2(N <= vect_size(x) && mat_ncols(A) <= vect_size(y), - "dimensions mismatch"); - typename linalg_traits::const_iterator itx1 = vect_const_begin(x); - typename linalg_traits::const_iterator ity2 = vect_const_begin(y); - for (size_type i = 0; i < N; ++i, ++itx1, ++ity2) { - typedef typename linalg_traits::sub_row_type row_type; - row_type row = mat_row(A, i); - typename linalg_traits::iterator - it = vect_begin(row), ite = vect_end(row); - typename linalg_traits::const_iterator itx2 = vect_const_begin(x); - typename linalg_traits::const_iterator ity1 = vect_const_begin(y); - value_type tx = *itx1, ty = *ity2; - for (; it != ite; ++it, ++ity1, ++itx2) - *it += conj_product(*ity1, tx) + conj_product(*itx2, ty); - } - } - - template - inline void rank_two_update(Matrix &A, const VecX& x, - const VecY& y, col_major) { - typedef typename linalg_traits::value_type value_type; - size_type M = mat_ncols(A); - GMM_ASSERT2(mat_nrows(A) <= vect_size(x) && M <= vect_size(y), - "dimensions mismatch"); - typename linalg_traits::const_iterator itx2 = vect_const_begin(x); - typename linalg_traits::const_iterator ity1 = vect_const_begin(y); - for (size_type i = 0; i < M; ++i, ++ity1, ++itx2) { - typedef typename linalg_traits::sub_col_type col_type; - col_type col = mat_col(A, i); - typename linalg_traits::iterator - it = vect_begin(col), ite = vect_end(col); - typename linalg_traits::const_iterator itx1 = vect_const_begin(x); - typename linalg_traits::const_iterator ity2 = vect_const_begin(y); - value_type ty = *ity1, tx = *itx2; - for (; it != ite; ++it, ++itx1, ++ity2) - *it += conj_product(ty, *itx1) + conj_product(tx, *ity2); - } - } - - ///@endcond - template - inline void rank_two_update(const Matrix &AA, const VecX& x, - const VecY& y) { - Matrix& A = const_cast(AA); - rank_two_update(A, x, y, typename principal_orientation_type::sub_orientation>::potype()); - } - ///@cond DOXY_SHOW_ALL_FUNCTIONS - - /* ********************************************************************* */ - /* Householder vector computation (complex and real version) */ - /* ********************************************************************* */ - - template void house_vector(const VECT &VV) { - VECT &V = const_cast(VV); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - R mu = vect_norm2(V), abs_v0 = gmm::abs(V[0]); - if (mu != R(0)) - gmm::scale(V, (abs_v0 == R(0)) ? T(R(1) / mu) - : (safe_divide(T(abs_v0), V[0]) / (abs_v0 + mu))); - if (gmm::real(V[vect_size(V)-1]) * R(0) != R(0)) gmm::clear(V); - V[0] = T(1); - } - - template void house_vector_last(const VECT &VV) { - VECT &V = const_cast(VV); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - size_type m = vect_size(V); - R mu = vect_norm2(V), abs_v0 = gmm::abs(V[m-1]); - if (mu != R(0)) - gmm::scale(V, (abs_v0 == R(0)) ? T(R(1) / mu) - : ((abs_v0 / V[m-1]) / (abs_v0 + mu))); - if (gmm::real(V[0]) * R(0) != R(0)) gmm::clear(V); - V[m-1] = T(1); - } - - /* ********************************************************************* */ - /* Householder updates (complex and real version) */ - /* ********************************************************************* */ - - // multiply A to the left by the reflector stored in V. W is a temporary. - template inline - void row_house_update(const MAT &AA, const VECT1 &V, const VECT2 &WW) { - VECT2 &W = const_cast(WW); MAT &A = const_cast(AA); - typedef typename linalg_traits::value_type value_type; - typedef typename number_traits::magnitude_type magnitude_type; - - gmm::mult(conjugated(A), - scaled(V, value_type(magnitude_type(-2)/vect_norm2_sqr(V))), W); - rank_one_update(A, V, W); - } - - // multiply A to the right by the reflector stored in V. W is a temporary. - template inline - void col_house_update(const MAT &AA, const VECT1 &V, const VECT2 &WW) { - VECT2 &W = const_cast(WW); MAT &A = const_cast(AA); - typedef typename linalg_traits::value_type value_type; - typedef typename number_traits::magnitude_type magnitude_type; - - gmm::mult(A, - scaled(V, value_type(magnitude_type(-2)/vect_norm2_sqr(V))), W); - rank_one_update(A, W, V); - } - - ///@endcond - - /* ********************************************************************* */ - /* Hessemberg reduction with Householder. */ - /* ********************************************************************* */ - - template - void Hessenberg_reduction(const MAT1& AA, const MAT2 &QQ, bool compute_Q){ - MAT1& A = const_cast(AA); MAT2& Q = const_cast(QQ); - typedef typename linalg_traits::value_type value_type; - if (compute_Q) gmm::copy(identity_matrix(), Q); - size_type n = mat_nrows(A); if (n < 2) return; - std::vector v(n), w(n); - sub_interval SUBK(0,n); - for (size_type k = 1; k+1 < n; ++k) { - sub_interval SUBI(k, n-k), SUBJ(k-1,n-k+1); - v.resize(n-k); - for (size_type j = k; j < n; ++j) v[j-k] = A(j, k-1); - house_vector(v); - row_house_update(sub_matrix(A, SUBI, SUBJ), v, sub_vector(w, SUBJ)); - col_house_update(sub_matrix(A, SUBK, SUBI), v, w); - // is it possible to "unify" the two on the common part of the matrix? - if (compute_Q) col_house_update(sub_matrix(Q, SUBK, SUBI), v, w); - } - } - - /* ********************************************************************* */ - /* Householder tridiagonalization for symmetric matrices */ - /* ********************************************************************* */ - - template - void Householder_tridiagonalization(const MAT1 &AA, const MAT2 &QQ, - bool compute_q) { - MAT1 &A = const_cast(AA); MAT2 &Q = const_cast(QQ); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = mat_nrows(A); if (n < 2) return; - std::vector v(n), p(n), w(n), ww(n); - sub_interval SUBK(0,n); - - for (size_type k = 1; k+1 < n; ++k) { // not optimized ... - sub_interval SUBI(k, n-k); - v.resize(n-k); p.resize(n-k); w.resize(n-k); - for (size_type l = k; l < n; ++l) - { v[l-k] = w[l-k] = A(l, k-1); A(l, k-1) = A(k-1, l) = T(0); } - house_vector(v); - R norm = vect_norm2_sqr(v); - A(k-1, k) = gmm::conj(A(k, k-1) = w[0] - T(2)*v[0]*vect_hp(w, v)/norm); - - gmm::mult(sub_matrix(A, SUBI), gmm::scaled(v, T(-2) / norm), p); - gmm::add(p, gmm::scaled(v, -vect_hp(v, p) / norm), w); - rank_two_update(sub_matrix(A, SUBI), v, w); - // it should be possible to compute only the upper or lower part - - if (compute_q) col_house_update(sub_matrix(Q, SUBK, SUBI), v, ww); - } - } - - /* ********************************************************************* */ - /* real and complex Givens rotations */ - /* ********************************************************************* */ - - template void Givens_rotation(T a, T b, T &c, T &s) { - typedef typename number_traits::magnitude_type R; - R aa = gmm::abs(a), bb = gmm::abs(b); - if (bb == R(0)) { c = T(1); s = T(0); return; } - if (aa == R(0)) { c = T(0); s = b / bb; return; } - if (bb > aa) - { T t = -safe_divide(a,b); s = T(R(1) / (sqrt(R(1)+gmm::abs_sqr(t)))); c = s * t; } - else - { T t = -safe_divide(b,a); c = T(R(1) / (sqrt(R(1)+gmm::abs_sqr(t)))); s = c * t; } - } - - // Apply Q* v - template inline - void Apply_Givens_rotation_left(T &x, T &y, T c, T s) - { T t1=x, t2=y; x = gmm::conj(c)*t1 - gmm::conj(s)*t2; y = c*t2 + s*t1; } - - // Apply v^T Q - template inline - void Apply_Givens_rotation_right(T &x, T &y, T c, T s) - { T t1=x, t2=y; x = c*t1 - s*t2; y = gmm::conj(c)*t2 + gmm::conj(s)*t1; } - - template - void row_rot(const MAT &AA, T c, T s, size_type i, size_type k) { - MAT &A = const_cast(AA); // can be specialized for row matrices - for (size_type j = 0; j < mat_ncols(A); ++j) - Apply_Givens_rotation_left(A(i,j), A(k,j), c, s); - } - - template - void col_rot(const MAT &AA, T c, T s, size_type i, size_type k) { - MAT &A = const_cast(AA); // can be specialized for column matrices - for (size_type j = 0; j < mat_nrows(A); ++j) - Apply_Givens_rotation_right(A(j,i), A(j,k), c, s); - } - -} - -#endif - diff --git a/include/gmm/gmm_dense_lu.h b/include/gmm/gmm_dense_lu.h deleted file mode 100644 index e683eb7251a..00000000000 --- a/include/gmm/gmm_dense_lu.h +++ /dev/null @@ -1,250 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of lu.h from MTL. -// See http://osl.iu.edu/research/mtl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -/**@file gmm_dense_lu.h - @author Andrew Lumsdaine, Jeremy G. Siek, Lie-Quan Lee, Y. Renard - @date June 5, 2003. - @brief LU factorizations and determinant computation for dense matrices. -*/ -#ifndef GMM_DENSE_LU_H -#define GMM_DENSE_LU_H - -#include "gmm_dense_Householder.h" -#include "gmm_opt.h" - -namespace gmm { - - - /** LU Factorization of a general (dense) matrix (real or complex). - - This is the outer product (a level-2 operation) form of the LU - Factorization with pivoting algorithm . This is equivalent to - LAPACK's dgetf2. Also see "Matrix Computations" 3rd Ed. by Golub - and Van Loan section 3.2.5 and especially page 115. - - The pivot indices in ipvt are indexed starting from 1 - so that this is compatible with LAPACK (Fortran). - */ - template - size_type lu_factor(DenseMatrix& A, Pvector& ipvt) { - typedef typename linalg_traits::value_type T; - typedef typename linalg_traits::value_type int_T; - typedef typename number_traits::magnitude_type R; - size_type info(0), i, j, jp, M(mat_nrows(A)), N(mat_ncols(A)); - size_type NN = std::min(M, N); - std::vector c(M), r(N); - - GMM_ASSERT2(ipvt.size()+1 >= NN, "IPVT too small"); - for (i = 0; i+1 < NN; ++i) ipvt[i] = int_T(i); - - if (M || N) { - for (j = 0; j+1 < NN; ++j) { - R max = gmm::abs(A(j,j)); jp = j; - for (i = j+1; i < M; ++i) /* find pivot. */ - if (gmm::abs(A(i,j)) > max) { jp = i; max = gmm::abs(A(i,j)); } - ipvt[j] = int_T(jp + 1); - - if (max == R(0)) { info = j + 1; break; } - if (jp != j) for (i = 0; i < N; ++i) std::swap(A(jp, i), A(j, i)); - - for (i = j+1; i < M; ++i) { A(i, j) /= A(j,j); c[i-j-1] = -A(i, j); } - for (i = j+1; i < N; ++i) r[i-j-1] = A(j, i); // avoid the copy ? - rank_one_update(sub_matrix(A, sub_interval(j+1, M-j-1), - sub_interval(j+1, N-j-1)), c, conjugated(r)); - } - ipvt[j] = int_T(j + 1); - } - return info; - } - - /** LU Solve : Solve equation Ax=b, given an LU factored matrix.*/ - // Thanks to Valient Gough for this routine! - template - void lu_solve(const DenseMatrix &LU, const Pvector& pvector, - VectorX &x, const VectorB &b) { - typedef typename linalg_traits::value_type T; - copy(b, x); - for(size_type i = 0; i < pvector.size(); ++i) { - size_type perm = pvector[i]-1; // permutations stored in 1's offset - if(i != perm) { T aux = x[i]; x[i] = x[perm]; x[perm] = aux; } - } - /* solve Ax = b -> LUx = b -> Ux = L^-1 b. */ - lower_tri_solve(LU, x, true); - upper_tri_solve(LU, x, false); - } - - template - void lu_solve(const DenseMatrix &A, VectorX &x, const VectorB &b) { - typedef typename linalg_traits::value_type T; - dense_matrix B(mat_nrows(A), mat_ncols(A)); - std::vector ipvt(mat_nrows(A)); - gmm::copy(A, B); - size_type info = lu_factor(B, ipvt); - GMM_ASSERT1(!info, "Singular system, pivot = " << info); - lu_solve(B, ipvt, x, b); - } - - template - void lu_solve_transposed(const DenseMatrix &LU, const Pvector& pvector, - VectorX &x, const VectorB &b) { - typedef typename linalg_traits::value_type T; - copy(b, x); - lower_tri_solve(transposed(LU), x, false); - upper_tri_solve(transposed(LU), x, true); - for(size_type i = pvector.size(); i > 0; --i) { - size_type perm = pvector[i-1]-1; // permutations stored in 1's offset - if(i-1 != perm) { T aux = x[i-1]; x[i-1] = x[perm]; x[perm] = aux; } - } - - } - - - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template - void lu_inverse(const DenseMatrixLU& LU, const Pvector& pvector, - DenseMatrix& AInv, col_major) { - typedef typename linalg_traits::value_type T; - std::vector tmp(pvector.size(), T(0)); - std::vector result(pvector.size()); - for(size_type i = 0; i < pvector.size(); ++i) { - tmp[i] = T(1); - lu_solve(LU, pvector, result, tmp); - copy(result, mat_col(AInv, i)); - tmp[i] = T(0); - } - } - - template - void lu_inverse(const DenseMatrixLU& LU, const Pvector& pvector, - DenseMatrix& AInv, row_major) { - typedef typename linalg_traits::value_type T; - std::vector tmp(pvector.size(), T(0)); - std::vector result(pvector.size()); - for(size_type i = 0; i < pvector.size(); ++i) { - tmp[i] = T(1); // to be optimized !! - // on peut sur le premier tri solve reduire le systeme - // et peut etre faire un solve sur une serie de vecteurs au lieu - // de vecteur a vecteur (accumulation directe de l'inverse dans la - // matrice au fur et a mesure du calcul ... -> evite la copie finale - lu_solve_transposed(LU, pvector, result, tmp); - copy(result, mat_row(AInv, i)); - tmp[i] = T(0); - } - } - ///@endcond - - /** Given an LU factored matrix, build the inverse of the matrix. */ - template - void lu_inverse(const DenseMatrixLU& LU, const Pvector& pvector, - const DenseMatrix& AInv_) { - DenseMatrix& AInv = const_cast(AInv_); - lu_inverse(LU, pvector, AInv, typename principal_orientation_type::sub_orientation>::potype()); - } - - /** Given a dense matrix, build the inverse of the matrix, and - return the determinant */ - template - typename linalg_traits::value_type - lu_inverse(const DenseMatrix& A_) { - typedef typename linalg_traits::value_type T; - DenseMatrix& A = const_cast(A_); - dense_matrix B(mat_nrows(A), mat_ncols(A)); - std::vector ipvt(mat_nrows(A)); - gmm::copy(A, B); - size_type info = lu_factor(B, ipvt); - GMM_ASSERT1(!info, "Non invertible matrix, pivot = " << info); - lu_inverse(B, ipvt, A); - return lu_det(B, ipvt); - } - - /** Compute the matrix determinant (via a LU factorization) */ - template - typename linalg_traits::value_type - lu_det(const DenseMatrixLU& LU, const Pvector &pvector) { - typedef typename linalg_traits::value_type T; - T det(1); - for (size_type j = 0; j < std::min(mat_nrows(LU), mat_ncols(LU)); ++j) - det *= LU(j,j); - for(size_type i = 0; i < pvector.size(); ++i) - if (i != size_type(pvector[i]-1)) { det = -det; } - return det; - } - - template - typename linalg_traits::value_type - lu_det(const DenseMatrix& A) { - typedef typename linalg_traits::value_type T; - dense_matrix B(mat_nrows(A), mat_ncols(A)); - std::vector ipvt(mat_nrows(A)); - gmm::copy(A, B); - lu_factor(B, ipvt); - return lu_det(B, ipvt); - } - -} - -#endif - diff --git a/include/gmm/gmm_dense_qr.h b/include/gmm/gmm_dense_qr.h deleted file mode 100644 index d6745997a4a..00000000000 --- a/include/gmm/gmm_dense_qr.h +++ /dev/null @@ -1,788 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_dense_qr.h - @author Caroline Lecalvez, Caroline.Lecalvez@gmm.insa-tlse.fr, Yves Renard - @date September 12, 2003. - @brief Dense QR factorization. -*/ -#ifndef GMM_DENSE_QR_H -#define GMM_DENSE_QR_H - -#include "gmm_dense_Householder.h" - -namespace gmm { - - - /** - QR factorization using Householder method (complex and real version). - */ - template - void qr_factor(const MAT1 &A_) { - MAT1 &A = const_cast(A_); - typedef typename linalg_traits::value_type value_type; - - size_type m = mat_nrows(A), n = mat_ncols(A); - GMM_ASSERT2(m >= n, "dimensions mismatch"); - - std::vector W(m), V(m); - - for (size_type j = 0; j < n; ++j) { - sub_interval SUBI(j, m-j), SUBJ(j, n-j); - V.resize(m-j); W.resize(n-j); - - for (size_type i = j; i < m; ++i) V[i-j] = A(i, j); - house_vector(V); - - row_house_update(sub_matrix(A, SUBI, SUBJ), V, W); - for (size_type i = j+1; i < m; ++i) A(i, j) = V[i-j]; - } - } - - - // QR comes from QR_factor(QR) where the upper triangular part stands for R - // and the lower part contains the Householder reflectors. - // A <- AQ - template - void apply_house_right(const MAT1 &QR, const MAT2 &A_) { - MAT2 &A = const_cast(A_); - typedef typename linalg_traits::value_type T; - size_type m = mat_nrows(QR), n = mat_ncols(QR); - GMM_ASSERT2(m == mat_ncols(A), "dimensions mismatch"); - if (m == 0) return; - std::vector V(m), W(mat_nrows(A)); - V[0] = T(1); - for (size_type j = 0; j < n; ++j) { - V.resize(m-j); - for (size_type i = j+1; i < m; ++i) V[i-j] = QR(i, j); - col_house_update(sub_matrix(A, sub_interval(0, mat_nrows(A)), - sub_interval(j, m-j)), V, W); - } - } - - // QR comes from QR_factor(QR) where the upper triangular part stands for R - // and the lower part contains the Householder reflectors. - // A <- Q*A - template - void apply_house_left(const MAT1 &QR, const MAT2 &A_) { - MAT2 &A = const_cast(A_); - typedef typename linalg_traits::value_type T; - size_type m = mat_nrows(QR), n = mat_ncols(QR); - GMM_ASSERT2(m == mat_nrows(A), "dimensions mismatch"); - if (m == 0) return; - std::vector V(m), W(mat_ncols(A)); - V[0] = T(1); - for (size_type j = 0; j < n; ++j) { - V.resize(m-j); - for (size_type i = j+1; i < m; ++i) V[i-j] = QR(i, j); - row_house_update(sub_matrix(A, sub_interval(j, m-j), - sub_interval(0, mat_ncols(A))), V, W); - } - } - - /** Compute the QR factorization, where Q is assembled. */ - template - void qr_factor(const MAT1 &A, const MAT2 &QQ, const MAT3 &RR) { - MAT2 &Q = const_cast(QQ); MAT3 &R = const_cast(RR); - typedef typename linalg_traits::value_type value_type; - - size_type m = mat_nrows(A), n = mat_ncols(A); - GMM_ASSERT2(m >= n, "dimensions mismatch"); - gmm::copy(A, Q); - - std::vector W(m); - dense_matrix VV(m, n); - - for (size_type j = 0; j < n; ++j) { - sub_interval SUBI(j, m-j), SUBJ(j, n-j); - - for (size_type i = j; i < m; ++i) VV(i,j) = Q(i, j); - house_vector(sub_vector(mat_col(VV,j), SUBI)); - - row_house_update(sub_matrix(Q, SUBI, SUBJ), - sub_vector(mat_col(VV,j), SUBI), sub_vector(W, SUBJ)); - } - - gmm::copy(sub_matrix(Q, sub_interval(0, n), sub_interval(0, n)), R); - gmm::copy(identity_matrix(), Q); - - for (size_type j = n-1; j != size_type(-1); --j) { - sub_interval SUBI(j, m-j), SUBJ(j, n-j); - row_house_update(sub_matrix(Q, SUBI, SUBJ), - sub_vector(mat_col(VV,j), SUBI), sub_vector(W, SUBJ)); - } - } - - ///@cond DOXY_SHOW_ALL_FUNCTIONS - template - void extract_eig(const MAT &A, VECT &V, Ttol tol, TA, TV) { - size_type n = mat_nrows(A); - if (n == 0) return; - tol *= Ttol(2); - Ttol tol_i = tol * gmm::abs(A(0,0)), tol_cplx = tol_i; - for (size_type i = 0; i < n; ++i) { - if (i < n-1) { - tol_i = (gmm::abs(A(i,i))+gmm::abs(A(i+1,i+1)))*tol; - tol_cplx = std::max(tol_cplx, tol_i); - } - if ((i < n-1) && gmm::abs(A(i+1,i)) >= tol_i) { - TA tr = A(i,i) + A(i+1, i+1); - TA det = A(i,i)*A(i+1, i+1) - A(i,i+1)*A(i+1, i); - TA delta = tr*tr - TA(4) * det; - if (delta < -tol_cplx) { - GMM_WARNING1("A complex eigenvalue has been detected : " - << std::complex(tr/TA(2), gmm::sqrt(-delta)/TA(2))); - V[i] = V[i+1] = tr / TA(2); - } - else { - delta = std::max(TA(0), delta); - V[i ] = TA(tr + gmm::sqrt(delta))/ TA(2); - V[i+1] = TA(tr - gmm::sqrt(delta))/ TA(2); - } - ++i; - } - else - V[i] = TV(A(i,i)); - } - } - - template - void extract_eig(const MAT &A, VECT &V, Ttol tol, TA, std::complex) { - size_type n = mat_nrows(A); - tol *= Ttol(2); - for (size_type i = 0; i < n; ++i) - if ((i == n-1) || - gmm::abs(A(i+1,i)) < (gmm::abs(A(i,i))+gmm::abs(A(i+1,i+1)))*tol) - V[i] = std::complex(A(i,i)); - else { - TA tr = A(i,i) + A(i+1, i+1); - TA det = A(i,i)*A(i+1, i+1) - A(i,i+1)*A(i+1, i); - TA delta = tr*tr - TA(4) * det; - if (delta < TA(0)) { - V[i] = std::complex(tr / TA(2), gmm::sqrt(-delta) / TA(2)); - V[i+1] = std::complex(tr / TA(2), -gmm::sqrt(-delta)/ TA(2)); - } - else { - V[i ] = TA(tr + gmm::sqrt(delta)) / TA(2); - V[i+1] = TA(tr - gmm::sqrt(delta)) / TA(2); - } - ++i; - } - } - - template - void extract_eig(const MAT &A, VECT &V, Ttol tol, std::complex, TV) { - typedef std::complex T; - size_type n = mat_nrows(A); - if (n == 0) return; - tol *= Ttol(2); - Ttol tol_i = tol * gmm::abs(A(0,0)), tol_cplx = tol_i; - for (size_type i = 0; i < n; ++i) { - if (i < n-1) { - tol_i = (gmm::abs(A(i,i))+gmm::abs(A(i+1,i+1)))*tol; - tol_cplx = std::max(tol_cplx, tol_i); - } - if ((i == n-1) || gmm::abs(A(i+1,i)) < tol_i) { - if (gmm::abs(std::imag(A(i,i))) > tol_cplx) - GMM_WARNING1("A complex eigenvalue has been detected : " - << T(A(i,i)) << " : " << gmm::abs(std::imag(A(i,i))) - / gmm::abs(std::real(A(i,i))) << " : " << tol_cplx); - V[i] = std::real(A(i,i)); - } - else { - T tr = A(i,i) + A(i+1, i+1); - T det = A(i,i)*A(i+1, i+1) - A(i,i+1)*A(i+1, i); - T delta = tr*tr - TA(4) * det; - T a1 = (tr + gmm::sqrt(delta)) / TA(2); - T a2 = (tr - gmm::sqrt(delta)) / TA(2); - if (gmm::abs(std::imag(a1)) > tol_cplx) - GMM_WARNING1("A complex eigenvalue has been detected : " << a1); - if (gmm::abs(std::imag(a2)) > tol_cplx) - GMM_WARNING1("A complex eigenvalue has been detected : " << a2); - - V[i] = std::real(a1); V[i+1] = std::real(a2); - ++i; - } - } - } - - template - void extract_eig(const MAT &A, VECT &V, Ttol tol, - std::complex, std::complex) { - size_type n = mat_nrows(A); - tol *= Ttol(2); - for (size_type i = 0; i < n; ++i) - if ((i == n-1) || - gmm::abs(A(i+1,i)) < (gmm::abs(A(i,i))+gmm::abs(A(i+1,i+1)))*tol) - V[i] = std::complex(A(i,i)); - else { - std::complex tr = A(i,i) + A(i+1, i+1); - std::complex det = A(i,i)*A(i+1, i+1) - A(i,i+1)*A(i+1, i); - std::complex delta = tr*tr - TA(4) * det; - V[i] = (tr + gmm::sqrt(delta)) / TA(2); - V[i+1] = (tr - gmm::sqrt(delta)) / TA(2); - ++i; - } - } - - ///@endcond - /** - Compute eigenvalue vector. - */ - template inline - void extract_eig(const MAT &A, const VECT &V, Ttol tol) { - extract_eig(A, const_cast(V), tol, - typename linalg_traits::value_type(), - typename linalg_traits::value_type()); - } - - /* ********************************************************************* */ - /* Stop criterion for QR algorithms */ - /* ********************************************************************* */ - - template - void qr_stop_criterion(MAT &A, size_type &p, size_type &q, Ttol tol) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - R rmin = default_min(R()) * R(2); - size_type n = mat_nrows(A); - if (n <= 2) { q = n; p = 0; } - else { - for (size_type i = 1; i < n-q; ++i) - if (gmm::abs(A(i,i-1)) < (gmm::abs(A(i,i))+ gmm::abs(A(i-1,i-1)))*tol - || gmm::abs(A(i,i-1)) < rmin) - A(i,i-1) = T(0); - - while ((q < n-1 && A(n-1-q, n-2-q) == T(0)) || - (q < n-2 && A(n-2-q, n-3-q) == T(0))) ++q; - if (q >= n-2) q = n; - p = n-q; if (p) --p; if (p) --p; - while (p > 0 && A(p,p-1) != T(0)) --p; - } - } - - template inline - void symmetric_qr_stop_criterion(const MAT &AA, size_type &p, size_type &q, - Ttol tol) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - R rmin = default_min(R()) * R(2); - MAT& A = const_cast(AA); - size_type n = mat_nrows(A); - if (n <= 1) { q = n; p = 0; } - else { - for (size_type i = 1; i < n-q; ++i) - if (gmm::abs(A(i,i-1)) < (gmm::abs(A(i,i))+ gmm::abs(A(i-1,i-1)))*tol - || gmm::abs(A(i,i-1)) < rmin) - A(i,i-1) = T(0); - - while (q < n-1 && A(n-1-q, n-2-q) == T(0)) ++q; - if (q >= n-1) q = n; - p = n-q; if (p) --p; if (p) --p; - while (p > 0 && A(p,p-1) != T(0)) --p; - } - } - - template inline - void symmetric_qr_stop_criterion(const VECT1 &diag, const VECT2 &sdiag_, - size_type &p, size_type &q, Ttol tol) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - R rmin = default_min(R()) * R(2); - VECT2 &sdiag = const_cast(sdiag_); - size_type n = vect_size(diag); - if (n <= 1) { q = n; p = 0; return; } - for (size_type i = 1; i < n-q; ++i) - if (gmm::abs(sdiag[i-1]) < (gmm::abs(diag[i])+ gmm::abs(diag[i-1]))*tol - || gmm::abs(sdiag[i-1]) < rmin) - sdiag[i-1] = T(0); - while (q < n-1 && sdiag[n-2-q] == T(0)) ++q; - if (q >= n-1) q = n; - p = n-q; if (p) --p; if (p) --p; - while (p > 0 && sdiag[p-1] != T(0)) --p; - } - - /* ********************************************************************* */ - /* 2x2 blocks reduction for Schur vectors */ - /* ********************************************************************* */ - - template - void block2x2_reduction(MATH &H, MATQ &Q, Ttol tol) { - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = mat_nrows(H), nq = mat_nrows(Q); - sub_interval SUBQ(0, nq), SUBL(0, 2); - std::vector v(2), w(std::max(n, nq)); v[0] = T(1); - if (n < 2) return; - tol *= Ttol(2); - Ttol tol_i = tol * gmm::abs(H(0,0)), tol_cplx = tol_i; - for (size_type i = 0; i < n-1; ++i) { - tol_i = (gmm::abs(H(i,i))+gmm::abs(H(i+1,i+1)))*tol; - tol_cplx = std::max(tol_cplx, tol_i); - - if (gmm::abs(H(i+1,i)) > tol_i) { // 2x2 block detected - T tr = (H(i+1, i+1) - H(i,i)) / T(2); - T delta = tr*tr + H(i,i+1)*H(i+1, i); - - if (is_complex(T()) || gmm::real(delta) >= R(0)) { - sub_interval SUBI(i, 2); - T theta = (tr - gmm::sqrt(delta)) / H(i+1,i); - R a = gmm::abs(theta); - v[1] = (a == R(0)) ? T(-1) - : gmm::conj(theta) * (R(1) - gmm::sqrt(a*a + R(1)) / a); - row_house_update(sub_matrix(H, SUBI), v, sub_vector(w, SUBL)); - col_house_update(sub_matrix(H, SUBI), v, sub_vector(w, SUBL)); - col_house_update(sub_matrix(Q, SUBQ, SUBI), v, sub_vector(w, SUBQ)); - } - ++i; - } - } - } - - /* ********************************************************************* */ - /* Basic qr algorithm. */ - /* ********************************************************************* */ - - #define tol_type_for_qr typename number_traits::value_type>::magnitude_type - #define default_tol_for_qr \ - (gmm::default_tol(tol_type_for_qr()) * tol_type_for_qr(3)) - - // QR method for real or complex square matrices based on QR factorisation. - // eigval has to be a complex vector if A has complex eigeinvalues. - // Very slow method. Use implicit_qr_method instead. - template - void rudimentary_qr_algorithm(const MAT1 &A, const VECT &eigval_, - const MAT2 &eigvect_, - tol_type_for_qr tol = default_tol_for_qr, - bool compvect = true) { - VECT &eigval = const_cast(eigval_); - MAT2 &eigvect = const_cast(eigvect_); - - typedef typename linalg_traits::value_type value_type; - - size_type n = mat_nrows(A), p, q = 0, ite = 0; - dense_matrix Q(n, n), R(n,n), A1(n,n); - gmm::copy(A, A1); - - Hessenberg_reduction(A1, eigvect, compvect); - qr_stop_criterion(A1, p, q, tol); - - while (q < n) { - qr_factor(A1, Q, R); - gmm::mult(R, Q, A1); - if (compvect) { gmm::mult(eigvect, Q, R); gmm::copy(R, eigvect); } - - qr_stop_criterion(A1, p, q, tol); - ++ite; - GMM_ASSERT1(ite < n*1000, "QR algorithm failed"); - } - if (compvect) block2x2_reduction(A1, Q, tol); - extract_eig(A1, eigval, tol); - } - - template - void rudimentary_qr_algorithm(const MAT1 &a, VECT &eigval, - tol_type_for_qr tol = default_tol_for_qr) { - dense_matrix::value_type> m(0,0); - rudimentary_qr_algorithm(a, eigval, m, tol, false); - } - - /* ********************************************************************* */ - /* Francis QR step. */ - /* ********************************************************************* */ - - template - void Francis_qr_step(const MAT1& HH, const MAT2 &QQ, bool compute_Q) { - MAT1& H = const_cast(HH); MAT2& Q = const_cast(QQ); - typedef typename linalg_traits::value_type value_type; - size_type n = mat_nrows(H), nq = mat_nrows(Q); - - std::vector v(3), w(std::max(n, nq)); - - value_type s = H(n-2, n-2) + H(n-1, n-1); - value_type t = H(n-2, n-2) * H(n-1, n-1) - H(n-2, n-1) * H(n-1, n-2); - value_type x = H(0, 0) * H(0, 0) + H(0,1) * H(1, 0) - s * H(0,0) + t; - value_type y = H(1, 0) * (H(0,0) + H(1,1) - s); - value_type z = H(1, 0) * H(2, 1); - - sub_interval SUBQ(0, nq); - - for (size_type k = 0; k < n - 2; ++k) { - v[0] = x; v[1] = y; v[2] = z; - house_vector(v); - size_type r = std::min(k+4, n), q = (k==0) ? 0 : k-1; - sub_interval SUBI(k, 3), SUBJ(0, r), SUBK(q, n-q); - - row_house_update(sub_matrix(H, SUBI, SUBK), v, sub_vector(w, SUBK)); - col_house_update(sub_matrix(H, SUBJ, SUBI), v, sub_vector(w, SUBJ)); - - if (compute_Q) - col_house_update(sub_matrix(Q, SUBQ, SUBI), v, sub_vector(w, SUBQ)); - - x = H(k+1, k); y = H(k+2, k); - if (k < n-3) z = H(k+3, k); - } - sub_interval SUBI(n-2,2), SUBJ(0, n), SUBK(n-3,3), SUBL(0, 3); - v.resize(2); - v[0] = x; v[1] = y; - house_vector(v); - row_house_update(sub_matrix(H, SUBI, SUBK), v, sub_vector(w, SUBL)); - col_house_update(sub_matrix(H, SUBJ, SUBI), v, sub_vector(w, SUBJ)); - if (compute_Q) - col_house_update(sub_matrix(Q, SUBQ, SUBI), v, sub_vector(w, SUBQ)); - } - - /* ********************************************************************* */ - /* Wilkinson Double shift QR step (from Lapack). */ - /* ********************************************************************* */ - - template - void Wilkinson_double_shift_qr_step(const MAT1& HH, const MAT2 &QQ, - Ttol tol, bool exc, bool compute_Q) { - MAT1& H = const_cast(HH); MAT2& Q = const_cast(QQ); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = mat_nrows(H), nq = mat_nrows(Q), m; - std::vector v(3), w(std::max(n, nq)); - const R dat1(0.75), dat2(-0.4375); - T h33, h44, h43h34, v1(0), v2(0), v3(0); - - if (exc) { /* Exceptional shift. */ - R s = gmm::abs(H(n-1, n-2)) + gmm::abs(H(n-2, n-3)); - h33 = h44 = dat1 * s; - h43h34 = dat2*s*s; - } - else { /* Wilkinson double shift. */ - h44 = H(n-1,n-1); h33 = H(n-2, n-2); - h43h34 = H(n-1, n-2) * H(n-2, n-1); - } - - /* Look for two consecutive small subdiagonal elements. */ - /* Determine the effect of starting the double-shift QR iteration at */ - /* row m, and see if this would make H(m-1, m-2) negligible. */ - for (m = n-2; m != 0; --m) { - T h11 = H(m-1, m-1), h22 = H(m, m); - T h21 = H(m, m-1), h12 = H(m-1, m); - T h44s = h44 - h11, h33s = h33 - h11; - v1 = (h33s*h44s-h43h34) / h21 + h12; - v2 = h22 - h11 - h33s - h44s; - v3 = H(m+1, m); - R s = gmm::abs(v1) + gmm::abs(v2) + gmm::abs(v3); - v1 /= s; v2 /= s; v3 /= s; - if (m == 1) break; - T h00 = H(m-2, m-2); - T h10 = H(m-1, m-2); - R tst1 = gmm::abs(v1)*(gmm::abs(h00)+gmm::abs(h11)+gmm::abs(h22)); - if (gmm::abs(h10)*(gmm::abs(v2)+gmm::abs(v3)) <= tol * tst1) break; - } - - /* Double shift QR step. */ - sub_interval SUBQ(0, nq); - for (size_type k = (m == 0) ? 0 : m-1; k < n-2; ++k) { - v[0] = v1; v[1] = v2; v[2] = v3; - house_vector(v); - size_type r = std::min(k+4, n), q = (k==0) ? 0 : k-1; - sub_interval SUBI(k, 3), SUBJ(0, r), SUBK(q, n-q); - - row_house_update(sub_matrix(H, SUBI, SUBK), v, sub_vector(w, SUBK)); - col_house_update(sub_matrix(H, SUBJ, SUBI), v, sub_vector(w, SUBJ)); - if (k > m-1) { H(k+1, k-1) = T(0); if (k < n-3) H(k+2, k-1) = T(0); } - - if (compute_Q) - col_house_update(sub_matrix(Q, SUBQ, SUBI), v, sub_vector(w, SUBQ)); - - v1 = H(k+1, k); v2 = H(k+2, k); - if (k < n-3) v3 = H(k+3, k); - } - sub_interval SUBI(n-2,2), SUBJ(0, n), SUBK(n-3,3), SUBL(0, 3); - v.resize(2); v[0] = v1; v[1] = v2; - house_vector(v); - row_house_update(sub_matrix(H, SUBI, SUBK), v, sub_vector(w, SUBL)); - col_house_update(sub_matrix(H, SUBJ, SUBI), v, sub_vector(w, SUBJ)); - if (compute_Q) - col_house_update(sub_matrix(Q, SUBQ, SUBI), v, sub_vector(w, SUBQ)); - } - - /* ********************************************************************* */ - /* Implicit QR algorithm. */ - /* ********************************************************************* */ - - // QR method for real or complex square matrices based on an - // implicit QR factorisation. eigval has to be a complex vector - // if A has complex eigeinvalues. complexity about 10n^3, 25n^3 if - // eigenvectors are computed - template - void implicit_qr_algorithm(const MAT1 &A, const VECT &eigval_, - const MAT2 &Q_, - tol_type_for_qr tol = default_tol_for_qr, - bool compvect = true) { - VECT &eigval = const_cast(eigval_); - MAT2 &Q = const_cast(Q_); - typedef typename linalg_traits::value_type value_type; - - size_type n(mat_nrows(A)), q(0), q_old, p(0), ite(0), its(0); - dense_matrix H(n,n); - sub_interval SUBK(0,0); - - gmm::copy(A, H); - Hessenberg_reduction(H, Q, compvect); - qr_stop_criterion(H, p, q, tol); - - while (q < n) { - sub_interval SUBI(p, n-p-q), SUBJ(0, mat_ncols(Q)); - if (compvect) SUBK = SUBI; -// Francis_qr_step(sub_matrix(H, SUBI), -// sub_matrix(Q, SUBJ, SUBK), compvect); - Wilkinson_double_shift_qr_step(sub_matrix(H, SUBI), - sub_matrix(Q, SUBJ, SUBK), - tol, (its == 10 || its == 20), compvect); - q_old = q; - qr_stop_criterion(H, p, q, tol*2); - if (q != q_old) its = 0; - ++its; ++ite; - GMM_ASSERT1(ite < n*100, "QR algorithm failed"); - } - if (compvect) block2x2_reduction(H, Q, tol); - extract_eig(H, eigval, tol); - } - - - template - void implicit_qr_algorithm(const MAT1 &a, VECT &eigval, - tol_type_for_qr tol = default_tol_for_qr) { - dense_matrix::value_type> m(0,0); - implicit_qr_algorithm(a, eigval, m, tol, false); - } - - /* ********************************************************************* */ - /* Implicit symmetric QR step with Wilkinson Shift. */ - /* ********************************************************************* */ - - template - void symmetric_Wilkinson_qr_step(const MAT1& MM, const MAT2 &ZZ, - bool compute_z) { - MAT1& M = const_cast(MM); MAT2& Z = const_cast(ZZ); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - size_type n = mat_nrows(M); - - for (size_type i = 0; i < n; ++i) { - M(i, i) = T(gmm::real(M(i, i))); - if (i > 0) { - T a = (M(i, i-1) + gmm::conj(M(i-1, i)))/R(2); - M(i, i-1) = a; M(i-1, i) = gmm::conj(a); - } - } - - R d = gmm::real(M(n-2, n-2) - M(n-1, n-1)) / R(2); - R e = gmm::abs_sqr(M(n-1, n-2)); - R nu = d + gmm::sgn(d)*gmm::sqrt(d*d+e); - if (nu == R(0)) { M(n-1, n-2) = T(0); return; } - R mu = gmm::real(M(n-1, n-1)) - e / nu; - T x = M(0,0) - T(mu), z = M(1, 0), c, s; - - for (size_type k = 1; k < n; ++k) { - Givens_rotation(x, z, c, s); - - if (k > 1) Apply_Givens_rotation_left(M(k-1,k-2), M(k,k-2), c, s); - Apply_Givens_rotation_left(M(k-1,k-1), M(k,k-1), c, s); - Apply_Givens_rotation_left(M(k-1,k ), M(k,k ), c, s); - if (k < n-1) Apply_Givens_rotation_left(M(k-1,k+1), M(k,k+1), c, s); - if (k > 1) Apply_Givens_rotation_right(M(k-2,k-1), M(k-2,k), c, s); - Apply_Givens_rotation_right(M(k-1,k-1), M(k-1,k), c, s); - Apply_Givens_rotation_right(M(k ,k-1), M(k,k) , c, s); - if (k < n-1) Apply_Givens_rotation_right(M(k+1,k-1), M(k+1,k), c, s); - - if (compute_z) col_rot(Z, c, s, k-1, k); - if (k < n-1) { x = M(k, k-1); z = M(k+1, k-1); } - } - - } - - template - void symmetric_Wilkinson_qr_step(const VECT1& diag_, const VECT2& sdiag_, - const MAT &ZZ, bool compute_z) { - VECT1& diag = const_cast(diag_); - VECT2& sdiag = const_cast(sdiag_); - MAT& Z = const_cast(ZZ); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = vect_size(diag); - R d = (diag[n-2] - diag[n-1]) / R(2); - R e = gmm::abs_sqr(sdiag[n-2]); - R nu = d + gmm::sgn(d)*gmm::sqrt(d*d+e); - if (nu == R(0)) { sdiag[n-2] = T(0); return; } - R mu = diag[n-1] - e / nu; - T x = diag[0] - T(mu), z = sdiag[0], c, s; - - T a01(0), a02(0); - T a10(0), a11(diag[0]), a12(gmm::conj(sdiag[0])), a13(0); - T a20(0), a21(sdiag[0]), a22(diag[1]), a23(gmm::conj(sdiag[1])); - T a31(0), a32(sdiag[1]); - - for (size_type k = 1; k < n; ++k) { - Givens_rotation(x, z, c, s); - - if (k > 1) Apply_Givens_rotation_left(a10, a20, c, s); - Apply_Givens_rotation_left(a11, a21, c, s); - Apply_Givens_rotation_left(a12, a22, c, s); - if (k < n-1) Apply_Givens_rotation_left(a13, a23, c, s); - - if (k > 1) Apply_Givens_rotation_right(a01, a02, c, s); - Apply_Givens_rotation_right(a11, a12, c, s); - Apply_Givens_rotation_right(a21, a22, c, s); - if (k < n-1) Apply_Givens_rotation_right(a31, a32, c, s); - - if (compute_z) col_rot(Z, c, s, k-1, k); - - diag[k-1] = gmm::real(a11); - diag[k] = gmm::real(a22); - if (k > 1) sdiag[k-2] = (gmm::conj(a01) + a10) / R(2); - sdiag[k-1] = (gmm::conj(a12) + a21) / R(2); - - x = sdiag[k-1]; z = (gmm::conj(a13) + a31) / R(2); - - a01 = a12; a02 = a13; - a10 = a21; a11 = a22; a12 = a23; a13 = T(0); - a20 = a31; a21 = a32; a31 = T(0); - - if (k < n-1) { - sdiag[k] = (gmm::conj(a23) + a32) / R(2); - a22 = T(diag[k+1]); a32 = sdiag[k+1]; a23 = gmm::conj(a32); - } - } - } - - /* ********************************************************************* */ - /* Implicit QR algorithm for symmetric or hermitian matrices. */ - /* ********************************************************************* */ - - // implicit QR method for real square symmetric matrices or complex - // hermitian matrices. - // eigval has to be a complex vector if A has complex eigeinvalues. - // complexity about 4n^3/3, 9n^3 if eigenvectors are computed - template - void symmetric_qr_algorithm_old(const MAT1 &A, const VECT &eigval_, - const MAT2 &eigvect_, - tol_type_for_qr tol = default_tol_for_qr, - bool compvect = true) { - VECT &eigval = const_cast(eigval_); - MAT2 &eigvect = const_cast(eigvect_); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - if (compvect) gmm::copy(identity_matrix(), eigvect); - size_type n = mat_nrows(A), q = 0, p, ite = 0; - dense_matrix Tri(n, n); - gmm::copy(A, Tri); - - Householder_tridiagonalization(Tri, eigvect, compvect); - - symmetric_qr_stop_criterion(Tri, p, q, tol); - - while (q < n) { - - sub_interval SUBI(p, n-p-q), SUBJ(0, mat_ncols(eigvect)), SUBK(p, n-p-q); - if (!compvect) SUBK = sub_interval(0,0); - symmetric_Wilkinson_qr_step(sub_matrix(Tri, SUBI), - sub_matrix(eigvect, SUBJ, SUBK), compvect); - - symmetric_qr_stop_criterion(Tri, p, q, tol*R(2)); - ++ite; - GMM_ASSERT1(ite < n*100, "QR algorithm failed. Probably, your matrix" - " is not real symmetric or complex hermitian"); - } - - extract_eig(Tri, eigval, tol); - } - - template - void symmetric_qr_algorithm(const MAT1 &A, const VECT &eigval_, - const MAT2 &eigvect_, - tol_type_for_qr tol = default_tol_for_qr, - bool compvect = true) { - VECT &eigval = const_cast(eigval_); - MAT2 &eigvect = const_cast(eigvect_); - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = mat_nrows(A), q = 0, p, ite = 0; - if (compvect) gmm::copy(identity_matrix(), eigvect); - if (n == 0) return; - if (n == 1) { eigval[0]=gmm::real(A(0,0)); return; } - dense_matrix Tri(n, n); - gmm::copy(A, Tri); - - Householder_tridiagonalization(Tri, eigvect, compvect); - - std::vector diag(n); - std::vector sdiag(n); - for (size_type i = 0; i < n; ++i) - { diag[i] = gmm::real(Tri(i, i)); if (i+1 < n) sdiag[i] = Tri(i+1, i); } - - symmetric_qr_stop_criterion(diag, sdiag, p, q, tol); - - while (q < n) { - sub_interval SUBI(p, n-p-q), SUBJ(0, mat_ncols(eigvect)), SUBK(p, n-p-q); - if (!compvect) SUBK = sub_interval(0,0); - - symmetric_Wilkinson_qr_step(sub_vector(diag, SUBI), - sub_vector(sdiag, SUBI), - sub_matrix(eigvect, SUBJ, SUBK), compvect); - - symmetric_qr_stop_criterion(diag, sdiag, p, q, tol*R(3)); - ++ite; - GMM_ASSERT1(ite < n*100, "QR algorithm failed."); - } - - gmm::copy(diag, eigval); - } - - - template - void symmetric_qr_algorithm(const MAT1 &a, VECT &eigval, - tol_type_for_qr tol = default_tol_for_qr) { - dense_matrix::value_type> m(0,0); - symmetric_qr_algorithm(a, eigval, m, tol, false); - } - - -} - -#endif - diff --git a/include/gmm/gmm_dense_sylvester.h b/include/gmm/gmm_dense_sylvester.h deleted file mode 100644 index fb017a6741f..00000000000 --- a/include/gmm/gmm_dense_sylvester.h +++ /dev/null @@ -1,173 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/** @file gmm_dense_sylvester.h - @author Yves Renard - @date June 5, 2003. - @brief Sylvester equation solver. -*/ -#ifndef GMM_DENSE_SYLVESTER_H -#define GMM_DENSE_SYLVESTER_H - -#include "gmm_kernel.h" - -namespace gmm { - - /* ********************************************************************* */ - /* Kronecker system matrix. */ - /* ********************************************************************* */ - template - void kron(const MAT1 &m1, const MAT2 &m2, const MAT3 &m3_, - bool init = true) { - MAT3 &m3 = const_cast(m3_); - size_type m = mat_nrows(m1), n = mat_ncols(m1); - size_type l = mat_nrows(m2), k = mat_ncols(m2); - - GMM_ASSERT2(mat_nrows(m3) == m*l && mat_ncols(m3) == n*k, - "dimensions mismatch"); - - for (size_type i = 0; i < m; ++i) - for (size_type j = 0; j < m; ++j) - if (init) - gmm::copy(gmm::scaled(m2, m1(i,j)), - gmm::sub_matrix(m3, sub_interval(l*i, l), - sub_interval(k*j, k))); - else - gmm::add(gmm::scaled(m2, m1(i,j)), - gmm::sub_matrix(m3, sub_interval(l*i, l), - sub_interval(k*j, k))); - } - - - /* ********************************************************************* */ - /* Copy a matrix into a vector. */ - /* ********************************************************************* */ - - template - colmatrix_to_vector(const MAT &A, VECT &v, col_major) { - size_type m = mat_nrows(A), n = mat_ncols(A); - GMM_ASSERT2(m*n == vect_size(v), "dimensions mismatch"); - for (size_type i = 0; i < n; ++i) - gmm::copy(mat_col(A, i), sub_vector(v, sub_interval(i*m, m))); - } - - template - colmatrix_to_vector(const MAT &A, VECT &v, row_and_col) - { colmatrix_to_vector(A, v, col_major()); } - - template - colmatrix_to_vector(const MAT &A, VECT &v, col_and_row) - { colmatrix_to_vector(A, v, col_major()); } - - template - colmatrix_to_vector(const MAT &A, VECT &v, row_major) { - size_type m = mat_nrows(mat), n = mat_ncols(A); - GMM_ASSERT2(m*n == vect_size(v), "dimensions mismatch"); - for (size_type i = 0; i < m; ++i) - gmm::copy(mat_row(A, i), sub_vector(v, sub_slice(i, n, m))); - } - - template inline - colmatrix_to_vector(const MAT &A, const VECT &v_) { - VECT &v = const_cast(v_); - colmatrix_to_vector(A, v, typename linalg_traits::sub_orientation()); - } - - - /* ********************************************************************* */ - /* Copy a vector into a matrix. */ - /* ********************************************************************* */ - - template - vector_to_colmatrix(const VECT &v, MAT &A, col_major) { - size_type m = mat_nrows(A), n = mat_ncols(A); - GMM_ASSERT2(m*n == vect_size(v), "dimensions mismatch"); - for (size_type i = 0; i < n; ++i) - gmm::copy(sub_vector(v, sub_interval(i*m, m)), mat_col(A, i)); - } - - template - vector_to_colmatrix(const VECT &v, MAT &A, row_and_col) - { vector_to_colmatrix(v, A, col_major()); } - - template - vector_to_colmatrix(const VECT &v, MAT &A, col_and_row) - { vector_to_colmatrix(v, A, col_major()); } - - template - vector_to_colmatrix(const VECT &v, MAT &A, row_major) { - size_type m = mat_nrows(mat), n = mat_ncols(A); - GMM_ASSERT2(m*n == vect_size(v), "dimensions mismatch"); - for (size_type i = 0; i < m; ++i) - gmm::copy(sub_vector(v, sub_slice(i, n, m)), mat_row(A, i)); - } - - template inline - vector_to_colmatrix(const VECT &v, const MAT &A_) { - MAT &A = const_cast(A_); - vector_to_colmatrix(v, A, typename linalg_traits::sub_orientation()); - } - - /* ********************************************************************* */ - /* Solve sylvester equation. */ - /* ********************************************************************* */ - - // very prohibitive solver, to be replaced ... - template - void sylvester(const MAT1 &m1, const MAT2 &m2, const MAT3 &m3, - const MAT4 &m4_) { - typedef typename linalg_traits::value_type T; - - MAT3 &m4 = const_cast(m4_); - size_type m = mat_nrows(m1), n = mat_ncols(m1); - size_type l = mat_nrows(m2), k = mat_ncols(m2); - - GMM_ASSERT2(m == n && l == k && m == mat_nrows(m3) && - l == mat_ncols(m3) && m == mat_nrows(m4) && l == mat_ncols(m4), - "dimensions mismatch"); - - gmm::dense_matrix akronb(m*l, m*l); - gmm::dense_matrix idm(m, m), idl(l,l); - gmm::copy(identity_matrix(), idm); - gmm::copy(identity_matrix(), idl); - std::vector x(m*l), c(m*l); - - kron(idl, m1, akronb); - kron(gmm::transposed(m2), idm, akronb, false); - - colmatrix_to_vector(m3, c); - lu_solve(akronb, c, x); - vector_to_colmatrix(x, m4); - - } -} - -#endif - diff --git a/include/gmm/gmm_domain_decomp.h b/include/gmm/gmm_domain_decomp.h deleted file mode 100644 index 6ddf0d21430..00000000000 --- a/include/gmm/gmm_domain_decomp.h +++ /dev/null @@ -1,164 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2004-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/** @file gmm_domain_decomp.h - @author Yves Renard - @date May 21, 2004. - @brief Domain decomposition. -*/ -#ifndef GMM_DOMAIN_DECOMP_H__ -#define GMM_DOMAIN_DECOMP_H__ - -#include "gmm_kernel.h" -#include - - -namespace gmm { - - /** This function separates into small boxes of size msize with a ratio - * of overlap (in [0,1[) a set of points. The result is given into a - * vector of sparse matrices vB. - */ - template - void rudimentary_regular_decomposition(std::vector pts, - double msize, - double overlap, - std::vector &vB) { - typedef typename linalg_traits::value_type value_type; - typedef abstract_null_type void_type; - typedef std::map map_type; - - size_type nbpts = pts.size(); - if (!nbpts || pts[0].size() == 0) { vB.resize(0); return; } - int dim = int(pts[0].size()); - - // computation of the global box and the number of sub-domains - Point pmin = pts[0], pmax = pts[0]; - for (size_type i = 1; i < nbpts; ++i) - for (int k = 0; k < dim; ++k) { - pmin[k] = std::min(pmin[k], pts[i][k]); - pmax[k] = std::max(pmax[k], pts[i][k]); - } - - std::vector nbsub(dim), mult(dim); - std::vector pts1(dim), pts2(dim); - size_type nbtotsub = 1; - for (int k = 0; k < dim; ++k) { - nbsub[k] = size_type((pmax[k] - pmin[k]) / msize)+1; - mult[k] = nbtotsub; nbtotsub *= nbsub[k]; - } - - std::vector subs(nbtotsub); - // points ventilation - std::vector ns(dim), na(dim), nu(dim); - for (size_type i = 0; i < nbpts; ++i) { - for (int k = 0; k < dim; ++k) { - register double a = (pts[i][k] - pmin[k]) / msize; - ns[k] = size_type(a) - 1; na[k] = 0; - pts1[k] = int(a + overlap); pts2[k] = int(ceil(a-1.0-overlap)); - } - size_type sum = 0; - do { - bool ok = 1; - for (int k = 0; k < dim; ++k) - if ((ns[k] >= nbsub[k]) || (pts1[k] < int(ns[k])) - || (pts2[k] > int(ns[k]))) { ok = false; break; } - if (ok) { - size_type ind = ns[0]; - for (int k=1; k < dim; ++k) ind += ns[k]*mult[k]; - subs[ind][i] = void_type(); - } - for (int k = 0; k < dim; ++k) { - if (na[k] < 2) { na[k]++; ns[k]++; ++sum; break; } - na[k] = 0; ns[k] -= 2; sum -= 2; - } - } while (sum); - } - // delete too small domains. - size_type nbmaxinsub = 0; - for (size_type i = 0; i < nbtotsub; ++i) - nbmaxinsub = std::max(nbmaxinsub, subs[i].size()); - - std::fill(ns.begin(), ns.end(), size_type(0)); - for (size_type i = 0; i < nbtotsub; ++i) { - if (subs[i].size() > 0 && subs[i].size() < nbmaxinsub / 10) { - - for (int k = 0; k < dim; ++k) nu[k] = ns[k]; - size_type nbmax = 0, imax = 0; - - for (int l = 0; l < dim; ++l) { - nu[l]--; - for (int m = 0; m < 2; ++m, nu[l]+=2) { - bool ok = true; - for (int k = 0; k < dim && ok; ++k) - if (nu[k] >= nbsub[k]) ok = false; - if (ok) { - size_type ind = ns[0]; - for (int k=1; k < dim; ++k) ind += ns[k]*mult[k]; - if (subs[ind].size() > nbmax) - { nbmax = subs[ind].size(); imax = ind; } - } - } - nu[l]--; - } - - if (nbmax > subs[i].size()) { - for (map_type::iterator it=subs[i].begin(); it!=subs[i].end(); ++it) - subs[imax][it->first] = void_type(); - subs[i].clear(); - } - } - for (int k = 0; k < dim; ++k) - { ns[k]++; if (ns[k] < nbsub[k]) break; ns[k] = 0; } - } - - // delete empty domains. - size_type effnb = 0; - for (size_type i = 0; i < nbtotsub; ++i) { - if (subs[i].size() > 0) - { if (i != effnb) std::swap(subs[i], subs[effnb]); ++effnb; } - } - - // build matrices - subs.resize(effnb); - vB.resize(effnb); - for (size_type i = 0; i < effnb; ++i) { - clear(vB[i]); resize(vB[i], nbpts, subs[i].size()); - size_type j = 0; - for (map_type::iterator it=subs[i].begin(); it!=subs[i].end(); ++it, ++j) - vB[i](it->first, j) = value_type(1); - } - } - - -} - - -#endif diff --git a/include/gmm/gmm_except.h b/include/gmm/gmm_except.h deleted file mode 100644 index f432c094bcb..00000000000 --- a/include/gmm/gmm_except.h +++ /dev/null @@ -1,333 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/** @file gmm_except.h - @author Yves Renard - @author Julien Pommier - @date September 01, 2002. - @brief Definition of basic exceptions. -*/ - -#ifndef GMM_EXCEPT_H__ -#define GMM_EXCEPT_H__ - -#include "gmm_std.h" - -namespace gmm { - -/* *********************************************************************** */ -/* Getfem++ generic errors. */ -/* *********************************************************************** */ - - class gmm_error: public std::logic_error { - public: - gmm_error(const std::string& what_arg): std::logic_error (what_arg) {} - }; - -#ifdef GETFEM_HAVE_PRETTY_FUNCTION -# define GMM_PRETTY_FUNCTION __PRETTY_FUNCTION__ -#else -# define GMM_PRETTY_FUNCTION "" -#endif - - // Errors : GMM_THROW should not be used on its own. - // GMM_ASSERT1 : Non-maskable errors. Typically for in/ouput and - // when the test do not significantly reduces the performance. - // GMM_ASSERT2 : All tests which are potentially performance - // consuming. Not hidden by default. Hidden when NDEBUG is - // defined. - // GMM_ASSERT3 : For internal checks. Hidden by default. Active - // only when DEBUG_MODE is defined. - -#ifdef __EXCEPTIONS - inline void short_error_throw(const char *file, int line, const char *func, - const char *errormsg) { - std::stringstream msg; - msg << "Error in " << file << ", line " << line << " " << func - << ": \n" << errormsg << ends; - throw gmm::gmm_error(msg.str()); - } -# define GMM_THROW_(type, errormsg) { \ - std::stringstream msg; \ - msg << "Error in "__FILE__ << ", line " \ - << __LINE__ << " " << GMM_PRETTY_FUNCTION << ": \n" \ - << errormsg << ends; \ - throw (type)(msg.str()); \ - } -#else - inline void short_error_throw(const char *file, int line, const char *func, - const char *errormsg) { - std::stringstream msg; - msg << "Error in " << file << ", line " << line << " " << func - << ": \n" << errormsg << ends; - ::abort(); - } -# define GMM_THROW_(type, errormsg) { \ - std::stringstream msg; \ - msg << "Error in "__FILE__ << ", line " \ - << __LINE__ << " " << GMM_PRETTY_FUNCTION << ": \n" \ - << errormsg << ends; \ - ::abort(); \ - } -#endif - -# define GMM_ASSERT1(test, errormsg) \ - { if (!(test)) GMM_THROW_(gmm::gmm_error, errormsg); } - - // inline void GMM_THROW() IS_DEPRECATED; - inline void GMM_THROW() {} -#define GMM_THROW(a, b) { GMM_THROW_(a,b); gmm::GMM_THROW(); } - -#if defined(NDEBUG) -# define GMM_ASSERT2(test, errormsg) -# define GMM_ASSERT3(test, errormsg) -#elif !defined(GMM_FULL_NDEBUG) -# define GMM_ASSERT2(test, errormsg) \ - { if (!(test)) gmm::short_error_throw(__FILE__, __LINE__, \ - GMM_PRETTY_FUNCTION, errormsg); } -# define GMM_ASSERT3(test, errormsg) \ - { if (!(test)) gmm::short_error_throw(__FILE__, __LINE__, \ - GMM_PRETTY_FUNCTION, errormsg); } -#else -# define GMM_ASSERT2(test, errormsg) \ - { if (!(test)) gmm::short_error_throw(__FILE__, __LINE__, \ - GMM_PRETTY_FUNCTION, errormsg); } -# define GMM_ASSERT3(test, errormsg) -#endif - -/* *********************************************************************** */ -/* Getfem++ warnings. */ -/* *********************************************************************** */ - - // This allows to dynamically hide warnings - struct warning_level { - static int level(int l = -2) - { static int level_ = 3; return (l != -2) ? (level_ = l) : level_; } - }; - - inline void set_warning_level(int l) { warning_level::level(std::max(0,l)); } - inline int get_warning_level(void) { return warning_level::level(-2); } - - // This allow not too compile some Warnings -#ifndef GMM_WARNING_LEVEL -# define GMM_WARNING_LEVEL 4 -#endif - - // Warning levels : 0 always printed - // 1 very important : specify a possible error in the code. - // 2 important : specify a default of optimization for inst. - // 3 remark - // 4 ignored by default. - -#define GMM_WARNING_MSG(level_, thestr) { \ - std::stringstream msg; \ - msg << "Level " << level_ << " Warning in "__FILE__ << ", line " \ - << __LINE__ << ": " << thestr << ends; \ - std::cerr << msg.str() << std::endl; \ - } - -#define GMM_WARNING0(thestr) GMM_WARNING_MSG(0, thestr) - -#if GMM_WARNING_LEVEL > 0 -# define GMM_WARNING1(thestr) \ - { if (1 <= gmm::warning_level::level()) GMM_WARNING_MSG(1, thestr) } -#else -# define GMM_WARNING1(thestr) {} -#endif - -#if GMM_WARNING_LEVEL > 1 -# define GMM_WARNING2(thestr) \ - { if (2 <= gmm::warning_level::level()) GMM_WARNING_MSG(2, thestr) } -#else -# define GMM_WARNING1(thestr) {} -#endif - -#if GMM_WARNING_LEVEL > 2 -# define GMM_WARNING3(thestr) \ - { if (3 <= gmm::warning_level::level()) GMM_WARNING_MSG(3, thestr) } -#else -# define GMM_WARNING1(thestr) {} -#endif - -#if GMM_WARNING_LEVEL > 3 -# define GMM_WARNING4(thestr) \ - { if (4 <= gmm::warning_level::level()) GMM_WARNING_MSG(4, thestr) } -#else -# define GMM_WARNING1(thestr) {} -#endif - -/* *********************************************************************** */ -/* Getfem++ traces. */ -/* *********************************************************************** */ - - // This allows to dynamically hide traces - struct traces_level { - static int level(int l = -2) - { static int level_ = 3; return (l != -2) ? (level_ = l) : level_; } - }; - - inline void set_traces_level(int l) { traces_level::level(std::max(0,l)); } - - // This allow not too compile some Warnings -#ifndef GMM_TRACES_LEVEL -# define GMM_TRACES_LEVEL 3 -#endif - - // Traces levels : 0 always printed - // 1 Susceptible to occur once in a program. - // 2 Susceptible to occur occasionnaly in a program (10). - // 3 Susceptible to occur often (100). - // 4 Susceptible to occur very often (>1000). - -#define GMM_TRACE_MSG_MPI // for Parallelized version -#define GMM_TRACE_MSG(level_, thestr) { \ - GMM_TRACE_MSG_MPI { \ - std::stringstream msg; \ - msg << "Trace " << level_ << " in "__FILE__ << ", line " \ - << __LINE__ << ": " << thestr \ - << ends; \ - std::cout << msg.str() << std::endl; \ - } \ - } - -#define GMM_TRACE0(thestr) GMM_TRACE_MSG(0, thestr) - -#if GMM_TRACES_LEVEL > 0 -# define GMM_TRACE1(thestr) \ - { if (1 <= gmm::traces_level::level()) GMM_TRACE_MSG(1, thestr) } -#else -# define GMM_TRACE1(thestr) {} -#endif - -#if GMM_TRACES_LEVEL > 1 -# define GMM_TRACE2(thestr) \ - { if (2 <= gmm::traces_level::level()) GMM_TRACE_MSG(2, thestr) } -#else -# define GMM_TRACE2(thestr) {} -#endif - -#if GMM_TRACES_LEVEL > 2 -# define GMM_TRACE3(thestr) \ - { if (3 <= gmm::traces_level::level()) GMM_TRACE_MSG(3, thestr) } -#else -# define GMM_TRACE3(thestr) {} -#endif - -#if GMM_TRACES_LEVEL > 3 -# define GMM_TRACE4(thestr) \ - { if (4 <= gmm::traces_level::level()) GMM_TRACE_MSG(4, thestr) } -#else -# define GMM_TRACE4(thestr) {} -#endif - - - /* ********************************************************************* */ - /* Definitions for compatibility with old versions. */ - /* ********************************************************************* */ - - using std::invalid_argument; - - struct dimension_error : public std::logic_error - { dimension_error(const std::string& w): std::logic_error(w) {} }; - struct file_not_found_error : public std::logic_error - { file_not_found_error(const std::string& w): std::logic_error (w) {} }; - struct internal_error : public std::logic_error - { internal_error(const std::string& w): std::logic_error(w) {} }; - struct failure_error : public std::logic_error - { failure_error(const std::string& w): std::logic_error (w) {} }; - struct not_linear_error : public std::logic_error - { not_linear_error(const std::string& w): std::logic_error (w) {} }; - struct to_be_done_error : public std::logic_error - { to_be_done_error(const std::string& w): std::logic_error (w) {} }; - -#define GMM_STANDARD_CATCH_ERROR catch(std::logic_error e) \ - { \ - cerr << "============================================\n"; \ - cerr << "| An error has been detected !!! |\n"; \ - cerr << "============================================\n"; \ - cerr << e.what() << endl << endl; \ - exit(1); \ - } \ - catch(std::runtime_error e) \ - { \ - cerr << "============================================\n"; \ - cerr << "| An error has been detected !!! |\n"; \ - cerr << "============================================\n"; \ - cerr << e.what() << endl << endl; \ - exit(1); \ - } \ - catch(std::bad_alloc) { \ - cerr << "============================================\n"; \ - cerr << "| A bad allocation has been detected !!! |\n"; \ - cerr << "============================================\n"; \ - exit(1); \ - } \ - catch(std::bad_typeid) { \ - cerr << "============================================\n"; \ - cerr << "| A bad typeid has been detected !!! |\n"; \ - cerr << "============================================\n"; \ - exit(1); \ - } \ - catch(std::bad_exception) { \ - cerr << "============================================\n"; \ - cerr << "| A bad exception has been detected !!! |\n"; \ - cerr << "============================================\n"; \ - exit(1); \ - } \ - catch(std::bad_cast) { \ - cerr << "============================================\n"; \ - cerr << "| A bad cast has been detected !!! |\n"; \ - cerr << "============================================\n"; \ - exit(1); \ - } \ - catch(...) { \ - cerr << "============================================\n"; \ - cerr << "| An unknown error has been detected !!! |\n"; \ - cerr << "============================================\n"; \ - exit(1); \ - } - // catch(ios_base::failure) { - // cerr << "============================================\n"; - // cerr << "| A ios_base::failure has been detected !!!|\n"; - // cerr << "============================================\n"; - // exit(1); - // } - -#if defined(__GNUC__) && (__GNUC__ > 3) -# define GMM_SET_EXCEPTION_DEBUG \ - std::set_terminate(__gnu_cxx::__verbose_terminate_handler); -#else -# define GMM_SET_EXCEPTION_DEBUG -#endif - -} - - -#endif /* GMM_EXCEPT_H__ */ diff --git a/include/gmm/gmm_inoutput.h b/include/gmm/gmm_inoutput.h deleted file mode 100644 index e47268ab280..00000000000 --- a/include/gmm/gmm_inoutput.h +++ /dev/null @@ -1,1131 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_inoutput.h - @author Yves Renard - @author Julien Pommier - @date July 8, 2003. - @brief Input/output on sparse matrices - - Support Harwell-Boeing and Matrix-Market formats. -*/ -#ifndef GMM_INOUTPUT_H -#define GMM_INOUTPUT_H - -#include -#include "gmm_kernel.h" -namespace gmm { - - /*************************************************************************/ - /* */ - /* Functions to read and write Harwell Boeing format. */ - /* */ - /*************************************************************************/ - - // Fri Aug 15 16:29:47 EDT 1997 - // - // Harwell-Boeing File I/O in C - // V. 1.0 - // - // National Institute of Standards and Technology, MD. - // K.A. Remington - // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - // NOTICE - // - // Permission to use, copy, modify, and distribute this software and - // its documentation for any purpose and without fee is hereby granted - // provided that the above copyright notice appear in all copies and - // that both the copyright notice and this permission notice appear in - // supporting documentation. - // - // Neither the Author nor the Institution (National Institute of Standards - // and Technology) make any representations about the suitability of this - // software for any purpose. This software is provided "as is" without - // expressed or implied warranty. - // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - inline void IOHBTerminate(const char *a) { GMM_ASSERT1(false, a);} - - inline bool is_complex_double__(std::complex) { return true; } - inline bool is_complex_double__(double) { return false; } - - inline int ParseIfmt(const char *fmt, int* perline, int* width) { - if (SECURE_NONCHAR_SSCANF(fmt, " (%dI%d)", perline, width) != 2) { - *perline = 1; - int s = SECURE_NONCHAR_SSCANF(fmt, " (I%d)", width); - GMM_ASSERT1(s == 1, "invalid HB I-format: " << fmt); - } - return *width; - } - - inline int ParseRfmt(const char *fmt, int* perline, int* width, - int* prec, int* flag) { - char p; - *perline = *width = *flag = *prec = 0; -#ifdef GMM_SECURE_CRT - if (sscanf_s(fmt, " (%d%c%d.%d)", perline, &p, sizeof(char), width, prec) - < 3 || !strchr("PEDF", p)) -#else - if (sscanf(fmt, " (%d%c%d.%d)", perline, &p, width, prec) < 3 - || !strchr("PEDF", p)) -#endif - { - *perline = 1; -#ifdef GMM_SECURE_CRT - int s = sscanf_s(fmt, " (%c%d.%d)", &p, sizeof(char), width, prec); -#else - int s = sscanf(fmt, " (%c%d.%d)", &p, width, prec); -#endif - GMM_ASSERT1(s>=2 && strchr("PEDF",p), "invalid HB REAL format: " << fmt); - } - *flag = p; - return *width; - } - - /** matrix input/output for Harwell-Boeing format */ - struct HarwellBoeing_IO { - int nrows() const { return Nrow; } - int ncols() const { return Ncol; } - int nnz() const { return Nnzero; } - int is_complex() const { return Type[0] == 'C'; } - int is_symmetric() const { return Type[1] == 'S'; } - int is_hermitian() const { return Type[1] == 'H'; } - HarwellBoeing_IO() { clear(); } - HarwellBoeing_IO(const char *filename) { clear(); open(filename); } - ~HarwellBoeing_IO() { close(); } - /** open filename and reads header */ - void open(const char *filename); - /** read the opened file */ - template void read(csc_matrix& A); - template void read(MAT &M) IS_DEPRECATED; - template - static void write(const char *filename, const csc_matrix& A); - template - static void write(const char *filename, const csc_matrix& A, - const std::vector &rhs); - template - static void write(const char *filename, - const csc_matrix_ref& A); - template - static void write(const char *filename, - const csc_matrix_ref& A, - const std::vector &rhs); - - /** static method for saving the matrix */ - template static void write(const char *filename, - const MAT& A) IS_DEPRECATED; - private: - FILE *f; - char Title[73], Key[9], Rhstype[4], Type[4]; - int Nrow, Ncol, Nnzero, Nrhs; - char Ptrfmt[17], Indfmt[17], Valfmt[21], Rhsfmt[21]; - int Ptrcrd, Indcrd, Valcrd, Rhscrd; - int lcount; - - - void close() { if (f) fclose(f); clear(); } - void clear() { - Nrow = Ncol = Nnzero = Nrhs = 0; f = 0; lcount = 0; - memset(Type, 0, sizeof Type); - memset(Key, 0, sizeof Key); - memset(Title, 0, sizeof Title); - } - char *getline(char *buf) { - fgets(buf, BUFSIZ, f); ++lcount; - int s = SECURE_NONCHAR_SSCANF(buf,"%*s"); - GMM_ASSERT1(s >= 0, "blank line in HB file at line " << lcount); - return buf; - } - - int substrtoi(const char *p, size_type len) { - char s[100]; len = std::min(len, sizeof s - 1); - SECURE_STRNCPY(s, 100, p, len); s[len] = 0; return atoi(s); - } - double substrtod(const char *p, size_type len, int Valflag) { - char s[100]; len = std::min(len, sizeof s - 1); - SECURE_STRNCPY(s, 100, p, len); s[len] = 0; - if ( Valflag != 'F' && !strchr(s,'E')) { - /* insert a char prefix for exp */ - int last = int(strlen(s)); - for (int j=last+1;j>=0;j--) { - s[j] = s[j-1]; - if ( s[j] == '+' || s[j] == '-' ) { - s[j-1] = char(Valflag); - break; - } - } - } - return atof(s); - } - template - int readHB_data(IND_TYPE colptr[], IND_TYPE rowind[], - double val[]) { - /***********************************************************************/ - /* This function opens and reads the specified file, interpreting its */ - /* contents as a sparse matrix stored in the Harwell/Boeing standard */ - /* format and creating compressed column storage scheme vectors to */ - /* hold the index and nonzero value information. */ - /* */ - /* ---------- */ - /* **CAVEAT** */ - /* ---------- */ - /* Parsing real formats from Fortran is tricky, and this file reader */ - /* does not claim to be foolproof. It has been tested for cases */ - /* when the real values are printed consistently and evenly spaced on */ - /* each line, with Fixed (F), and Exponential (E or D) formats. */ - /* */ - /* ** If the input file does not adhere to the H/B format, the ** */ - /* ** results will be unpredictable. ** */ - /* */ - /***********************************************************************/ - int i,ind,col,offset,count; - int Ptrperline, Ptrwidth, Indperline, Indwidth; - int Valperline, Valwidth, Valprec, Nentries; - int Valflag; /* Indicates 'E','D', or 'F' float format */ - char line[BUFSIZ]; - - /* Parse the array input formats from Line 3 of HB file */ - ParseIfmt(Ptrfmt,&Ptrperline,&Ptrwidth); - ParseIfmt(Indfmt,&Indperline,&Indwidth); - if ( Type[0] != 'P' ) { /* Skip if pattern only */ - ParseRfmt(Valfmt,&Valperline,&Valwidth,&Valprec,&Valflag); - } - - cout << "Valwidth = " << Valwidth << endl; getchar(); - - /* Read column pointer array: */ - offset = 0; /* if base 0 storage is declared (via macro def), */ - /* then storage entries are offset by 1 */ - - for (count = 0, i=0;i Ncol) break; - colptr[count] = substrtoi(line+col,Ptrwidth)-offset; - count++; col += Ptrwidth; - } - } - - /* Read row index array: */ - for (count = 0, i=0;i(strchr(line,'D')) )) *p = 'E'; - } - for (col = 0, ind = 0;ind csc matrices */ - template void - HarwellBoeing_IO::read(csc_matrix& A) { - - typedef typename csc_matrix::IND_TYPE IND_TYPE; - - GMM_ASSERT1(f, "no file opened!"); - GMM_ASSERT1(Type[0] != 'P', - "Bad HB matrix format (pattern matrices not supported)"); - GMM_ASSERT1(!is_complex_double__(T()) || Type[0] != 'R', - "Bad HB matrix format (file contains a REAL matrix)"); - GMM_ASSERT1(is_complex_double__(T()) || Type[0] != 'C', - "Bad HB matrix format (file contains a COMPLEX matrix)"); - if (A.pr) { delete[] A.pr; delete[] A.ir; delete[] A.jc; } - A.nc = ncols(); A.nr = nrows(); - A.pr = 0; - A.jc = new IND_TYPE[ncols()+1]; - A.ir = new IND_TYPE[nnz()]; - A.pr = new T[nnz()]; - readHB_data(A.jc, A.ir, (double*)A.pr); - for (int i = 0; i <= ncols(); ++i) { A.jc[i] += shift; A.jc[i] -= 1; } - for (int i = 0; i < nnz(); ++i) { A.ir[i] += shift; A.ir[i] -= 1; } - } - - template void - HarwellBoeing_IO::read(MAT &M) { - csc_matrix::value_type> csc; - read(csc); - resize(M, mat_nrows(csc), mat_ncols(csc)); - copy(csc, M); - } - - template - inline int writeHB_mat_double(const char* filename, int M, int N, int nz, - const IND_TYPE colptr[], - const IND_TYPE rowind[], - const double val[], int Nrhs, - const double rhs[], const double guess[], - const double exact[], const char* Title, - const char* Key, const char* Type, - const char* Ptrfmt, const char* Indfmt, - const char* Valfmt, const char* Rhsfmt, - const char* Rhstype, int shift) { - /************************************************************************/ - /* The writeHB function opens the named file and writes the specified */ - /* matrix and optional right-hand-side(s) to that file in */ - /* Harwell-Boeing format. */ - /* */ - /* For a description of the Harwell Boeing standard, see: */ - /* Duff, et al., ACM TOMS Vol.15, No.1, March 1989 */ - /* */ - /************************************************************************/ - FILE *out_file; - int i, entry, offset, j, acount, linemod; - int totcrd, ptrcrd, indcrd, valcrd, rhscrd; - int nvalentries, nrhsentries; - int Ptrperline, Ptrwidth, Indperline, Indwidth; - int Rhsperline, Rhswidth, Rhsprec, Rhsflag; - int Valperline, Valwidth, Valprec; - int Valflag; /* Indicates 'E','D', or 'F' float format */ - char pformat[16],iformat[16],vformat[19],rformat[19]; - - if ( Type[0] == 'C' ) - { nvalentries = 2*nz; nrhsentries = 2*M; } - else - { nvalentries = nz; nrhsentries = M; } - - if ( filename != NULL ) { - SECURE_FOPEN(&out_file, filename, "w"); - GMM_ASSERT1(out_file != NULL, "Error: Cannot open file: " << filename); - } else out_file = stdout; - - if ( Ptrfmt == NULL ) Ptrfmt = "(8I10)"; - ParseIfmt(Ptrfmt, &Ptrperline, &Ptrwidth); - SECURE_SPRINTF1(pformat,sizeof(pformat),"%%%dd",Ptrwidth); - ptrcrd = (N+1)/Ptrperline; - if ( (N+1)%Ptrperline != 0) ptrcrd++; - - if ( Indfmt == NULL ) Indfmt = Ptrfmt; - ParseIfmt(Indfmt, &Indperline, &Indwidth); - SECURE_SPRINTF1(iformat,sizeof(iformat), "%%%dd",Indwidth); - indcrd = nz/Indperline; - if ( nz%Indperline != 0) indcrd++; - - if ( Type[0] != 'P' ) { /* Skip if pattern only */ - if ( Valfmt == NULL ) Valfmt = "(4E21.13)"; - ParseRfmt(Valfmt, &Valperline, &Valwidth, &Valprec, &Valflag); - if (Valflag == 'D') *strchr(Valfmt,'D') = 'E'; - if (Valflag == 'F') - SECURE_SPRINTF2(vformat, sizeof(vformat), "%% %d.%df", Valwidth, - Valprec); - else - SECURE_SPRINTF2(vformat, sizeof(vformat), "%% %d.%dE", Valwidth, - Valprec); - valcrd = nvalentries/Valperline; - if ( nvalentries%Valperline != 0) valcrd++; - } else valcrd = 0; - - if ( Nrhs > 0 ) { - if ( Rhsfmt == NULL ) Rhsfmt = Valfmt; - ParseRfmt(Rhsfmt,&Rhsperline,&Rhswidth,&Rhsprec, &Rhsflag); - if (Rhsflag == 'F') - SECURE_SPRINTF2(rformat,sizeof(rformat), "%% %d.%df",Rhswidth,Rhsprec); - else - SECURE_SPRINTF2(rformat,sizeof(rformat), "%% %d.%dE",Rhswidth,Rhsprec); - if (Rhsflag == 'D') *strchr(Rhsfmt,'D') = 'E'; - rhscrd = nrhsentries/Rhsperline; - if ( nrhsentries%Rhsperline != 0) rhscrd++; - if ( Rhstype[1] == 'G' ) rhscrd+=rhscrd; - if ( Rhstype[2] == 'X' ) rhscrd+=rhscrd; - rhscrd*=Nrhs; - } else rhscrd = 0; - - totcrd = 4+ptrcrd+indcrd+valcrd+rhscrd; - - - /* Print header information: */ - - fprintf(out_file,"%-72s%-8s\n%14d%14d%14d%14d%14d\n",Title, Key, totcrd, - ptrcrd, indcrd, valcrd, rhscrd); - fprintf(out_file,"%3s%11s%14d%14d%14d%14d\n",Type," ", M, N, nz, 0); - fprintf(out_file,"%-16s%-16s%-20s", Ptrfmt, Indfmt, Valfmt); - if ( Nrhs != 0 ) { - /* Print Rhsfmt on fourth line and */ - /* optional fifth header line for auxillary vector information:*/ - fprintf(out_file,"%-20s\n%-14s%d\n",Rhsfmt,Rhstype,Nrhs); - } - else - fprintf(out_file,"\n"); - - offset = 1 - shift; /* if base 0 storage is declared (via macro def), */ - /* then storage entries are offset by 1 */ - - /* Print column pointers: */ - for (i = 0; i < N+1; i++) { - entry = colptr[i]+offset; - fprintf(out_file,pformat,entry); - if ( (i+1)%Ptrperline == 0 ) fprintf(out_file,"\n"); - } - - if ( (N+1) % Ptrperline != 0 ) fprintf(out_file,"\n"); - - /* Print row indices: */ - for (i=0;i 0 ) { - for (j=0;j void - HarwellBoeing_IO::write(const char *filename, - const csc_matrix& A) { - write(filename, csc_matrix_ref - (A.pr, A.ir, A.jc, A.nr, A.nc)); - } - - template void - HarwellBoeing_IO::write(const char *filename, - const csc_matrix& A, - const std::vector &rhs) { - write(filename, csc_matrix_ref - (A.pr, A.ir, A.jc, A.nr, A.nc), rhs); - } - - template void - HarwellBoeing_IO::write(const char *filename, - const csc_matrix_ref& A) { - const char *t = 0; - if (is_complex_double__(T())) - if (mat_nrows(A) == mat_ncols(A)) t = "CUA"; else t = "CRA"; - else - if (mat_nrows(A) == mat_ncols(A)) t = "RUA"; else t = "RRA"; - writeHB_mat_double(filename, int(mat_nrows(A)), int(mat_ncols(A)), - A.jc[mat_ncols(A)], A.jc, A.ir, - (const double *)A.pr, - 0, 0, 0, 0, "GETFEM++ CSC MATRIX", "CSCMAT", - t, 0, 0, 0, 0, "F", shift); - } - - template void - HarwellBoeing_IO::write(const char *filename, - const csc_matrix_ref& A, - const std::vector &rhs) { - const char *t = 0; - if (is_complex_double__(T())) - if (mat_nrows(A) == mat_ncols(A)) t = "CUA"; else t = "CRA"; - else - if (mat_nrows(A) == mat_ncols(A)) t = "RUA"; else t = "RRA"; - int Nrhs = gmm::vect_size(rhs) / mat_nrows(A); - writeHB_mat_double(filename, int(mat_nrows(A)), int(mat_ncols(A)), - A.jc[mat_ncols(A)], A.jc, A.ir, - (const double *)A.pr, - Nrhs, (const double *)(&rhs[0]), 0, 0, - "GETFEM++ CSC MATRIX", "CSCMAT", - t, 0, 0, 0, 0, "F ", shift); - } - - - template void - HarwellBoeing_IO::write(const char *filename, const MAT& A) { - gmm::csc_matrix::value_type> - tmp(gmm::mat_nrows(A), gmm::mat_ncols(A)); - gmm::copy(A,tmp); - HarwellBoeing_IO::write(filename, tmp); - } - - /** save a "double" or "std::complex" csc matrix into a - HarwellBoeing file - */ - template inline void - Harwell_Boeing_save(const std::string &filename, - const csc_matrix& A) - { HarwellBoeing_IO::write(filename.c_str(), A); } - - /** save a reference on "double" or "std::complex" csc matrix - into a HarwellBoeing file - */ - template inline void - Harwell_Boeing_save(const std::string &filename, - const csc_matrix_ref& A) - { HarwellBoeing_IO::write(filename.c_str(), A); } - - /** save a "double" or "std::complex" generic matrix - into a HarwellBoeing file making a copy in a csc matrix - */ - template inline void - Harwell_Boeing_save(const std::string &filename, const MAT& A) { - gmm::csc_matrix::value_type> - tmp(gmm::mat_nrows(A), gmm::mat_ncols(A)); - gmm::copy(A, tmp); - HarwellBoeing_IO::write(filename.c_str(), tmp); - } - - template inline void - Harwell_Boeing_save(const std::string &filename, const MAT& A, - const VECT &RHS) { - typedef typename gmm::linalg_traits::value_type T; - gmm::csc_matrix tmp(gmm::mat_nrows(A), gmm::mat_ncols(A)); - gmm::copy(A, tmp); - std::vector tmprhs(gmm::vect_size(RHS)); - gmm::copy(RHS, tmprhs); - HarwellBoeing_IO::write(filename.c_str(), tmp, tmprhs); - } - - /** load a "double" or "std::complex" csc matrix from a - HarwellBoeing file - */ - template void - Harwell_Boeing_load(const std::string &filename, csc_matrix& A) { - HarwellBoeing_IO h(filename.c_str()); h.read(A); - } - - /** load a "double" or "std::complex" generic matrix from a - HarwellBoeing file - */ - template void - Harwell_Boeing_load(const std::string &filename, MAT& A) { - csc_matrix::value_type> csc; - Harwell_Boeing_load(filename, csc); - resize(A, mat_nrows(csc), mat_ncols(csc)); - copy(csc, A); - } - - /*************************************************************************/ - /* */ - /* Functions to read and write MatrixMarket format. */ - /* */ - /*************************************************************************/ - - /* - * Matrix Market I/O library for ANSI C - * - * See http://math.nist.gov/MatrixMarket for details. - * - * - */ - -#define MM_MAX_LINE_LENGTH 1025 -#define MatrixMarketBanner "%%MatrixMarket" -#define MM_MAX_TOKEN_LENGTH 64 - - typedef char MM_typecode[4]; - - /******************* MM_typecode query functions *************************/ - -#define mm_is_matrix(typecode) ((typecode)[0]=='M') - -#define mm_is_sparse(typecode) ((typecode)[1]=='C') -#define mm_is_coordinate(typecode) ((typecode)[1]=='C') -#define mm_is_dense(typecode) ((typecode)[1]=='A') -#define mm_is_array(typecode) ((typecode)[1]=='A') - -#define mm_is_complex(typecode) ((typecode)[2]=='C') -#define mm_is_real(typecode) ((typecode)[2]=='R') -#define mm_is_pattern(typecode) ((typecode)[2]=='P') -#define mm_is_integer(typecode) ((typecode)[2]=='I') - -#define mm_is_symmetric(typecode) ((typecode)[3]=='S') -#define mm_is_general(typecode) ((typecode)[3]=='G') -#define mm_is_skew(typecode) ((typecode)[3]=='K') -#define mm_is_hermitian(typecode) ((typecode)[3]=='H') - - /******************* MM_typecode modify fucntions ************************/ - -#define mm_set_matrix(typecode) ((*typecode)[0]='M') -#define mm_set_coordinate(typecode) ((*typecode)[1]='C') -#define mm_set_array(typecode) ((*typecode)[1]='A') -#define mm_set_dense(typecode) mm_set_array(typecode) -#define mm_set_sparse(typecode) mm_set_coordinate(typecode) - -#define mm_set_complex(typecode) ((*typecode)[2]='C') -#define mm_set_real(typecode) ((*typecode)[2]='R') -#define mm_set_pattern(typecode) ((*typecode)[2]='P') -#define mm_set_integer(typecode) ((*typecode)[2]='I') - - -#define mm_set_symmetric(typecode) ((*typecode)[3]='S') -#define mm_set_general(typecode) ((*typecode)[3]='G') -#define mm_set_skew(typecode) ((*typecode)[3]='K') -#define mm_set_hermitian(typecode) ((*typecode)[3]='H') - -#define mm_clear_typecode(typecode) ((*typecode)[0]=(*typecode)[1]= \ - (*typecode)[2]=' ',(*typecode)[3]='G') - -#define mm_initialize_typecode(typecode) mm_clear_typecode(typecode) - - - /******************* Matrix Market error codes ***************************/ - - -#define MM_COULD_NOT_READ_FILE 11 -#define MM_PREMATURE_EOF 12 -#define MM_NOT_MTX 13 -#define MM_NO_HEADER 14 -#define MM_UNSUPPORTED_TYPE 15 -#define MM_LINE_TOO_LONG 16 -#define MM_COULD_NOT_WRITE_FILE 17 - - - /******************** Matrix Market internal definitions ***************** - - MM_matrix_typecode: 4-character sequence - - object sparse/ data storage - dense type scheme - - string position: [0] [1] [2] [3] - - Matrix typecode: M(atrix) C(oord) R(eal) G(eneral) - A(array) C(omplex) H(ermitian) - P(attern) S(ymmetric) - I(nteger) K(kew) - - ***********************************************************************/ - -#define MM_MTX_STR "matrix" -#define MM_ARRAY_STR "array" -#define MM_DENSE_STR "array" -#define MM_COORDINATE_STR "coordinate" -#define MM_SPARSE_STR "coordinate" -#define MM_COMPLEX_STR "complex" -#define MM_REAL_STR "real" -#define MM_INT_STR "integer" -#define MM_GENERAL_STR "general" -#define MM_SYMM_STR "symmetric" -#define MM_HERM_STR "hermitian" -#define MM_SKEW_STR "skew-symmetric" -#define MM_PATTERN_STR "pattern" - - inline char *mm_typecode_to_str(MM_typecode matcode) { - char buffer[MM_MAX_LINE_LENGTH]; - const char *types[4] = {0,0,0,0}; - /* int error =0; */ - /* int i; */ - - /* check for MTX type */ - if (mm_is_matrix(matcode)) - types[0] = MM_MTX_STR; - /* - else - error=1; - */ - /* check for CRD or ARR matrix */ - if (mm_is_sparse(matcode)) - types[1] = MM_SPARSE_STR; - else - if (mm_is_dense(matcode)) - types[1] = MM_DENSE_STR; - else - return NULL; - - /* check for element data type */ - if (mm_is_real(matcode)) - types[2] = MM_REAL_STR; - else - if (mm_is_complex(matcode)) - types[2] = MM_COMPLEX_STR; - else - if (mm_is_pattern(matcode)) - types[2] = MM_PATTERN_STR; - else - if (mm_is_integer(matcode)) - types[2] = MM_INT_STR; - else - return NULL; - - - /* check for symmetry type */ - if (mm_is_general(matcode)) - types[3] = MM_GENERAL_STR; - else if (mm_is_symmetric(matcode)) - types[3] = MM_SYMM_STR; - else if (mm_is_hermitian(matcode)) - types[3] = MM_HERM_STR; - else if (mm_is_skew(matcode)) - types[3] = MM_SKEW_STR; - else - return NULL; - - SECURE_SPRINTF4(buffer, sizeof(buffer), "%s %s %s %s", types[0], types[1], - types[2], types[3]); - return SECURE_STRDUP(buffer); - - } - - inline int mm_read_banner(FILE *f, MM_typecode *matcode) { - char line[MM_MAX_LINE_LENGTH]; - char banner[MM_MAX_TOKEN_LENGTH]; - char mtx[MM_MAX_TOKEN_LENGTH]; - char crd[MM_MAX_TOKEN_LENGTH]; - char data_type[MM_MAX_TOKEN_LENGTH]; - char storage_scheme[MM_MAX_TOKEN_LENGTH]; - char *p; - /* int ret_code; */ - - mm_clear_typecode(matcode); - - if (fgets(line, MM_MAX_LINE_LENGTH, f) == NULL) - return MM_PREMATURE_EOF; - -#ifdef GMM_SECURE_CRT - if (sscanf_s(line, "%s %s %s %s %s", banner, sizeof(banner), - mtx, sizeof(mtx), crd, sizeof(crd), data_type, - sizeof(data_type), storage_scheme, - sizeof(storage_scheme)) != 5) -#else - if (sscanf(line, "%s %s %s %s %s", banner, mtx, crd, - data_type, storage_scheme) != 5) -#endif - return MM_PREMATURE_EOF; - - for (p=mtx; *p!='\0'; *p=char(tolower(*p)),p++) {}; /* convert to lower case */ - for (p=crd; *p!='\0'; *p=char(tolower(*p)),p++) {}; - for (p=data_type; *p!='\0'; *p=char(tolower(*p)),p++) {}; - for (p=storage_scheme; *p!='\0'; *p=char(tolower(*p)),p++) {}; - - /* check for banner */ - if (strncmp(banner, MatrixMarketBanner, strlen(MatrixMarketBanner)) != 0) - return MM_NO_HEADER; - - /* first field should be "mtx" */ - if (strcmp(mtx, MM_MTX_STR) != 0) - return MM_UNSUPPORTED_TYPE; - mm_set_matrix(matcode); - - - /* second field describes whether this is a sparse matrix (in coordinate - storgae) or a dense array */ - - - if (strcmp(crd, MM_SPARSE_STR) == 0) - mm_set_sparse(matcode); - else - if (strcmp(crd, MM_DENSE_STR) == 0) - mm_set_dense(matcode); - else - return MM_UNSUPPORTED_TYPE; - - - /* third field */ - - if (strcmp(data_type, MM_REAL_STR) == 0) - mm_set_real(matcode); - else - if (strcmp(data_type, MM_COMPLEX_STR) == 0) - mm_set_complex(matcode); - else - if (strcmp(data_type, MM_PATTERN_STR) == 0) - mm_set_pattern(matcode); - else - if (strcmp(data_type, MM_INT_STR) == 0) - mm_set_integer(matcode); - else - return MM_UNSUPPORTED_TYPE; - - - /* fourth field */ - - if (strcmp(storage_scheme, MM_GENERAL_STR) == 0) - mm_set_general(matcode); - else - if (strcmp(storage_scheme, MM_SYMM_STR) == 0) - mm_set_symmetric(matcode); - else - if (strcmp(storage_scheme, MM_HERM_STR) == 0) - mm_set_hermitian(matcode); - else - if (strcmp(storage_scheme, MM_SKEW_STR) == 0) - mm_set_skew(matcode); - else - return MM_UNSUPPORTED_TYPE; - - return 0; - } - - inline int mm_read_mtx_crd_size(FILE *f, int *M, int *N, int *nz ) { - char line[MM_MAX_LINE_LENGTH]; - /* int ret_code;*/ - int num_items_read; - - /* set return null parameter values, in case we exit with errors */ - *M = *N = *nz = 0; - - /* now continue scanning until you reach the end-of-comments */ - do { - if (fgets(line,MM_MAX_LINE_LENGTH,f) == NULL) - return MM_PREMATURE_EOF; - } while (line[0] == '%'); - - /* line[] is either blank or has M,N, nz */ - if (SECURE_NONCHAR_SSCANF(line, "%d %d %d", M, N, nz) == 3) return 0; - else - do { - num_items_read = SECURE_NONCHAR_FSCANF(f, "%d %d %d", M, N, nz); - if (num_items_read == EOF) return MM_PREMATURE_EOF; - } - while (num_items_read != 3); - - return 0; - } - - - inline int mm_read_mtx_crd_data(FILE *f, int, int, int nz, int I[], - int J[], double val[], MM_typecode matcode) { - int i; - if (mm_is_complex(matcode)) { - for (i=0; i void read(Matrix &A); - /* write a matrix */ - template static void - write(const char *filename, const csc_matrix& A); - template static void - write(const char *filename, - const csc_matrix_ref& A); - template static void - write(const char *filename, const MAT& A); - }; - - /** load a matrix-market file */ - template inline void - MatrixMarket_load(const char *filename, Matrix& A) { - MatrixMarket_IO mm; mm.open(filename); - mm.read(A); - } - /** write a matrix-market file */ - template void - MatrixMarket_save(const char *filename, const csc_matrix& A) { - MatrixMarket_IO mm; mm.write(filename, A); - } - - template inline void - MatrixMarket_save(const char *filename, - const csc_matrix_ref& A) { - MatrixMarket_IO mm; mm.write(filename, A); - } - - - inline void MatrixMarket_IO::open(const char *filename) { - if (f) { fclose(f); } - SECURE_FOPEN(&f, filename, "r"); - GMM_ASSERT1(f, "Sorry, cannot open file " << filename); - int s1 = mm_read_banner(f, &matcode); - GMM_ASSERT1(s1 == 0, "Sorry, cannnot find the matrix market banner in " - << filename); - int s2 = mm_is_coordinate(matcode), s3 = mm_is_matrix(matcode); - GMM_ASSERT1(s2 > 0 && s3 > 0, - "file is not coordinate storage or is not a matrix"); - int s4 = mm_is_pattern(matcode); - GMM_ASSERT1(s4 == 0, - "the file does only contain the pattern of a sparse matrix"); - int s5 = mm_is_skew(matcode); - GMM_ASSERT1(s5 == 0, "not currently supporting skew symmetric"); - isSymmetric = mm_is_symmetric(matcode) || mm_is_hermitian(matcode); - isHermitian = mm_is_hermitian(matcode); - isComplex = mm_is_complex(matcode); - mm_read_mtx_crd_size(f, &row, &col, &nz); - } - - template void MatrixMarket_IO::read(Matrix &A) { - typedef typename linalg_traits::value_type T; - GMM_ASSERT1(f, "no file opened!"); - GMM_ASSERT1(!is_complex_double__(T()) || isComplex, - "Bad MM matrix format (complex matrix expected)"); - GMM_ASSERT1(is_complex_double__(T()) || !isComplex, - "Bad MM matrix format (real matrix expected)"); - A = Matrix(row, col); - gmm::clear(A); - - std::vector I(nz), J(nz); - std::vector PR(nz); - mm_read_mtx_crd_data(f, row, col, nz, &I[0], &J[0], - (double*)&PR[0], matcode); - - for (size_type i = 0; i < size_type(nz); ++i) A(I[i]-1, J[i]-1) = PR[i]; - } - - template void - MatrixMarket_IO::write(const char *filename, const csc_matrix& A) { - write(filename, csc_matrix_ref - (A.pr, A.ir, A.jc, A.nr, A.nc)); - } - - template void - MatrixMarket_IO::write(const char *filename, - const csc_matrix_ref& A) { - static MM_typecode t1 = {'M', 'C', 'R', 'G'}; - static MM_typecode t2 = {'M', 'C', 'C', 'G'}; - MM_typecode t; - - if (is_complex_double__(T())) std::copy(&(t2[0]), &(t2[0])+4, &(t[0])); - else std::copy(&(t1[0]), &(t1[0])+4, &(t[0])); - size_type nz = A.jc[mat_ncols(A)]; - std::vector I(nz), J(nz); - for (size_type j=0; j < mat_ncols(A); ++j) { - for (size_type i = A.jc[j]; i < A.jc[j+1]; ++i) { - I[i] = A.ir[i] + 1 - shift; - J[i] = int(j + 1); - } - } - mm_write_mtx_crd(filename, int(mat_nrows(A)), int(mat_ncols(A)), - int(nz), &I[0], &J[0], (const double *)A.pr, t); - } - - - template void - MatrixMarket_IO::write(const char *filename, const MAT& A) { - gmm::csc_matrix::value_type> - tmp(gmm::mat_nrows(A), gmm::mat_ncols(A)); - gmm::copy(A,tmp); - MatrixMarket_IO::write(filename, tmp); - } - - template static void vecsave(std::string fname, const VEC& V) { - std::ofstream f(fname.c_str()); f.precision(16); - for (size_type i=0; i < gmm::vect_size(V); ++i) f << V[i] << "\n"; - } - - template static void vecload(std::string fname, - const VEC& V_) { - VEC &V(const_cast(V_)); - std::ifstream f(fname.c_str()); - for (size_type i=0; i < gmm::vect_size(V); ++i) f >> V[i]; - } -} - - -#endif // GMM_INOUTPUT_H diff --git a/include/gmm/gmm_interface.h b/include/gmm/gmm_interface.h deleted file mode 100644 index 373b45a7333..00000000000 --- a/include/gmm/gmm_interface.h +++ /dev/null @@ -1,1065 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - - -/**@file gmm_interface.h - @author Yves Renard - @date October 13, 2002. - @brief gmm interface for STL vectors. -*/ - -#ifndef GMM_INTERFACE_H__ -#define GMM_INTERFACE_H__ - -#include "gmm_blas.h" -#include "gmm_sub_index.h" - -namespace gmm { - - /* ********************************************************************* */ - /* */ - /* What is needed for a Vector type : */ - /* Vector v(n) defines a vector with n components. */ - /* v[i] allows to access to the ith component of v. */ - /* linalg_traits should be filled with appropriate definitions */ - /* */ - /* for a dense vector : the minimum is two random iterators (begin and */ - /* end) and a pointer to a valid origin. */ - /* for a sparse vector : the minimum is two forward iterators, with */ - /* a method it.index() which gives the index of */ - /* a non zero element, an interface object */ - /* should describe the method to add new non */ - /* zero element, and a pointer to a valid */ - /* origin. */ - /* */ - /* What is needed for a Matrix type : */ - /* Matrix m(n, m) defines a matrix with n rows and m columns. */ - /* m(i, j) allows to access to the element at row i and column j. */ - /* linalg_traits should be filled with appropriate definitions */ - /* */ - /* What is needed for an iterator on dense vector */ - /* to be standard random access iterator */ - /* */ - /* What is needed for an iterator on a sparse vector */ - /* to be a standard bidirectional iterator */ - /* elt should be sorted with increasing indices. */ - /* it.index() gives the index of the non-zero element. */ - /* */ - /* Remark : If original iterators are not convenient, they could be */ - /* redefined and interfaced in linalg_traits without changing */ - /* the original Vector type. */ - /* */ - /* ********************************************************************* */ - - /* ********************************************************************* */ - /* Simple references on vectors */ - /* ********************************************************************* */ - - template struct simple_vector_ref { - typedef simple_vector_ref this_type; - typedef typename std::iterator_traits::value_type V; - typedef V * CPT; - typedef typename std::iterator_traits::reference ref_V; - typedef typename linalg_traits::iterator iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - size_type size_; - - simple_vector_ref(ref_V v) : begin_(vect_begin(const_cast(v))), - end_(vect_end(const_cast(v))), - origin(linalg_origin(const_cast(v))), - size_(vect_size(v)) {} - - simple_vector_ref(const simple_vector_ref &cr) - : begin_(cr.begin_),end_(cr.end_),origin(cr.origin),size_(cr.size_) {} - - simple_vector_ref(void) {} - - reference operator[](size_type i) const - { return linalg_traits::access(origin, begin_, end_, i); } - }; - - template inline - void set_to_begin(IT &it, ORG o, simple_vector_ref *,linalg_modifiable) { - typedef typename linalg_traits >::V_reference ref_t; - set_to_begin(it, o, PT(), ref_t()); - } - - template inline - void set_to_begin(IT &it, ORG o, const simple_vector_ref *, - linalg_modifiable) { - typedef typename linalg_traits >::V_reference ref_t; - set_to_begin(it, o, PT(), ref_t()); - } - - template inline - void set_to_end(IT &it, ORG o, simple_vector_ref *, linalg_modifiable) { - typedef typename linalg_traits >::V_reference ref_t; - set_to_end(it, o, PT(), ref_t()); - } - - template inline - void set_to_end(IT &it, ORG o, const simple_vector_ref *, - linalg_modifiable) { - typedef typename linalg_traits >::V_reference ref_t; - set_to_end(it, o, PT(), ref_t()); - } - - - template struct linalg_traits > { - typedef simple_vector_ref this_type; - typedef this_type *pthis_type; - typedef typename std::iterator_traits::value_type V; - typedef typename linalg_traits::origin_type origin_type; - typedef V *pV; - typedef typename linalg_traits::is_reference V_reference; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef typename select_ref::ref_type porigin_type; - typedef typename select_ref::const_iterator, - typename linalg_traits::iterator, PT>::ref_type iterator; - typedef typename linalg_traits::const_iterator const_iterator; - typedef typename linalg_traits::storage_type storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size_; } - static inline iterator begin(this_type &v) { - iterator it = v.begin_; - set_to_begin(it, v.origin, pthis_type(), is_reference()); - return it; - } - static inline const_iterator begin(const this_type &v) { - const_iterator it = v.begin_; - set_to_begin(it, v.origin, pthis_type(), is_reference()); - return it; - } - static inline iterator end(this_type &v) { - iterator it = v.end_; - set_to_end(it, v.origin, pthis_type(), is_reference()); - return it; - } - static inline const_iterator end(const this_type &v) { - const_iterator it = v.end_; - set_to_end(it, v.origin, pthis_type(), is_reference()); - return it; - } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void clear(origin_type* o, const iterator &it, const iterator &ite) - { linalg_traits::clear(o, it, ite); } - static void do_clear(this_type &v) { clear(v.origin, v.begin_, v.end_); } - static value_type access(const origin_type *o, const const_iterator &it, - const const_iterator &ite, size_type i) - { return linalg_traits::access(o, it, ite, i); } - static reference access(origin_type *o, const iterator &it, - const iterator &ite, size_type i) - { return linalg_traits::access(o, it, ite, i); } - }; - - template - std::ostream &operator << (std::ostream &o, const simple_vector_ref& v) - { gmm::write(o,v); return o; } - - /* ********************************************************************* */ - /* */ - /* Traits for S.T.L. object */ - /* */ - /* ********************************************************************* */ - - template - struct linalg_traits > { - typedef std::vector this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_vector linalg_type; - typedef T value_type; - typedef T& reference; - typedef typename this_type::iterator iterator; - typedef typename this_type::const_iterator const_iterator; - typedef abstract_dense storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return v.begin(); } - static const_iterator begin(const this_type &v) { return v.begin(); } - static iterator end(this_type &v) { return v.end(); } - static const_iterator end(const this_type &v) { return v.end(); } - static origin_type* origin(this_type &v) { return &v; } - static const origin_type* origin(const this_type &v) { return &v; } - static void clear(origin_type*, const iterator &it, const iterator &ite) - { std::fill(it, ite, value_type(0)); } - static void do_clear(this_type &v) { std::fill(v.begin(), v.end(), T(0)); } - static value_type access(const origin_type *, const const_iterator &it, - const const_iterator &, size_type i) - { return it[i]; } - static reference access(origin_type *, const iterator &it, - const iterator &, size_type i) - { return it[i]; } - static void resize(this_type &v, size_type n) { v.resize(n); } - }; -} -namespace std { - template ostream &operator << - (std::ostream &o, const vector& m) { gmm::write(o,m); return o; } -} -namespace gmm { - - template - inline size_type nnz(const std::vector& l) { return l.size(); } - - /* ********************************************************************* */ - /* */ - /* Traits for ref objects */ - /* */ - /* ********************************************************************* */ - - template - struct tab_ref_with_origin : public gmm::tab_ref { - typedef tab_ref_with_origin this_type; - // next line replaced by the 4 following lines in order to please aCC - //typedef typename linalg_traits::porigin_type porigin_type; - typedef typename linalg_traits::origin_type origin_type; - typedef typename std::iterator_traits::pointer PT; - typedef typename select_ref::ref_type porigin_type; - - - porigin_type origin; - - tab_ref_with_origin(void) {} - template tab_ref_with_origin(const IT &b, const IT &e, PT p) - : gmm::tab_ref(b,e), origin(porigin_type(p)) {} - tab_ref_with_origin(const IT &b, const IT &e, porigin_type p) - : gmm::tab_ref(b,e), origin(p) {} - - tab_ref_with_origin(const V &v, const sub_interval &si) - : gmm::tab_ref(vect_begin(const_cast(v))+si.min, - vect_begin(const_cast(v))+si.max), - origin(linalg_origin(const_cast(v))) {} - tab_ref_with_origin(V &v, const sub_interval &si) - : gmm::tab_ref(vect_begin(const_cast(v))+si.min, - vect_begin(const_cast(v))+si.max), - origin(linalg_origin(const_cast(v))) {} - }; - - template - struct linalg_traits > { - typedef typename std::iterator_traits::pointer PT; - typedef typename linalg_traits::origin_type origin_type; - typedef tab_ref_with_origin this_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::reference reference; - typedef typename this_type::iterator iterator; - typedef typename this_type::iterator const_iterator; - typedef abstract_dense storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return v.begin(); } - static const_iterator begin(const this_type &v) { return v.begin(); } - static iterator end(this_type &v) { return v.end(); } - static const_iterator end(const this_type &v) { return v.end(); } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void clear(origin_type*, const iterator &it, const iterator &ite) - { std::fill(it, ite, value_type(0)); } - static inline void do_clear(this_type &v) - { std::fill(v.begin(), v.end(), value_type(0)); } - static value_type access(const origin_type *, const const_iterator &it, - const const_iterator &, size_type i) - { return it[i]; } - static reference access(origin_type *, const iterator &it, - const iterator &, size_type i) - { return it[i]; } - }; - - template std::ostream &operator << - (std::ostream &o, const tab_ref_with_origin& m) - { gmm::write(o,m); return o; } - - - template - struct tab_ref_reg_spaced_with_origin : public gmm::tab_ref_reg_spaced { - typedef tab_ref_reg_spaced_with_origin this_type; - typedef typename linalg_traits::porigin_type porigin_type; - - porigin_type origin; - - tab_ref_reg_spaced_with_origin(void) {} - tab_ref_reg_spaced_with_origin(const IT &b, size_type n, size_type s, - const porigin_type p) - : gmm::tab_ref_reg_spaced(b,n,s), origin(p) {} - tab_ref_reg_spaced_with_origin(const V &v, const sub_slice &si) - : gmm::tab_ref_reg_spaced(vect_begin(const_cast(v)) + si.min, - si.N, (si.max - si.min)/si.N), - origin(linalg_origin(const_cast(v))) {} - tab_ref_reg_spaced_with_origin(V &v, const sub_slice &si) - : gmm::tab_ref_reg_spaced(vect_begin(const_cast(v)) + si.min, - si.N, (si.max - si.min)/si.N), - origin(linalg_origin(const_cast(v))) {} - }; - - template - struct linalg_traits > { - typedef typename std::iterator_traits::pointer PT; - typedef tab_ref_reg_spaced_with_origin this_type; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::reference reference; - typedef typename this_type::iterator iterator; - typedef typename this_type::iterator const_iterator; - typedef abstract_dense storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return v.begin(); } - static const_iterator begin(const this_type &v) { return v.begin(); } - static iterator end(this_type &v) { return v.end(); } - static const_iterator end(const this_type &v) { return v.end(); } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void clear(origin_type*, const iterator &it, const iterator &ite) - { std::fill(it, ite, value_type(0)); } - static void do_clear(this_type &v) - { std::fill(v.begin(), v.end(), value_type(0)); } - static value_type access(const origin_type *, const const_iterator &it, - const const_iterator &, size_type i) - { return it[i]; } - static reference access(origin_type *, const iterator &it, - const iterator &, size_type i) - { return it[i]; } - }; - - template std::ostream &operator << - (std::ostream &o, const tab_ref_reg_spaced_with_origin& m) - { gmm::write(o,m); return o; } - - - template - struct tab_ref_index_ref_with_origin - : public gmm::tab_ref_index_ref { - typedef tab_ref_index_ref_with_origin this_type; - typedef typename linalg_traits::porigin_type porigin_type; - - porigin_type origin; - - tab_ref_index_ref_with_origin(void) {} - tab_ref_index_ref_with_origin(const IT &b, const ITINDEX &bi, - const ITINDEX &ei, porigin_type p) - : gmm::tab_ref_index_ref(b, bi, ei), origin(p) {} - - tab_ref_index_ref_with_origin(const V &v, const sub_index &si) - : gmm::tab_ref_index_ref(vect_begin(const_cast(v)), - si.begin(), si.end()), - origin(linalg_origin(const_cast(v))) {} - tab_ref_index_ref_with_origin(V &v, const sub_index &si) - : gmm::tab_ref_index_ref(vect_begin(const_cast(v)), - si.begin(), si.end()), - origin(linalg_origin(const_cast(v))) {} - }; - - template - struct linalg_traits > { - typedef typename std::iterator_traits::pointer PT; - typedef tab_ref_index_ref_with_origin this_type; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::reference reference; - typedef typename this_type::iterator iterator; - typedef typename this_type::iterator const_iterator; - typedef abstract_dense storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return v.begin(); } - static const_iterator begin(const this_type &v) { return v.begin(); } - static iterator end(this_type &v) { return v.end(); } - static const_iterator end(const this_type &v) { return v.end(); } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void clear(origin_type*, const iterator &it, const iterator &ite) - { std::fill(it, ite, value_type(0)); } - static void do_clear(this_type &v) - { std::fill(v.begin(), v.end(), value_type(0)); } - static value_type access(const origin_type *, const const_iterator &it, - const const_iterator &, size_type i) - { return it[i]; } - static reference access(origin_type *, const iterator &it, - const iterator &, size_type i) - { return it[i]; } - }; - - template - std::ostream &operator << - (std::ostream &o, const tab_ref_index_ref_with_origin& m) - { gmm::write(o,m); return o; } - - - template - struct dense_compressed_iterator { - typedef ITER value_type; - typedef ITER *pointer; - typedef ITER &reference; - typedef ptrdiff_t difference_type; - typedef std::random_access_iterator_tag iterator_category; - typedef size_t size_type; - typedef dense_compressed_iterator iterator; - typedef typename std::iterator_traits::value_type *MPT; - - ITER it; - size_type N, nrows, ncols, i; - PT origin; - - iterator operator ++(int) { iterator tmp = *this; i++; return tmp; } - iterator operator --(int) { iterator tmp = *this; i--; return tmp; } - iterator &operator ++() { ++i; return *this; } - iterator &operator --() { --i; return *this; } - iterator &operator +=(difference_type ii) { i += ii; return *this; } - iterator &operator -=(difference_type ii) { i -= ii; return *this; } - iterator operator +(difference_type ii) const - { iterator itt = *this; return (itt += ii); } - iterator operator -(difference_type ii) const - { iterator itt = *this; return (itt -= ii); } - difference_type operator -(const iterator &ii) const - { return (N ? (it - ii.it) / N : 0) + i - ii.i; } - - ITER operator *() const { return it+i*N; } - ITER operator [](int ii) const { return it + (i+ii) * N; } - - bool operator ==(const iterator &ii) const - { return (*this - ii) == difference_type(0); } - bool operator !=(const iterator &ii) const { return !(ii == *this); } - bool operator < (const iterator &ii) const - { return (*this - ii) < difference_type(0); } - - dense_compressed_iterator(void) {} - dense_compressed_iterator(const dense_compressed_iterator &ii) - : it(ii.it), N(ii.N), nrows(ii.nrows), ncols(ii.ncols), i(ii.i), - origin(ii.origin) {} - dense_compressed_iterator(const ITER &iter, size_type n, size_type r, - size_type c, size_type ii, PT o) - : it(iter), N(n), nrows(r), ncols(c), i(ii), origin(o) { } - - }; - - /* ******************************************************************** */ - /* Read only reference on a compressed sparse vector */ - /* ******************************************************************** */ - - template - struct cs_vector_ref_iterator { - PT1 pr; - PT2 ir; - - typedef typename std::iterator_traits::value_type value_type; - typedef PT1 pointer; - typedef typename std::iterator_traits::reference reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - typedef cs_vector_ref_iterator iterator; - - cs_vector_ref_iterator(void) {} - cs_vector_ref_iterator(PT1 p1, PT2 p2) : pr(p1), ir(p2) {} - - inline size_type index(void) const { return (*ir) - shift; } - iterator &operator ++() { ++pr; ++ir; return *this; } - iterator operator ++(int) { iterator tmp = *this; ++(*this); return tmp; } - iterator &operator --() { --pr; --ir; return *this; } - iterator operator --(int) { iterator tmp = *this; --(*this); return tmp; } - - reference operator *() const { return *pr; } - pointer operator ->() const { return pr; } - - bool operator ==(const iterator &i) const { return (i.pr==pr);} - bool operator !=(const iterator &i) const { return (i.pr!=pr);} - }; - - template struct cs_vector_ref { - PT1 pr; - PT2 ir; - size_type n, size_; - - typedef cs_vector_ref this_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename linalg_traits::const_iterator const_iterator; - - cs_vector_ref(PT1 pt1, PT2 pt2, size_type nnz, size_type ns) - : pr(pt1), ir(pt2), n(nnz), size_(ns) {} - cs_vector_ref(void) {} - - size_type size(void) const { return size_; } - - const_iterator begin(void) const { return const_iterator(pr, ir); } - const_iterator end(void) const { return const_iterator(pr+n, ir+n); } - - value_type operator[](size_type i) const - { return linalg_traits::access(pr, begin(), end(),i); } - }; - - template - struct linalg_traits > { - typedef cs_vector_ref this_type; - typedef linalg_const is_reference; - typedef abstract_vector linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef value_type origin_type; - typedef typename std::iterator_traits::value_type reference; - typedef cs_vector_ref_iterator::pointer, - typename const_pointer::pointer, shift> const_iterator; - typedef abstract_null_type iterator; - typedef abstract_sparse storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return v.begin(); } - static const_iterator begin(const this_type &v) { return v.begin(); } - static iterator end(this_type &v) { return v.end(); } - static const_iterator end(const this_type &v) { return v.end(); } - static const origin_type* origin(const this_type &v) { return v.pr; } - static value_type access(const origin_type *, const const_iterator &b, - const const_iterator &e, size_type i) { - if (b.ir == e.ir) return value_type(0); - PT2 p = std::lower_bound(b.ir, e.ir, i+shift); - return (*p == i+shift && p != e.ir) ? b.pr[p-b.ir] : value_type(0); - } - }; - - template - std::ostream &operator << - (std::ostream &o, const cs_vector_ref& m) - { gmm::write(o,m); return o; } - - template - inline size_type nnz(const cs_vector_ref& l) { return l.n; } - - /* ******************************************************************** */ - /* Read only reference on a compressed sparse column matrix */ - /* ******************************************************************** */ - - template - struct sparse_compressed_iterator { - typedef typename std::iterator_traits::value_type value_type; - typedef const value_type *pointer; - typedef const value_type &reference; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - typedef std::random_access_iterator_tag iterator_category; - typedef sparse_compressed_iterator iterator; - - PT1 pr; - PT2 ir; - PT3 jc; - size_type n; - const value_type *origin; - - iterator operator ++(int) { iterator tmp = *this; jc++; return tmp; } - iterator operator --(int) { iterator tmp = *this; jc--; return tmp; } - iterator &operator ++() { jc++; return *this; } - iterator &operator --() { jc--; return *this; } - iterator &operator +=(difference_type i) { jc += i; return *this; } - iterator &operator -=(difference_type i) { jc -= i; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const { return jc - i.jc; } - - reference operator *() const { return pr + *jc - shift; } - reference operator [](int ii) { return pr + *(jc+ii) - shift; } - - bool operator ==(const iterator &i) const { return (jc == i.jc); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (jc < i.jc); } - - sparse_compressed_iterator(void) {} - sparse_compressed_iterator(PT1 p1, PT2 p2, PT3 p3, size_type nn, - const value_type *o) - : pr(p1), ir(p2), jc(p3), n(nn), origin(o) { } - - }; - - template - struct csc_matrix_ref { - PT1 pr; // values. - PT2 ir; // row indexes. - PT3 jc; // column repartition on pr and ir. - size_type nc, nr; - - typedef typename std::iterator_traits::value_type value_type; - csc_matrix_ref(PT1 pt1, PT2 pt2, PT3 pt3, size_type nrr, size_type ncc) - : pr(pt1), ir(pt2), jc(pt3), nc(ncc), nr(nrr) {} - csc_matrix_ref(void) {} - - size_type nrows(void) const { return nr; } - size_type ncols(void) const { return nc; } - - value_type operator()(size_type i, size_type j) const - { return mat_col(*this, j)[i]; } - }; - - template - struct linalg_traits > { - typedef csc_matrix_ref this_type; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::value_type reference; - typedef value_type origin_type; - typedef abstract_sparse storage_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_row_iterator; - typedef abstract_null_type sub_col_type; - typedef cs_vector_ref::pointer, - typename const_pointer::pointer, shift> const_sub_col_type; - typedef sparse_compressed_iterator::pointer, - typename const_pointer::pointer, - typename const_pointer::pointer, - shift> const_col_iterator; - typedef abstract_null_type col_iterator; - typedef col_major sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m.pr, m.ir, m.jc, m.nr, m.pr); } - static const_col_iterator col_end(const this_type &m) - { return const_col_iterator(m.pr, m.ir, m.jc + m.nc, m.nr, m.pr); } - static const_sub_col_type col(const const_col_iterator &it) { - return const_sub_col_type(it.pr + *(it.jc) - shift, - it.ir + *(it.jc) - shift, *(it.jc + 1) - *(it.jc), it.n); - } - static const origin_type* origin(const this_type &m) { return m.pr; } - static value_type access(const const_col_iterator &itcol, size_type j) - { return col(itcol)[j]; } - }; - - - template - std::ostream &operator << - (std::ostream &o, const csc_matrix_ref& m) - { gmm::write(o,m); return o; } - - /* ******************************************************************** */ - /* Read only reference on a compressed sparse row matrix */ - /* ******************************************************************** */ - - template - struct csr_matrix_ref { - PT1 pr; // values. - PT2 ir; // column indexes. - PT3 jc; // row repartition on pr and ir. - size_type nc, nr; - - typedef typename std::iterator_traits::value_type value_type; - csr_matrix_ref(PT1 pt1, PT2 pt2, PT3 pt3, size_type nrr, size_type ncc) - : pr(pt1), ir(pt2), jc(pt3), nc(ncc), nr(nrr) {} - csr_matrix_ref(void) {} - - size_type nrows(void) const { return nr; } - size_type ncols(void) const { return nc; } - - value_type operator()(size_type i, size_type j) const - { return mat_col(*this, i)[j]; } - }; - - template - struct linalg_traits > { - typedef csr_matrix_ref this_type; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::value_type reference; - typedef value_type origin_type; - typedef abstract_sparse storage_type; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_col_iterator; - typedef abstract_null_type sub_row_type; - typedef cs_vector_ref::pointer, - typename const_pointer::pointer, shift> - const_sub_row_type; - typedef sparse_compressed_iterator::pointer, - typename const_pointer::pointer, - typename const_pointer::pointer, - shift> const_row_iterator; - typedef abstract_null_type row_iterator; - typedef row_major sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m.pr, m.ir, m.jc, m.nc, m.pr); } - static const_row_iterator row_end(const this_type &m) - { return const_row_iterator(m.pr, m.ir, m.jc + m.nr, m.nc, m.pr); } - static const_sub_row_type row(const const_row_iterator &it) { - return const_sub_row_type(it.pr + *(it.jc) - shift, - it.ir + *(it.jc) - shift, *(it.jc + 1) - *(it.jc), it.n); - } - static const origin_type* origin(const this_type &m) { return m.pr; } - static value_type access(const const_row_iterator &itrow, size_type j) - { return row(itrow)[j]; } - }; - - template - std::ostream &operator << - (std::ostream &o, const csr_matrix_ref& m) - { gmm::write(o,m); return o; } - - /* ********************************************************************* */ - /* */ - /* Simple interface for C arrays */ - /* */ - /* ********************************************************************* */ - - template struct array1D_reference { - - typedef typename std::iterator_traits::value_type value_type; - - PT begin, end; - - const value_type &operator[](size_type i) const { return *(begin+i); } - value_type &operator[](size_type i) { return *(begin+i); } - - array1D_reference(PT begin_, size_type s) : begin(begin_), end(begin_+s) {} - }; - - template - struct linalg_traits > { - typedef array1D_reference this_type; - typedef this_type origin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::reference reference; - typedef PT iterator; - typedef PT const_iterator; - typedef abstract_dense storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.end - v.begin; } - static iterator begin(this_type &v) { return v.begin; } - static const_iterator begin(const this_type &v) { return v.begin; } - static iterator end(this_type &v) { return v.end; } - static const_iterator end(const this_type &v) { return v.end; } - static origin_type* origin(this_type &v) { return &v; } - static const origin_type* origin(const this_type &v) { return &v; } - static void clear(origin_type*, const iterator &it, const iterator &ite) - { std::fill(it, ite, value_type(0)); } - static void do_clear(this_type &v) - { std::fill(v.begin, v.end, value_type(0)); } - static value_type access(const origin_type *, const const_iterator &it, - const const_iterator &, size_type i) - { return it[i]; } - static reference access(origin_type *, const iterator &it, - const iterator &, size_type i) - { return it[i]; } - static void resize(this_type &, size_type ) - { GMM_ASSERT1(false, "Not resizable vector"); } - }; - - template std::ostream &operator << - (std::ostream &o, const array1D_reference& v) - { gmm::write(o,v); return o; } - - template struct array2D_col_reference { - - typedef typename std::iterator_traits::value_type T; - typedef typename std::iterator_traits::reference reference; - typedef typename const_reference::reference const_reference; - typedef PT iterator; - typedef typename const_pointer::pointer const_iterator; - - PT begin_; - size_type nbl, nbc; - - inline const_reference operator ()(size_type l, size_type c) const { - GMM_ASSERT2(l < nbl && c < nbc, "out of range"); - return *(begin_ + c*nbl+l); - } - inline reference operator ()(size_type l, size_type c) { - GMM_ASSERT2(l < nbl && c < nbc, "out of range"); - return *(begin_ + c*nbl+l); - } - - void resize(size_type, size_type); - void reshape(size_type m, size_type n) { - GMM_ASSERT2(n*m == nbl*nbc, "dimensions mismatch"); - nbl = m; nbc = n; - } - - void fill(T a, T b = T(0)) { - std::fill(begin_, end+nbc*nbl, b); - iterator p = begin_, e = end+nbc*nbl; - while (p < e) { *p = a; p += nbl+1; } - } - inline size_type nrows(void) const { return nbl; } - inline size_type ncols(void) const { return nbc; } - - iterator begin(void) { return begin_; } - const_iterator begin(void) const { return begin_; } - iterator end(void) { return begin_+nbl*nbc; } - const_iterator end(void) const { return begin_+nbl*nbc; } - - array2D_col_reference(PT begin__, size_type nrows_, size_type ncols_) - : begin_(begin__), nbl(nrows_), nbc(ncols_) {} - }; - - template struct linalg_traits > { - typedef array2D_col_reference this_type; - typedef this_type origin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::reference reference; - typedef abstract_dense storage_type; - typedef tab_ref_reg_spaced_with_origin sub_row_type; - typedef tab_ref_reg_spaced_with_origin const_sub_row_type; - typedef dense_compressed_iterator row_iterator; - typedef dense_compressed_iterator const_row_iterator; - typedef tab_ref_with_origin sub_col_type; - typedef tab_ref_with_origin const_sub_col_type; - typedef dense_compressed_iterator col_iterator; - typedef dense_compressed_iterator const_col_iterator; - typedef col_and_row sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_sub_row_type row(const const_row_iterator &it) - { return const_sub_row_type(*it, it.nrows, it.ncols, it.origin); } - static const_sub_col_type col(const const_col_iterator &it) - { return const_sub_col_type(*it, *it + it.nrows, it.origin); } - static sub_row_type row(const row_iterator &it) - { return sub_row_type(*it, it.nrows, it.ncols, it.origin); } - static sub_col_type col(const col_iterator &it) - { return sub_col_type(*it, *it + it.nrows, it.origin); } - static row_iterator row_begin(this_type &m) - { return row_iterator(m.begin(), 1, m.nrows(), m.ncols(), 0, &m); } - static row_iterator row_end(this_type &m) - { return row_iterator(m.begin(), 1, m.nrows(), m.ncols(), m.nrows(), &m); } - static const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m.begin(), 1, m.nrows(), m.ncols(), 0, &m); } - static const_row_iterator row_end(const this_type &m) { - return const_row_iterator(m.begin(), 1, m.nrows(), - m.ncols(), m.nrows(), &m); - } - static col_iterator col_begin(this_type &m) - { return col_iterator(m.begin(), m.nrows(), m.nrows(), m.ncols(), 0, &m); } - static col_iterator col_end(this_type &m) { - return col_iterator(m.begin(), m.nrows(), m.nrows(), m.ncols(), - m.ncols(), &m); - } - static const_col_iterator col_begin(const this_type &m) { - return const_col_iterator(m.begin(), m.nrows(), m.nrows(), - m.ncols(), 0, &m); - } - static const_col_iterator col_end(const this_type &m) { - return const_col_iterator(m.begin(), m.nrows(),m.nrows(),m.ncols(), - m.ncols(), &m); - } - static origin_type* origin(this_type &m) { return &m; } - static const origin_type* origin(const this_type &m) { return &m; } - static void do_clear(this_type &m) { m.fill(value_type(0)); } - static value_type access(const const_col_iterator &itcol, size_type j) - { return (*itcol)[j]; } - static reference access(const col_iterator &itcol, size_type j) - { return (*itcol)[j]; } - static void resize(this_type &v, size_type m, size_type n) - { v.resize(m,n); } - static void reshape(this_type &v, size_type m, size_type n) - { v.reshape(m, n); } - }; - - template std::ostream &operator << - (std::ostream &o, const array2D_col_reference& m) - { gmm::write(o,m); return o; } - - - - template struct array2D_row_reference { - - typedef typename std::iterator_traits::value_type T; - typedef typename std::iterator_traits::reference reference; - typedef typename const_reference::reference const_reference; - typedef PT iterator; - typedef typename const_pointer::pointer const_iterator; - - PT begin_; - size_type nbl, nbc; - - inline const_reference operator ()(size_type l, size_type c) const { - GMM_ASSERT2(l < nbl && c < nbc, "out of range"); - return *(begin_ + l*nbc+c); - } - inline reference operator ()(size_type l, size_type c) { - GMM_ASSERT2(l < nbl && c < nbc, "out of range"); - return *(begin_ + l*nbc+c); - } - - void resize(size_type, size_type); - void reshape(size_type m, size_type n) { - GMM_ASSERT2(n*m == nbl*nbc, "dimensions mismatch"); - nbl = m; nbc = n; - } - - void fill(T a, T b = T(0)) { - std::fill(begin_, end+nbc*nbl, b); - iterator p = begin_, e = end+nbc*nbl; - while (p < e) { *p = a; p += nbc+1; } - } - inline size_type nrows(void) const { return nbl; } - inline size_type ncols(void) const { return nbc; } - - iterator begin(void) { return begin_; } - const_iterator begin(void) const { return begin_; } - iterator end(void) { return begin_+nbl*nbc; } - const_iterator end(void) const { return begin_+nbl*nbc; } - - array2D_row_reference(PT begin__, size_type nrows_, size_type ncols_) - : begin_(begin__), nbl(nrows_), nbc(ncols_) {} - }; - - template struct linalg_traits > { - typedef array2D_row_reference this_type; - typedef this_type origin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::reference reference; - typedef abstract_dense storage_type; - typedef tab_ref_reg_spaced_with_origin sub_col_type; - typedef tab_ref_reg_spaced_with_origin const_sub_col_type; - typedef dense_compressed_iterator col_iterator; - typedef dense_compressed_iterator const_col_iterator; - typedef tab_ref_with_origin sub_row_type; - typedef tab_ref_with_origin const_sub_row_type; - typedef dense_compressed_iterator row_iterator; - typedef dense_compressed_iterator const_row_iterator; - typedef col_and_row sub_orientation; - typedef linalg_true index_sorted; - static size_type ncols(const this_type &m) { return m.ncols(); } - static size_type nrows(const this_type &m) { return m.nrows(); } - static const_sub_col_type col(const const_col_iterator &it) - { return const_sub_col_type(*it, it.ncols, it.nrows, it.origin); } - static const_sub_row_type row(const const_row_iterator &it) - { return const_sub_row_type(*it, *it + it.ncols, it.origin); } - static sub_col_type col(const col_iterator &it) - { return sub_col_type(*it, *it, it.ncols, it.nrows, it.origin); } - static sub_row_type row(const row_iterator &it) - { return sub_row_type(*it, *it + it.ncols, it.origin); } - static col_iterator col_begin(this_type &m) - { return col_iterator(m.begin(), 1, m.ncols(), m.nrows(), 0, &m); } - static col_iterator col_end(this_type &m) - { return col_iterator(m.begin(), 1, m.ncols(), m.nrows(), m.ncols(), &m); } - static const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m.begin(), 1, m.ncols(), m.nrows(), 0, &m); } - static const_col_iterator col_end(const this_type &m) { - return const_col_iterator(m.begin(), 1, m.ncols(), - m.nrows(), m.ncols(), &m); - } - static row_iterator row_begin(this_type &m) - { return row_iterator(m.begin(), m.ncols(), m.ncols(), m.nrows(), 0, &m); } - static row_iterator row_end(this_type &m) { - return row_iterator(m.begin(), m.ncols(), m.ncols(), m.nrows(), - m.nrows(), &m); - } - static const_row_iterator row_begin(const this_type &m) { - return const_row_iterator(m.begin(), m.ncols(), m.ncols(), m.nrows(), - 0, &m); - } - static const_row_iterator row_end(const this_type &m) { - return const_row_iterator(m.begin(), m.ncols(), m.ncols(), m.nrows(), - m.nrows(), &m); - } - static origin_type* origin(this_type &m) { return &m; } - static const origin_type* origin(const this_type &m) { return &m; } - static void do_clear(this_type &m) { m.fill(value_type(0)); } - static value_type access(const const_row_iterator &itrow, size_type j) - { return (*itrow)[j]; } - static reference access(const row_iterator &itrow, size_type j) - { return (*itrow)[j]; } - static void resize(this_type &v, size_type m, size_type n) - { v.resize(m,n); } - static void reshape(this_type &v, size_type m, size_type n) - { v.reshape(m, n); } - }; - - template std::ostream &operator << - (std::ostream &o, const array2D_row_reference& m) - { gmm::write(o,m); return o; } - - - - - - -} - - -#endif // GMM_INTERFACE_H__ diff --git a/include/gmm/gmm_interface_bgeot.h b/include/gmm/gmm_interface_bgeot.h deleted file mode 100644 index 6e1b7b567e3..00000000000 --- a/include/gmm/gmm_interface_bgeot.h +++ /dev/null @@ -1,82 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_interface_bgeot.h - @author Yves Renard - @date October 13, 2002. - @brief interface for bgeot::small_vector -*/ -#ifndef GMM_INTERFACE_BGEOT_H__ -#define GMM_INTERFACE_BGEOT_H__ - - -namespace gmm { - - /* ********************************************************************* */ - /* */ - /* Traits for bgeot objects */ - /* */ - /* ********************************************************************* */ - - template struct linalg_traits > { - typedef bgeot::small_vector this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_vector linalg_type; - typedef T value_type; - typedef T& reference; - typedef typename this_type::iterator iterator; - typedef typename this_type::const_iterator const_iterator; - typedef abstract_dense storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return v.begin(); } - static const_iterator begin(const this_type &v) { return v.begin(); } - static iterator end(this_type &v) { return v.end(); } - static const_iterator end(const this_type &v) { return v.end(); } - static origin_type* origin(this_type &v) { return &v; } - static const origin_type* origin(const this_type &v) { return &v; } - static void clear(origin_type* o, const iterator &it, const iterator &ite) - { std::fill(it, ite, value_type(0)); } - static void do_clear(this_type &v) - { std::fill(v.begin(), v.end(), value_type(0)); } - static value_type access(const origin_type *, const const_iterator &it, - const const_iterator &, size_type i) - { return it[i]; } - static reference access(origin_type *, const iterator &it, - const iterator &, size_type i) - { return it[i]; } - static void resize(this_type &v, size_type n) { v.resize(n); } - }; - -} - - -#endif // GMM_INTERFACE_BGEOT_H__ diff --git a/include/gmm/gmm_iter.h b/include/gmm/gmm_iter.h deleted file mode 100644 index 029e340e3cb..00000000000 --- a/include/gmm/gmm_iter.h +++ /dev/null @@ -1,139 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_iter.h - @author Yves Renard - @date February 10, 2003. - @brief Iteration object. -*/ - -#ifndef GMM_ITER_H__ -#define GMM_ITER_H__ - -#include "gmm_kernel.h" - -namespace gmm { - - /** The Iteration object calculates whether the solution has reached the - desired accuracy, or whether the maximum number of iterations has - been reached. - - The method finished() checks the convergence. The first() - method is used to determine the first iteration of the loop. - */ - class iteration { - protected : - double rhsn; /* Right hand side norm. */ - size_type maxiter; /* Max. number of iterations. */ - int noise; /* if noise > 0 iterations are printed. */ - double resmax; /* maximum residu. */ - double resminreach, resadd; - size_type nit; /* iteration number. */ - double res; /* last computed residu. */ - std::string name; /* eventually, name of the method. */ - bool written; - void (*callback)(const gmm::iteration&); - public : - - void init(void) { - nit = 0; res = 0.0; written = false; - resminreach = 1E50; resadd = 0.0; - callback = 0; - } - - iteration(double r = 1.0E-8, int noi = 0, size_type mit = size_type(-1)) - : rhsn(1.0), maxiter(mit), noise(noi), resmax(r) { init(); } - - void operator ++(int) { nit++; written = false; resadd += res; } - void operator ++() { (*this)++; } - - bool first(void) { return nit == 0; } - - /* get/set the "noisyness" (verbosity) of the solvers */ - int get_noisy(void) const { return noise; } - void set_noisy(int n) { noise = n; } - void reduce_noisy(void) { if (noise > 0) noise--; } - - double get_resmax(void) const { return resmax; } - void set_resmax(double r) { resmax = r; } - - double get_res() const { return res; } - - /* change the user-definable callback, called after each iteration */ - void set_callback(void (*t)(const gmm::iteration&)) { - callback = t; - } - - size_type get_iteration(void) const { return nit; } - void set_iteration(size_type i) { nit = i; } - - size_type get_maxiter(void) const { return maxiter; } - void set_maxiter(size_type i) { maxiter = i; } - - double get_rhsnorm(void) const { return rhsn; } - void set_rhsnorm(double r) { rhsn = r; } - - bool converged(void) { return res <= rhsn * resmax; } - bool converged(double nr) { - res = gmm::abs(nr); resminreach = std::min(resminreach, res); - return converged(); - } - template bool converged(const VECT &v) - { return converged(gmm::vect_norm2(v)); } - - bool finished(double nr) { - if (callback) callback(*this); - if (noise > 0 && !written) { - double a = (rhsn == 0) ? 1.0 : rhsn; - converged(nr); - cout << name << " iter " << nit << " residual " - << gmm::abs(nr) / a; -// if (nit % 100 == 0 && nit > 0) { -// cout << " (residual min " << resminreach / a << " mean val " -// << resadd / (100.0 * a) << " )"; -// resadd = 0.0; -// } - cout << endl; - written = true; - } - return (nit >= maxiter || converged(nr)); - } - template bool finished_vect(const VECT &v) - { return finished(double(gmm::vect_norm2(v))); } - - - void set_name(const std::string &n) { name = n; } - const std::string &get_name(void) const { return name; } - - }; - -} - -#endif /* GMM_ITER_H__ */ diff --git a/include/gmm/gmm_iter_solvers.h b/include/gmm/gmm_iter_solvers.h deleted file mode 100644 index 395c5afd370..00000000000 --- a/include/gmm/gmm_iter_solvers.h +++ /dev/null @@ -1,109 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_iter_solvers.h - @author Yves Renard - @date October 13, 2002. - @brief Include standard gmm iterative solvers (cg, gmres, ...) -*/ -#ifndef GMM_ITER_SOLVERS_H__ -#define GMM_ITER_SOLVERS_H__ - -#include "gmm_iter.h" - - -namespace gmm { - - /** mixed method to find a zero of a real function G, a priori - * between a and b. If the zero is not between a and b, iterations - * of secant are applied. When a convenient interval is found, - * iterations of dichotomie and regula falsi are applied. - */ - template - T find_root(const FUNC &G, T a = T(0), T b = T(1), - T tol = gmm::default_tol(T())) { - T c, Ga = G(a), Gb = G(b), Gc, d; - d = gmm::abs(b - a); -#if 0 - for (int i = 0; i < 4; i++) { /* secant iterations. */ - if (d < tol) return (b + a) / 2.0; - c = b - Gb * (b - a) / (Gb - Ga); Gc = G(c); - a = b; b = c; Ga = Gb; Gb = Gc; - d = gmm::abs(b - a); - } -#endif - while (Ga * Gb > 0.0) { /* secant iterations. */ - if (d < tol) return (b + a) / 2.0; - c = b - Gb * (b - a) / (Gb - Ga); Gc = G(c); - a = b; b = c; Ga = Gb; Gb = Gc; - d = gmm::abs(b - a); - } - - c = std::max(a, b); a = std::min(a, b); b = c; - while (d > tol) { - c = b - (b - a) * (Gb / (Gb - Ga)); /* regula falsi. */ - if (c > b) c = b; if (c < a) c = a; - Gc = G(c); - if (Gc*Gb > 0) { b = c; Gb = Gc; } else { a = c; Ga = Gc; } - c = (b + a) / 2.0 ; Gc = G(c); /* Dichotomie. */ - if (Gc*Gb > 0) { b = c; Gb = Gc; } else { a = c; Ga = Gc; } - d = gmm::abs(b - a); c = (b + a) / 2.0; if ((c == a) || (c == b)) d = 0.0; - } - return (b + a) / 2.0; - } - -} - -#include "gmm_precond_diagonal.h" -#include "gmm_precond_ildlt.h" -#include "gmm_precond_ildltt.h" -#include "gmm_precond_mr_approx_inverse.h" -#include "gmm_precond_ilu.h" -#include "gmm_precond_ilut.h" -#include "gmm_precond_ilutp.h" - - - -#include "gmm_solver_cg.h" -#include "gmm_solver_bicgstab.h" -#include "gmm_solver_qmr.h" -#include "gmm_solver_constrained_cg.h" -#include "gmm_solver_Schwarz_additive.h" -#include "gmm_modified_gram_schmidt.h" -#include "gmm_tri_solve.h" -#include "gmm_solver_gmres.h" -#include "gmm_solver_bfgs.h" -#include "gmm_least_squares_cg.h" - -// #include "gmm_solver_idgmres.h" - - - -#endif // GMM_ITER_SOLVERS_H__ diff --git a/include/gmm/gmm_kernel.h b/include/gmm/gmm_kernel.h deleted file mode 100644 index 4ccc00e9854..00000000000 --- a/include/gmm/gmm_kernel.h +++ /dev/null @@ -1,53 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_kernel.h - @author Yves Renard - @date November 15, 2003. - @brief Include the base gmm files. - */ - -#ifndef GMM_KERNEL_H__ -#define GMM_KERNEL_H__ - -#include "gmm_def.h" -#include "gmm_blas.h" -#include "gmm_real_part.h" -#include "gmm_interface.h" -#include "gmm_sub_vector.h" -#include "gmm_sub_matrix.h" -#include "gmm_vector_to_matrix.h" -#include "gmm_vector.h" -#include "gmm_matrix.h" -#include "gmm_tri_solve.h" -#include "gmm_blas_interface.h" - - -#endif // GMM_KERNEL_H__ diff --git a/include/gmm/gmm_lapack_interface.h b/include/gmm/gmm_lapack_interface.h deleted file mode 100644 index bccd1ecd8df..00000000000 --- a/include/gmm/gmm_lapack_interface.h +++ /dev/null @@ -1,422 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_lapack_interface.h - @author Yves Renard - @date October 7, 2003. - @brief gmm interface for LAPACK -*/ - -#if defined(GMM_USES_LAPACK) || defined(GMM_USES_ATLAS) - -#ifndef GMM_LAPACK_INTERFACE_H -#define GMM_LAPACK_INTERFACE_H - -#include "gmm_blas_interface.h" -#include "gmm_dense_lu.h" -#include "gmm_dense_qr.h" - - -namespace gmm { - - /* ********************************************************************* */ - /* Operations interfaced for T = float, double, std::complex */ - /* or std::complex : */ - /* */ - /* lu_factor(dense_matrix, std::vector) */ - /* lu_solve(dense_matrix, std::vector, std::vector) */ - /* lu_solve(dense_matrix, std::vector, std::vector, */ - /* std::vector) */ - /* lu_solve_transposed(dense_matrix, std::vector, std::vector,*/ - /* std::vector) */ - /* lu_inverse(dense_matrix) */ - /* lu_inverse(dense_matrix, std::vector, dense_matrix) */ - /* */ - /* qr_factor(dense_matrix, dense_matrix, dense_matrix) */ - /* */ - /* implicit_qr_algorithm(dense_matrix, std::vector) */ - /* implicit_qr_algorithm(dense_matrix, std::vector, */ - /* dense_matrix) */ - /* implicit_qr_algorithm(dense_matrix, std::vector >) */ - /* implicit_qr_algorithm(dense_matrix, std::vector >, */ - /* dense_matrix) */ - /* */ - /* ********************************************************************* */ - - /* ********************************************************************* */ - /* LAPACK functions used. */ - /* ********************************************************************* */ - - extern "C" { - void sgetrf_(...); void dgetrf_(...); void cgetrf_(...); void zgetrf_(...); - void sgetrs_(...); void dgetrs_(...); void cgetrs_(...); void zgetrs_(...); - void sgetri_(...); void dgetri_(...); void cgetri_(...); void zgetri_(...); - void sgeqrf_(...); void dgeqrf_(...); void cgeqrf_(...); void zgeqrf_(...); - void sorgqr_(...); void dorgqr_(...); void cungqr_(...); void zungqr_(...); - void sormqr_(...); void dormqr_(...); void cunmqr_(...); void zunmqr_(...); - void sgees_ (...); void dgees_ (...); void cgees_ (...); void zgees_ (...); - void sgeev_ (...); void dgeev_ (...); void cgeev_ (...); void zgeev_ (...); - } - - /* ********************************************************************* */ - /* LU decomposition. */ - /* ********************************************************************* */ - -# define getrf_interface(lapack_name, base_type) inline \ - size_type lu_factor(dense_matrix &A, std::vector &ipvt){\ - GMMLAPACK_TRACE("getrf_interface"); \ - int m(mat_nrows(A)), n(mat_ncols(A)), lda(m), info(0); \ - if (m && n) lapack_name(&m, &n, &A(0,0), &lda, &ipvt[0], &info); \ - return size_type(info); \ - } - - getrf_interface(sgetrf_, BLAS_S) - getrf_interface(dgetrf_, BLAS_D) - getrf_interface(cgetrf_, BLAS_C) - getrf_interface(zgetrf_, BLAS_Z) - - /* ********************************************************************* */ - /* LU solve. */ - /* ********************************************************************* */ - -# define getrs_interface(f_name, trans1, lapack_name, base_type) inline \ - void f_name(const dense_matrix &A, \ - const std::vector &ipvt, std::vector &x, \ - const std::vector &b) { \ - GMMLAPACK_TRACE("getrs_interface"); \ - int n(mat_nrows(A)), info, nrhs(1); \ - gmm::copy(b, x); trans1; \ - if (n) \ - lapack_name(&t, &n, &nrhs, &(A(0,0)),&n,&ipvt[0], &x[0], &n, &info); \ - } - -# define getrs_trans_n const char t = 'N' -# define getrs_trans_t const char t = 'T' - - getrs_interface(lu_solve, getrs_trans_n, sgetrs_, BLAS_S) - getrs_interface(lu_solve, getrs_trans_n, dgetrs_, BLAS_D) - getrs_interface(lu_solve, getrs_trans_n, cgetrs_, BLAS_C) - getrs_interface(lu_solve, getrs_trans_n, zgetrs_, BLAS_Z) - getrs_interface(lu_solve_transposed, getrs_trans_t, sgetrs_, BLAS_S) - getrs_interface(lu_solve_transposed, getrs_trans_t, dgetrs_, BLAS_D) - getrs_interface(lu_solve_transposed, getrs_trans_t, cgetrs_, BLAS_C) - getrs_interface(lu_solve_transposed, getrs_trans_t, zgetrs_, BLAS_Z) - - /* ********************************************************************* */ - /* LU inverse. */ - /* ********************************************************************* */ - -# define getri_interface(lapack_name, base_type) inline \ - void lu_inverse(const dense_matrix &LU, \ - std::vector &ipvt, const dense_matrix &A_) { \ - GMMLAPACK_TRACE("getri_interface"); \ - dense_matrix& \ - A = const_cast &>(A_); \ - int n(mat_nrows(A)), info, lwork(-1); base_type work1; \ - if (n) { \ - gmm::copy(LU, A); \ - lapack_name(&n, &A(0,0), &n, &ipvt[0], &work1, &lwork, &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name(&n, &A(0,0), &n, &ipvt[0], &work[0], &lwork, &info); \ - } \ - } - - getri_interface(sgetri_, BLAS_S) - getri_interface(dgetri_, BLAS_D) - getri_interface(cgetri_, BLAS_C) - getri_interface(zgetri_, BLAS_Z) - - - /* ********************************************************************* */ - /* QR factorization. */ - /* ********************************************************************* */ - -# define geqrf_interface(lapack_name1, base_type) inline \ - void qr_factor(dense_matrix &A){ \ - GMMLAPACK_TRACE("geqrf_interface"); \ - int m(mat_nrows(A)), n(mat_ncols(A)), info, lwork(-1); base_type work1;\ - if (m && n) { \ - std::vector tau(n); \ - lapack_name1(&m, &n, &A(0,0), &m, &tau[0], &work1 , &lwork, &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name1(&m, &n, &A(0,0), &m, &tau[0], &work[0], &lwork, &info); \ - GMM_ASSERT1(!info, "QR factorization failed"); \ - } \ - } - - geqrf_interface(sgeqrf_, BLAS_S) - geqrf_interface(dgeqrf_, BLAS_D) - // For complex values, housholder vectors are not the same as in - // gmm::lu_factor. Impossible to interface for the moment. - // geqrf_interface(cgeqrf_, BLAS_C) - // geqrf_interface(zgeqrf_, BLAS_Z) - -# define geqrf_interface2(lapack_name1, lapack_name2, base_type) inline \ - void qr_factor(const dense_matrix &A, \ - dense_matrix &Q, dense_matrix &R) { \ - GMMLAPACK_TRACE("geqrf_interface2"); \ - int m(mat_nrows(A)), n(mat_ncols(A)), info, lwork(-1); base_type work1;\ - if (m && n) { \ - gmm::copy(A, Q); \ - std::vector tau(n); \ - lapack_name1(&m, &n, &Q(0,0), &m, &tau[0], &work1 , &lwork, &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name1(&m, &n, &Q(0,0), &m, &tau[0], &work[0], &lwork, &info); \ - GMM_ASSERT1(!info, "QR factorization failed"); \ - base_type *p = &R(0,0), *q = &Q(0,0); \ - for (int j = 0; j < n; ++j, q += m-n) \ - for (int i = 0; i < n; ++i, ++p, ++q) \ - *p = (j < i) ? base_type(0) : *q; \ - lapack_name2(&m, &n, &n, &Q(0,0), &m,&tau[0],&work[0],&lwork,&info); \ - } \ - else gmm::clear(Q); \ - } - - geqrf_interface2(sgeqrf_, sorgqr_, BLAS_S) - geqrf_interface2(dgeqrf_, dorgqr_, BLAS_D) - geqrf_interface2(cgeqrf_, cungqr_, BLAS_C) - geqrf_interface2(zgeqrf_, zungqr_, BLAS_Z) - - /* ********************************************************************* */ - /* QR algorithm for eigenvalues search. */ - /* ********************************************************************* */ - -# define gees_interface(lapack_name, base_type) \ - template inline void implicit_qr_algorithm( \ - const dense_matrix &A, const VECT &eigval_, \ - dense_matrix &Q, \ - double tol=gmm::default_tol(base_type()), bool compvect = true) { \ - GMMLAPACK_TRACE("gees_interface"); \ - typedef bool (*L_fp)(...); L_fp p = 0; \ - int n(mat_nrows(A)), info, lwork(-1), sdim; base_type work1; \ - if (!n) return; \ - dense_matrix H(n,n); gmm::copy(A, H); \ - char jobvs = (compvect ? 'V' : 'N'), sort = 'N'; \ - std::vector rwork(n), eigv1(n), eigv2(n); \ - lapack_name(&jobvs, &sort, p, &n, &H(0,0), &n, &sdim, &eigv1[0], \ - &eigv2[0], &Q(0,0), &n, &work1, &lwork, &rwork[0], &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name(&jobvs, &sort, p, &n, &H(0,0), &n, &sdim, &eigv1[0], \ - &eigv2[0], &Q(0,0), &n, &work[0], &lwork, &rwork[0],&info);\ - GMM_ASSERT1(!info, "QR algorithm failed"); \ - extract_eig(H, const_cast(eigval_), tol); \ - } - -# define gees_interface2(lapack_name, base_type) \ - template inline void implicit_qr_algorithm( \ - const dense_matrix &A, const VECT &eigval_, \ - dense_matrix &Q, \ - double tol=gmm::default_tol(base_type()), bool compvect = true) { \ - GMMLAPACK_TRACE("gees_interface2"); \ - typedef bool (*L_fp)(...); L_fp p = 0; \ - int n(mat_nrows(A)), info, lwork(-1), sdim; base_type work1; \ - if (!n) return; \ - dense_matrix H(n,n); gmm::copy(A, H); \ - char jobvs = (compvect ? 'V' : 'N'), sort = 'N'; \ - std::vector rwork(n), eigvv(n*2); \ - lapack_name(&jobvs, &sort, p, &n, &H(0,0), &n, &sdim, &eigvv[0], \ - &Q(0,0), &n, &work1, &lwork, &rwork[0], &rwork[0], &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name(&jobvs, &sort, p, &n, &H(0,0), &n, &sdim, &eigvv[0], \ - &Q(0,0), &n, &work[0], &lwork, &rwork[0], &rwork[0],&info);\ - GMM_ASSERT1(!info, "QR algorithm failed"); \ - extract_eig(H, const_cast(eigval_), tol); \ - } - - gees_interface(sgees_, BLAS_S) - gees_interface(dgees_, BLAS_D) - gees_interface2(cgees_, BLAS_C) - gees_interface2(zgees_, BLAS_Z) - -# define geev_int_right(lapack_name, base_type) \ - template inline void geev_interface_right( \ - const dense_matrix &A, const VECT &eigval_, \ - dense_matrix &Q) { \ - GMMLAPACK_TRACE("geev_interface"); \ - int n(mat_nrows(A)), info, lwork(-1); base_type work1; \ - if (!n) return; \ - dense_matrix H(n,n); gmm::copy(A, H); \ - char jobvl = 'N', jobvr = 'V'; \ - std::vector eigvr(n), eigvi(n); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigvr[0], &eigvi[0], \ - &Q(0,0), &n, &Q(0,0), &n, &work1, &lwork, &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigvr[0], &eigvi[0], \ - &Q(0,0), &n, &Q(0,0), &n, &work[0], &lwork, &info); \ - GMM_ASSERT1(!info, "QR algorithm failed"); \ - gmm::copy(eigvr, gmm::real_part(const_cast(eigval_))); \ - gmm::copy(eigvi, gmm::imag_part(const_cast(eigval_))); \ - } - -# define geev_int_rightc(lapack_name, base_type) \ - template inline void geev_interface_right( \ - const dense_matrix &A, const VECT &eigval_, \ - dense_matrix &Q) { \ - GMMLAPACK_TRACE("geev_interface"); \ - int n(mat_nrows(A)), info, lwork(-1); base_type work1; \ - if (!n) return; \ - dense_matrix H(n,n); gmm::copy(A, H); \ - char jobvl = 'N', jobvr = 'V'; \ - std::vector rwork(2*n); \ - std::vector eigv(n); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigv[0], &Q(0,0), &n, \ - &Q(0,0), &n, &work1, &lwork, &rwork[0], &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigv[0], &Q(0,0), &n, \ - &Q(0,0), &n, &work[0], &lwork, &rwork[0], &info); \ - GMM_ASSERT1(!info, "QR algorithm failed"); \ - gmm::copy(eigv, const_cast(eigval_)); \ - } - - geev_int_right(sgeev_, BLAS_S) - geev_int_right(dgeev_, BLAS_D) - geev_int_rightc(cgeev_, BLAS_C) - geev_int_rightc(zgeev_, BLAS_Z) - -# define geev_int_left(lapack_name, base_type) \ - template inline void geev_interface_left( \ - const dense_matrix &A, const VECT &eigval_, \ - dense_matrix &Q) { \ - GMMLAPACK_TRACE("geev_interface"); \ - int n(mat_nrows(A)), info, lwork(-1); base_type work1; \ - if (!n) return; \ - dense_matrix H(n,n); gmm::copy(A, H); \ - char jobvl = 'V', jobvr = 'N'; \ - std::vector eigvr(n), eigvi(n); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigvr[0], &eigvi[0], \ - &Q(0,0), &n, &Q(0,0), &n, &work1, &lwork, &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigvr[0], &eigvi[0], \ - &Q(0,0), &n, &Q(0,0), &n, &work[0], &lwork, &info); \ - GMM_ASSERT1(!info, "QR algorithm failed"); \ - gmm::copy(eigvr, gmm::real_part(const_cast(eigval_))); \ - gmm::copy(eigvi, gmm::imag_part(const_cast(eigval_))); \ - } - -# define geev_int_leftc(lapack_name, base_type) \ - template inline void geev_interface_left( \ - const dense_matrix &A, const VECT &eigval_, \ - dense_matrix &Q) { \ - GMMLAPACK_TRACE("geev_interface"); \ - int n(mat_nrows(A)), info, lwork(-1); base_type work1; \ - if (!n) return; \ - dense_matrix H(n,n); gmm::copy(A, H); \ - char jobvl = 'V', jobvr = 'N'; \ - std::vector rwork(2*n); \ - std::vector eigv(n); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigv[0], &Q(0,0), &n, \ - &Q(0,0), &n, &work1, &lwork, &rwork[0], &info); \ - lwork = int(gmm::real(work1)); \ - std::vector work(lwork); \ - lapack_name(&jobvl, &jobvr, &n, &H(0,0), &n, &eigv[0], &Q(0,0), &n, \ - &Q(0,0), &n, &work[0], &lwork, &rwork[0], &info); \ - GMM_ASSERT1(!info, "QR algorithm failed"); \ - gmm::copy(eigv, const_cast(eigval_)); \ - } - - geev_int_left(sgeev_, BLAS_S) - geev_int_left(dgeev_, BLAS_D) - geev_int_leftc(cgeev_, BLAS_C) - geev_int_leftc(zgeev_, BLAS_Z) - - - - /* ********************************************************************* */ - /* Interface to SVD. Does not correspond to a Gmm++ functionnality. */ - /* Author : Sebastian Nowozin */ - /* ********************************************************************* */ - - - extern "C" { - void sgesvd_(...); void dgesvd_(...); - } - -# define gesvd_interface(lapack_name, base_type) inline \ - void svd(dense_matrix &X, \ - dense_matrix &U, \ - dense_matrix &Vtransposed, \ - std::vector &sigma) { \ - GMMLAPACK_TRACE("gesvd_interface"); \ - int m(mat_nrows(X)), n(mat_ncols(X)); \ - int mn_min = m < n ? m : n; \ - sigma.resize(mn_min); \ - std::vector work(15 * mn_min); \ - int lwork(work.size()); \ - resize(U, m, n); \ - resize(Vtransposed, n, n); \ - char job = 'A'; \ - int info = -1; \ - lapack_name(&job, &job, &m, &n, &X(0,0), &m, &sigma[0], &U(0,0), \ - &m, &Vtransposed(0,0), &n, &work[0], &lwork, &info); \ - } - -# define cgesvd_interface(lapack_name, base_type, base_type2) inline \ - void svd(dense_matrix &X, \ - dense_matrix &U, \ - dense_matrix &Vtransposed, \ - std::vector &sigma) { \ - GMMLAPACK_TRACE("gesvd_interface"); \ - int m(mat_nrows(X)), n(mat_ncols(X)); \ - int mn_min = m < n ? m : n; \ - sigma.resize(mn_min); \ - std::vector work(15 * mn_min); \ - std::vector rwork(5 * mn_min); \ - int lwork(work.size()); \ - resize(U, m, n); \ - resize(Vtransposed, n, n); \ - char job = 'A'; \ - int info = -1; \ - lapack_name(&job, &job, &m, &n, &X(0,0), &m, &sigma[0], &U(0,0), \ - &m, &Vtransposed(0,0), &n, &work[0], &lwork, \ - &rwork[0], &info); \ - } - - gesvd_interface(sgesvd_, BLAS_S) - gesvd_interface(dgesvd_, BLAS_D) - cgesvd_interface(cgesvd_, BLAS_C, BLAS_S) - cgesvd_interface(zgesvd_, BLAS_Z, BLAS_D) - - - - - -} - -#endif // GMM_LAPACK_INTERFACE_H - -#endif // GMM_USES_LAPACK || GMM_USES_ATLAS diff --git a/include/gmm/gmm_least_squares_cg.h b/include/gmm/gmm_least_squares_cg.h deleted file mode 100644 index f21c05a42f5..00000000000 --- a/include/gmm/gmm_least_squares_cg.h +++ /dev/null @@ -1,95 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_leastsquares_cg.h - @author Benjamin Schleimer - @date January 23, 2007. - @brief Conjugate gradient least squares algorithm. - Algorithm taken from http://www.stat.washington.edu/wxs/Stat538-w05/Notes/conjugate-gradients.pdf page 6 -*/ -#ifndef GMM_LEAST_SQUARES_CG_H__ -#define GMM_LEAST_SQUARES_CG_H__ - -#include "gmm_kernel.h" -#include "gmm_iter.h" -#include "gmm_conjugated.h" - -namespace gmm { - - template - void least_squares_cg(const Matrix& C, Vector1& x, const Vector2& y, - iteration &iter) { - - typedef typename temporary_dense_vector::vector_type temp_vector; - typedef typename linalg_traits::value_type T; - - T rho, rho_1(0), a; - temp_vector p(vect_size(x)), q(vect_size(y)), g(vect_size(x)); - temp_vector r(vect_size(y)); - iter.set_rhsnorm(gmm::sqrt(gmm::abs(vect_hp(y, y)))); - - if (iter.get_rhsnorm() == 0.0) - clear(x); - else { - mult(C, scaled(x, T(-1)), y, r); - mult(conjugated(C), r, g); - rho = vect_hp(g, g); - copy(g, p); - - while (!iter.finished_vect(g)) { - - if (!iter.first()) { - rho = vect_hp(g, g); - add(g, scaled(p, rho / rho_1), p); - } - - mult(C, p, q); - - a = rho / vect_hp(q, q); - add(scaled(p, a), x); - add(scaled(q, -a), r); - // NOTE: how do we minimize the impact to the transpose? - mult(conjugated(C), r, g); - rho_1 = rho; - - ++iter; - } - } - } - - template inline - void least_squares_cg(const Matrix& C, const Vector1& x, const Vector2& y, - iteration &iter) - { least_squares_cg(C, linalg_const_cast(x), y, iter); } -} - - -#endif // GMM_SOLVER_CG_H__ diff --git a/include/gmm/gmm_matrix.h b/include/gmm/gmm_matrix.h deleted file mode 100644 index 77050b3cff9..00000000000 --- a/include/gmm/gmm_matrix.h +++ /dev/null @@ -1,1200 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/** @file gmm_matrix.h - @author Yves Renard - @date October 13, 2002. - @brief Declaration of some matrix types (gmm::dense_matrix, - gmm::row_matrix, gmm::col_matrix, gmm::csc_matrix, etc.) -*/ - -#ifndef GMM_MATRIX_H__ -#define GMM_MATRIX_H__ - -#include "gmm_vector.h" -#include "gmm_sub_vector.h" -#include "gmm_sub_matrix.h" -#include "gmm_transposed.h" - -namespace gmm -{ - - /* ******************************************************************** */ - /* */ - /* Identity matrix */ - /* */ - /* ******************************************************************** */ - - struct identity_matrix { - template void build_with(const MAT &) {} - }; - - template inline - void add(const identity_matrix&, M &v1) { - size_type n = std::min(gmm::mat_nrows(v1), gmm::mat_ncols(v1)); - for (size_type i = 0; i < n; ++i) - v1(i,i) += typename linalg_traits::value_type(1); - } - template inline - void add(const identity_matrix &I, const M &v1) - { add(I, linalg_const_cast(v1)); } - - template inline - void mult(const identity_matrix&, const V1 &v1, V2 &v2) - { copy(v1, v2); } - template inline - void mult(const identity_matrix&, const V1 &v1, const V2 &v2) - { copy(v1, v2); } - template inline - void mult(const identity_matrix&, const V1 &v1, const V2 &v2, V3 &v3) - { add(v1, v2, v3); } - template inline - void mult(const identity_matrix&, const V1 &v1, const V2 &v2, const V3 &v3) - { add(v1, v2, v3); } - template inline - void left_mult(const identity_matrix&, const V1 &v1, V2 &v2) - { copy(v1, v2); } - template inline - void left_mult(const identity_matrix&, const V1 &v1, const V2 &v2) - { copy(v1, v2); } - template inline - void right_mult(const identity_matrix&, const V1 &v1, V2 &v2) - { copy(v1, v2); } - template inline - void right_mult(const identity_matrix&, const V1 &v1, const V2 &v2) - { copy(v1, v2); } - template inline - void transposed_left_mult(const identity_matrix&, const V1 &v1, V2 &v2) - { copy(v1, v2); } - template inline - void transposed_left_mult(const identity_matrix&, const V1 &v1,const V2 &v2) - { copy(v1, v2); } - template inline - void transposed_right_mult(const identity_matrix&, const V1 &v1, V2 &v2) - { copy(v1, v2); } - template inline - void transposed_right_mult(const identity_matrix&,const V1 &v1,const V2 &v2) - { copy(v1, v2); } - template void copy_ident(const identity_matrix&, M &m) { - size_type i = 0, n = std::min(mat_nrows(m), mat_ncols(m)); - clear(m); - for (; i < n; ++i) m(i,i) = typename linalg_traits::value_type(1); - } - template inline void copy(const identity_matrix&, M &m) - { copy_ident(identity_matrix(), m); } - template inline void copy(const identity_matrix &, const M &m) - { copy_ident(identity_matrix(), linalg_const_cast(m)); } - template inline - typename linalg_traits::value_type - vect_sp(const identity_matrix &, const V1 &v1, const V2 &v2) - { return vect_sp(v1, v2); } - template inline - typename linalg_traits::value_type - vect_hp(const identity_matrix &, const V1 &v1, const V2 &v2) - { return vect_hp(v1, v2); } - template inline bool is_identity(const M&) { return false; } - inline bool is_identity(const identity_matrix&) { return true; } - - /* ******************************************************************** */ - /* */ - /* Row matrix */ - /* */ - /* ******************************************************************** */ - - template class row_matrix { - protected : - std::vector li; /* array of rows. */ - size_type nc; - - public : - - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::value_type value_type; - - row_matrix(size_type r, size_type c) : li(r, V(c)), nc(c) {} - row_matrix(void) : nc(0) {} - reference operator ()(size_type l, size_type c) - { return li[l][c]; } - value_type operator ()(size_type l, size_type c) const - { return li[l][c]; } - - void clear_mat(); - void resize(size_type m, size_type n); - - typename std::vector::iterator begin(void) - { return li.begin(); } - typename std::vector::iterator end(void) - { return li.end(); } - typename std::vector::const_iterator begin(void) const - { return li.begin(); } - typename std::vector::const_iterator end(void) const - { return li.end(); } - - - V& row(size_type i) { return li[i]; } - const V& row(size_type i) const { return li[i]; } - V& operator[](size_type i) { return li[i]; } - const V& operator[](size_type i) const { return li[i]; } - - inline size_type nrows(void) const { return li.size(); } - inline size_type ncols(void) const { return nc; } - - void swap(row_matrix &m) { std::swap(li, m.li); std::swap(nc, m.nc); } - void swap_row(size_type i, size_type j) { std::swap(li[i], li[j]); } - }; - - template void row_matrix::resize(size_type m, size_type n) { - size_type nr = std::min(nrows(), m); - li.resize(m); - for (size_type i=nr; i < m; ++i) gmm::resize(li[i], n); - if (n != nc) { - for (size_type i=0; i < nr; ++i) gmm::resize(li[i], n); - nc = n; - } - } - - - template void row_matrix::clear_mat() - { for (size_type i=0; i < nrows(); ++i) clear(li[i]); } - - template struct linalg_traits > { - typedef row_matrix this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::storage_type storage_type; - typedef simple_vector_ref sub_row_type; - typedef simple_vector_ref const_sub_row_type; - typedef typename std::vector::iterator row_iterator; - typedef typename std::vector::const_iterator const_row_iterator; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_col_iterator; - typedef row_major sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static row_iterator row_begin(this_type &m) { return m.begin(); } - static row_iterator row_end(this_type &m) { return m.end(); } - static const_row_iterator row_begin(const this_type &m) - { return m.begin(); } - static const_row_iterator row_end(const this_type &m) - { return m.end(); } - static const_sub_row_type row(const const_row_iterator &it) - { return const_sub_row_type(*it); } - static sub_row_type row(const row_iterator &it) - { return sub_row_type(*it); } - static origin_type* origin(this_type &m) { return &m; } - static const origin_type* origin(const this_type &m) { return &m; } - static void do_clear(this_type &m) { m.clear_mat(); } - static value_type access(const const_row_iterator &itrow, size_type j) - { return (*itrow)[j]; } - static reference access(const row_iterator &itrow, size_type j) - { return (*itrow)[j]; } - static void resize(this_type &v, size_type m, size_type n) - { v.resize(m, n); } - static void reshape(this_type &, size_type, size_type) - { GMM_ASSERT1(false, "Sorry, to be done"); } - }; - - template std::ostream &operator << - (std::ostream &o, const row_matrix& m) { gmm::write(o,m); return o; } - - /* ******************************************************************** */ - /* */ - /* Column matrix */ - /* */ - /* ******************************************************************** */ - - template class col_matrix { - protected : - std::vector li; /* array of columns. */ - size_type nr; - - public : - - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::value_type value_type; - - col_matrix(size_type r, size_type c) : li(c, V(r)), nr(r) { } - col_matrix(void) : nr(0) {} - reference operator ()(size_type l, size_type c) - { return li[c][l]; } - value_type operator ()(size_type l, size_type c) const - { return li[c][l]; } - - void clear_mat(); - void resize(size_type, size_type); - - V& col(size_type i) { return li[i]; } - const V& col(size_type i) const { return li[i]; } - V& operator[](size_type i) { return li[i]; } - const V& operator[](size_type i) const { return li[i]; } - - typename std::vector::iterator begin(void) - { return li.begin(); } - typename std::vector::iterator end(void) - { return li.end(); } - typename std::vector::const_iterator begin(void) const - { return li.begin(); } - typename std::vector::const_iterator end(void) const - { return li.end(); } - - inline size_type ncols(void) const { return li.size(); } - inline size_type nrows(void) const { return nr; } - - void swap(col_matrix &m) { std::swap(li, m.li); std::swap(nr, m.nr); } - void swap_col(size_type i, size_type j) { std::swap(li[i], li[j]); } - }; - - template void col_matrix::resize(size_type m, size_type n) { - size_type nc = std::min(ncols(), n); - li.resize(n); - for (size_type i=nc; i < n; ++i) gmm::resize(li[i], m); - if (m != nr) { - for (size_type i=0; i < nc; ++i) gmm::resize(li[i], m); - nr = m; - } - } - - template void col_matrix::clear_mat() - { for (size_type i=0; i < ncols(); ++i) clear(li[i]); } - - template struct linalg_traits > { - typedef col_matrix this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::storage_type storage_type; - typedef simple_vector_ref sub_col_type; - typedef simple_vector_ref const_sub_col_type; - typedef typename std::vector::iterator col_iterator; - typedef typename std::vector::const_iterator const_col_iterator; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_row_iterator; - typedef col_major sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static col_iterator col_begin(this_type &m) { return m.begin(); } - static col_iterator col_end(this_type &m) { return m.end(); } - static const_col_iterator col_begin(const this_type &m) - { return m.begin(); } - static const_col_iterator col_end(const this_type &m) - { return m.end(); } - static const_sub_col_type col(const const_col_iterator &it) - { return const_sub_col_type(*it); } - static sub_col_type col(const col_iterator &it) - { return sub_col_type(*it); } - static origin_type* origin(this_type &m) { return &m; } - static const origin_type* origin(const this_type &m) { return &m; } - static void do_clear(this_type &m) { m.clear_mat(); } - static value_type access(const const_col_iterator &itcol, size_type j) - { return (*itcol)[j]; } - static reference access(const col_iterator &itcol, size_type j) - { return (*itcol)[j]; } - static void resize(this_type &v, size_type m, size_type n) - { v.resize(m,n); } - static void reshape(this_type &, size_type, size_type) - { GMM_ASSERT1(false, "Sorry, to be done"); } - }; - - template std::ostream &operator << - (std::ostream &o, const col_matrix& m) { gmm::write(o,m); return o; } - - /* ******************************************************************** */ - /* */ - /* Dense matrix */ - /* */ - /* ******************************************************************** */ - - template class dense_matrix : public std::vector { - public: - typedef typename std::vector::size_type size_type; - typedef typename std::vector::iterator iterator; - typedef typename std::vector::const_iterator const_iterator; - - protected: - size_type nbc, nbl; - - public: - - inline const T& operator ()(size_type l, size_type c) const { - GMM_ASSERT2(l < nbl && c < nbc, "out of range"); - return *(this->begin() + c*nbl+l); - } - inline T& operator ()(size_type l, size_type c) { - GMM_ASSERT2(l < nbl && c < nbc, "out of range"); - return *(this->begin() + c*nbl+l); - } - - void resize(size_type, size_type); - void reshape(size_type, size_type); - - void fill(T a, T b = T(0)); - inline size_type nrows(void) const { return nbl; } - inline size_type ncols(void) const { return nbc; } - void swap(dense_matrix &m) - { std::vector::swap(m); std::swap(nbc, m.nbc); std::swap(nbl, m.nbl); } - - dense_matrix(size_type l, size_type c) - : std::vector(c*l), nbc(c), nbl(l) {} - dense_matrix(void) { nbl = nbc = 0; } - }; - - template void dense_matrix::reshape(size_type m,size_type n) { - GMM_ASSERT2(n*m == nbl*nbc, "dimensions mismatch"); - nbl = m; nbc = n; - } - - template void dense_matrix::resize(size_type m, size_type n) { - if (n*m > nbc*nbl) std::vector::resize(n*m); - if (m < nbl) { - for (size_type i = 1; i < std::min(nbc, n); ++i) - std::copy(this->begin()+i*nbl, this->begin()+(i*nbl+m), - this->begin()+i*m); - for (size_type i = std::min(nbc, n); i < n; ++i) - std::fill(this->begin()+(i*m), this->begin()+(i+1)*m, T(0)); - } - else if (m > nbl) { /* do nothing when the nb of rows does not change */ - for (size_type i = std::min(nbc, n); i > 1; --i) - std::copy(this->begin()+(i-1)*nbl, this->begin()+i*nbl, - this->begin()+(i-1)*m); - for (size_type i = 0; i < std::min(nbc, n); ++i) - std::fill(this->begin()+(i*m+nbl), this->begin()+(i+1)*m, T(0)); - } - if (n*m < nbc*nbl) std::vector::resize(n*m); - nbl = m; nbc = n; - } - - template void dense_matrix::fill(T a, T b) { - std::fill(this->begin(), this->end(), b); - size_type n = std::min(nbl, nbc); - if (a != b) for (size_type i = 0; i < n; ++i) (*this)(i,i) = a; - } - - template struct linalg_traits > { - typedef dense_matrix this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_matrix linalg_type; - typedef T value_type; - typedef T& reference; - typedef abstract_dense storage_type; - typedef tab_ref_reg_spaced_with_origin sub_row_type; - typedef tab_ref_reg_spaced_with_origin const_sub_row_type; - typedef dense_compressed_iterator row_iterator; - typedef dense_compressed_iterator const_row_iterator; - typedef tab_ref_with_origin sub_col_type; - typedef tab_ref_with_origin const_sub_col_type; - typedef dense_compressed_iterator col_iterator; - typedef dense_compressed_iterator const_col_iterator; - typedef col_and_row sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_sub_row_type row(const const_row_iterator &it) - { return const_sub_row_type(*it, it.nrows, it.ncols, it.origin); } - static const_sub_col_type col(const const_col_iterator &it) - { return const_sub_col_type(*it, *it + it.nrows, it.origin); } - static sub_row_type row(const row_iterator &it) - { return sub_row_type(*it, it.nrows, it.ncols, it.origin); } - static sub_col_type col(const col_iterator &it) - { return sub_col_type(*it, *it + it.nrows, it.origin); } - static row_iterator row_begin(this_type &m) - { return row_iterator(m.begin(), m.size() ? 1 : 0, m.nrows(), m.ncols(), 0, &m); } - static row_iterator row_end(this_type &m) - { return row_iterator(m.begin(), m.size() ? 1 : 0, m.nrows(), m.ncols(), m.nrows(), &m); } - static const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m.begin(), m.size() ? 1 : 0, m.nrows(), m.ncols(), 0, &m); } - static const_row_iterator row_end(const this_type &m) - { return const_row_iterator(m.begin(), m.size() ? 1 : 0, m.nrows(), m.ncols(), m.nrows(), &m); } - static col_iterator col_begin(this_type &m) - { return col_iterator(m.begin(), m.nrows(), m.nrows(), m.ncols(), 0, &m); } - static col_iterator col_end(this_type &m) - { return col_iterator(m.begin(), m.nrows(), m.nrows(), m.ncols(), m.ncols(), &m); } - static const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m.begin(), m.nrows(), m.nrows(), m.ncols(), 0, &m); } - static const_col_iterator col_end(const this_type &m) - { return const_col_iterator(m.begin(),m.nrows(),m.nrows(),m.ncols(),m.ncols(), &m); } - static origin_type* origin(this_type &m) { return &m; } - static const origin_type* origin(const this_type &m) { return &m; } - static void do_clear(this_type &m) { m.fill(value_type(0)); } - static value_type access(const const_col_iterator &itcol, size_type j) - { return (*itcol)[j]; } - static reference access(const col_iterator &itcol, size_type j) - { return (*itcol)[j]; } - static void resize(this_type &v, size_type m, size_type n) - { v.resize(m,n); } - static void reshape(this_type &v, size_type m, size_type n) - { v.reshape(m, n); } - }; - - template std::ostream &operator << - (std::ostream &o, const dense_matrix& m) { gmm::write(o,m); return o; } - - /* ******************************************************************** */ - /* */ - /* Read only compressed sparse column matrix */ - /* */ - /* ******************************************************************** */ - - template - struct csc_matrix { - typedef unsigned int IND_TYPE; - - T *pr; // values. - IND_TYPE *ir; // row indices. - IND_TYPE *jc; // column repartition on pr and ir. - size_type nc, nr; - - typedef T value_type; - typedef T& access_type; - - template void init_with_good_format(const Matrix &B); - template void init_with(const Matrix &A); - void init_with(const col_matrix > &B) - { init_with_good_format(B); } - void init_with(const col_matrix > &B) - { init_with_good_format(B); } - template - void init_with(const csc_matrix_ref& B) - { init_with_good_format(B); } - template - void init_with(const csc_matrix& B) - { init_with_good_format(B); } - - void init_with_identity(size_type n); - - csc_matrix(void) : pr(0), ir(0), jc(0), nc(0), nr(0) {} - csc_matrix(size_type nnr, size_type nnc); - ~csc_matrix() { if (pr) { delete[] pr; delete[] ir; delete[] jc; } } - - size_type nrows(void) const { return nr; } - size_type ncols(void) const { return nc; } - void swap(csc_matrix &m) { - std::swap(pr, m.pr); - std::swap(ir,m.ir); std::swap(jc, m.jc); - std::swap(nc, m.nc); std::swap(nr,m.nr); - } - value_type operator()(size_type i, size_type j) const - { return mat_col(*this, j)[i]; } - }; - - template template - void csc_matrix::init_with_good_format(const Matrix &B) { - typedef typename linalg_traits::const_sub_col_type col_type; - if (pr) { delete[] pr; delete[] ir; delete[] jc; } - nc = mat_ncols(B); nr = mat_nrows(B); - jc = new IND_TYPE[nc+1]; - jc[0] = shift; - for (size_type j = 0; j < nc; ++j) { - jc[j+1] = IND_TYPE(jc[j] + nnz(mat_const_col(B, j))); - } - pr = new T[jc[nc]]; - ir = new IND_TYPE[jc[nc]]; - for (size_type j = 0; j < nc; ++j) { - col_type col = mat_const_col(B, j); - typename linalg_traits::const_iterator - it = vect_const_begin(col), ite = vect_const_end(col); - for (size_type k = 0; it != ite; ++it, ++k) { - pr[jc[j]-shift+k] = *it; - ir[jc[j]-shift+k] = IND_TYPE(it.index() + shift); - } - } - } - - template template - void csc_matrix::init_with(const Matrix &A) { - col_matrix > B(mat_nrows(A), mat_ncols(A)); - copy(A, B); - init_with_good_format(B); - } - - template - void csc_matrix::init_with_identity(size_type n) { - if (pr) { delete[] pr; delete[] ir; delete[] jc; } - nc = nr = n; - pr = new T[nc]; - ir = new IND_TYPE[nc]; - jc = new IND_TYPE[nc+1]; - for (size_type j = 0; j < nc; ++j) - { ir[j] = jc[j] = shift + j; pr[j] = T(1); } - jc[nc] = shift + nc; - } - - template - csc_matrix::csc_matrix(size_type nnr, size_type nnc) - : nc(nnc), nr(nnr) { - pr = new T[1]; ir = new IND_TYPE[1]; - jc = new IND_TYPE[nc+1]; - for (size_type j = 0; j <= nc; ++j) jc[j] = shift; - } - - template - struct linalg_traits > { - typedef csc_matrix this_type; - typedef typename this_type::IND_TYPE IND_TYPE; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef T value_type; - typedef T origin_type; - typedef T reference; - typedef abstract_sparse storage_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_row_iterator; - typedef abstract_null_type sub_col_type; - typedef cs_vector_ref - const_sub_col_type; - typedef sparse_compressed_iterator - const_col_iterator; - typedef abstract_null_type col_iterator; - typedef col_major sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m.pr, m.ir, m.jc, m.nr, m.pr); } - static const_col_iterator col_end(const this_type &m) - { return const_col_iterator(m.pr, m.ir, m.jc + m.nc, m.nr, m.pr); } - static const_sub_col_type col(const const_col_iterator &it) { - return const_sub_col_type(it.pr + *(it.jc) - shift, - it.ir + *(it.jc) - shift, - *(it.jc + 1) - *(it.jc), it.n); - } - static const origin_type* origin(const this_type &m) { return m.pr; } - static void do_clear(this_type &m) { m.do_clear(); } - static value_type access(const const_col_iterator &itcol, size_type j) - { return col(itcol)[j]; } - }; - - template - std::ostream &operator << - (std::ostream &o, const csc_matrix& m) - { gmm::write(o,m); return o; } - - template - inline void copy(const identity_matrix &, csc_matrix& M) - { M.init_with_identity(mat_nrows(M)); } - - template - inline void copy(const Matrix &A, csc_matrix& M) - { M.init_with(A); } - - /* ******************************************************************** */ - /* */ - /* Read only compressed sparse row matrix */ - /* */ - /* ******************************************************************** */ - - template - struct csr_matrix { - - typedef unsigned int IND_TYPE; - - T *pr; // values. - IND_TYPE *ir; // col indices. - IND_TYPE *jc; // row repartition on pr and ir. - size_type nc, nr; - - typedef T value_type; - typedef T& access_type; - - - template void init_with_good_format(const Matrix &B); - void init_with(const row_matrix > &B) - { init_with_good_format(B); } - void init_with(const row_matrix > &B) - { init_with_good_format(B); } - template - void init_with(const csr_matrix_ref& B) - { init_with_good_format(B); } - template - void init_with(const csr_matrix& B) - { init_with_good_format(B); } - - template void init_with(const Matrix &A); - void init_with_identity(size_type n); - - csr_matrix(void) : pr(0), ir(0), jc(0), nc(0), nr(0) {} - csr_matrix(size_type nnr, size_type nnc); - ~csr_matrix() { if (pr) { delete[] pr; delete[] ir; delete[] jc; } } - - size_type nrows(void) const { return nr; } - size_type ncols(void) const { return nc; } - void swap(csr_matrix &m) { - std::swap(pr, m.pr); - std::swap(ir,m.ir); std::swap(jc, m.jc); - std::swap(nc, m.nc); std::swap(nr,m.nr); - } - - value_type operator()(size_type i, size_type j) const - { return mat_row(*this, i)[j]; } - }; - - template template - void csr_matrix::init_with_good_format(const Matrix &B) { - typedef typename linalg_traits::const_sub_row_type row_type; - if (pr) { delete[] pr; delete[] ir; delete[] jc; } - nc = mat_ncols(B); nr = mat_nrows(B); - jc = new IND_TYPE[nr+1]; - jc[0] = shift; - for (size_type j = 0; j < nr; ++j) { - jc[j+1] = IND_TYPE(jc[j] + nnz(mat_const_row(B, j))); - } - pr = new T[jc[nr]]; - ir = new IND_TYPE[jc[nr]]; - for (size_type j = 0; j < nr; ++j) { - row_type row = mat_const_row(B, j); - typename linalg_traits::const_iterator - it = vect_const_begin(row), ite = vect_const_end(row); - for (size_type k = 0; it != ite; ++it, ++k) { - pr[jc[j]-shift+k] = *it; - ir[jc[j]-shift+k] = IND_TYPE(it.index()+shift); - } - } - } - - template template - void csr_matrix::init_with(const Matrix &A) { - row_matrix > B(mat_nrows(A), mat_ncols(A)); - copy(A, B); - init_with_good_format(B); - } - - template - void csr_matrix::init_with_identity(size_type n) { - if (pr) { delete[] pr; delete[] ir; delete[] jc; } - nc = nr = n; - pr = new T[nr]; - ir = new IND_TYPE[nr]; - jc = new IND_TYPE[nr+1]; - for (size_type j = 0; j < nr; ++j) - { ir[j] = jc[j] = shift + j; pr[j] = T(1); } - jc[nr] = shift + nr; - } - - template - csr_matrix::csr_matrix(size_type nnr, size_type nnc) - : nc(nnc), nr(nnr) { - pr = new T[1]; ir = new IND_TYPE[1]; - jc = new IND_TYPE[nr+1]; - for (size_type j = 0; j < nr; ++j) jc[j] = shift; - jc[nr] = shift; - } - - - template - struct linalg_traits > { - typedef csr_matrix this_type; - typedef typename this_type::IND_TYPE IND_TYPE; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef T value_type; - typedef T origin_type; - typedef T reference; - typedef abstract_sparse storage_type; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_col_iterator; - typedef abstract_null_type sub_row_type; - typedef cs_vector_ref - const_sub_row_type; - typedef sparse_compressed_iterator - const_row_iterator; - typedef abstract_null_type row_iterator; - typedef row_major sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m.pr, m.ir, m.jc, m.nc, m.pr); } - static const_row_iterator row_end(const this_type &m) - { return const_row_iterator(m.pr, m.ir, m.jc + m.nr, m.nc, m.pr); } - static const_sub_row_type row(const const_row_iterator &it) { - return const_sub_row_type(it.pr + *(it.jc) - shift, - it.ir + *(it.jc) - shift, - *(it.jc + 1) - *(it.jc), it.n); - } - static const origin_type* origin(const this_type &m) { return m.pr; } - static void do_clear(this_type &m) { m.do_clear(); } - static value_type access(const const_row_iterator &itrow, size_type j) - { return row(itrow)[j]; } - }; - - template - std::ostream &operator << - (std::ostream &o, const csr_matrix& m) - { gmm::write(o,m); return o; } - - template - inline void copy(const identity_matrix &, csr_matrix& M) - { M.init_with_identity(mat_nrows(M)); } - - template - inline void copy(const Matrix &A, csr_matrix& M) - { M.init_with(A); } - - /* ******************************************************************** */ - /* */ - /* Block matrix */ - /* */ - /* ******************************************************************** */ - - template class block_matrix { - protected : - std::vector blocks; - size_type nrowblocks_; - size_type ncolblocks_; - std::vector introw, intcol; - - public : - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::reference reference; - - size_type nrows(void) const { return introw[nrowblocks_-1].max; } - size_type ncols(void) const { return intcol[ncolblocks_-1].max; } - size_type nrowblocks(void) const { return nrowblocks_; } - size_type ncolblocks(void) const { return ncolblocks_; } - const sub_interval &subrowinterval(size_type i) const { return introw[i]; } - const sub_interval &subcolinterval(size_type i) const { return intcol[i]; } - const MAT &block(size_type i, size_type j) const - { return blocks[j*ncolblocks_+i]; } - MAT &block(size_type i, size_type j) - { return blocks[j*ncolblocks_+i]; } - void do_clear(void); - // to be done : read and write access to a component - value_type operator() (size_type i, size_type j) const { - size_type k, l; - for (k = 0; k < nrowblocks_; ++k) - if (i >= introw[k].min && i < introw[k].max) break; - for (l = 0; l < nrowblocks_; ++l) - if (j >= introw[l].min && j < introw[l].max) break; - return (block(k, l))(i - introw[k].min, j - introw[l].min); - } - reference operator() (size_type i, size_type j) { - size_type k, l; - for (k = 0; k < nrowblocks_; ++k) - if (i >= introw[k].min && i < introw[k].max) break; - for (l = 0; l < nrowblocks_; ++l) - if (j >= introw[l].min && j < introw[l].max) break; - return (block(k, l))(i - introw[k].min, j - introw[l].min); - } - - template void resize(const CONT &c1, const CONT &c2); - template block_matrix(const CONT &c1, const CONT &c2) - { resize(c1, c2); } - block_matrix(void) {} - - }; - - template struct linalg_traits > { - typedef block_matrix this_type; - typedef linalg_false is_reference; - typedef abstract_matrix linalg_type; - typedef this_type origin_type; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::storage_type storage_type; - typedef abstract_null_type sub_row_type; // to be done ... - typedef abstract_null_type const_sub_row_type; // to be done ... - typedef abstract_null_type row_iterator; // to be done ... - typedef abstract_null_type const_row_iterator; // to be done ... - typedef abstract_null_type sub_col_type; // to be done ... - typedef abstract_null_type const_sub_col_type; // to be done ... - typedef abstract_null_type col_iterator; // to be done ... - typedef abstract_null_type const_col_iterator; // to be done ... - typedef abstract_null_type sub_orientation; // to be done ... - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static origin_type* origin(this_type &m) { return &m; } - static const origin_type* origin(const this_type &m) { return &m; } - static void do_clear(this_type &m) { m.do_clear(); } - // access to be done ... - static void resize(this_type &, size_type , size_type) - { GMM_ASSERT1(false, "Sorry, to be done"); } - static void reshape(this_type &, size_type , size_type) - { GMM_ASSERT1(false, "Sorry, to be done"); } - }; - - template void block_matrix::do_clear(void) { - for (size_type j = 0, l = 0; j < ncolblocks_; ++j) - for (size_type i = 0, k = 0; i < nrowblocks_; ++i) - clear(block(i,j)); - } - - template template - void block_matrix::resize(const CONT &c1, const CONT &c2) { - nrowblocks_ = c1.size(); ncolblocks_ = c2.size(); - blocks.resize(nrowblocks_ * ncolblocks_); - intcol.resize(ncolblocks_); - introw.resize(nrowblocks_); - for (size_type j = 0, l = 0; j < ncolblocks_; ++j) { - intcol[j] = sub_interval(l, c2[j]); l += c2[j]; - for (size_type i = 0, k = 0; i < nrowblocks_; ++i) { - if (j == 0) { introw[i] = sub_interval(k, c1[i]); k += c1[i]; } - block(i, j) = MAT(c1[i], c2[j]); - } - } - } - - template - void copy(const block_matrix &m1, M2 &m2) { - for (size_type j = 0; j < m1.ncolblocks(); ++j) - for (size_type i = 0; i < m1.nrowblocks(); ++i) - copy(m1.block(i,j), sub_matrix(m2, m1.subrowinterval(i), - m1.subcolinterval(j))); - } - - template - void copy(const block_matrix &m1, const M2 &m2) - { copy(m1, linalg_const_cast(m2)); } - - - template - void mult(const block_matrix &m, const V1 &v1, V2 &v2) { - clear(v2); - typename sub_vector_type::vector_type sv; - for (size_type i = 0; i < m.nrowblocks() ; ++i) - for (size_type j = 0; j < m.ncolblocks() ; ++j) { - sv = sub_vector(v2, m.subrowinterval(i)); - mult(m.block(i,j), - sub_vector(v1, m.subcolinterval(j)), sv, sv); - } - } - - template - void mult(const block_matrix &m, const V1 &v1, const V2 &v2, V3 &v3) { - typename sub_vector_type::vector_type sv; - for (size_type i = 0; i < m.nrowblocks() ; ++i) - for (size_type j = 0; j < m.ncolblocks() ; ++j) { - sv = sub_vector(v3, m.subrowinterval(i)); - if (j == 0) - mult(m.block(i,j), - sub_vector(v1, m.subcolinterval(j)), - sub_vector(v2, m.subrowinterval(i)), sv); - else - mult(m.block(i,j), - sub_vector(v1, m.subcolinterval(j)), sv, sv); - } - - } - - template - void mult(const block_matrix &m, const V1 &v1, const V2 &v2) - { mult(m, v1, linalg_const_cast(v2)); } - - template - void mult(const block_matrix &m, const V1 &v1, const V2 &v2, - const V3 &v3) - { mult_const(m, v1, v2, linalg_const_cast(v3)); } - -} - /* ******************************************************************** */ - /* */ - /* Distributed matrices */ - /* */ - /* ******************************************************************** */ - -#ifdef GMM_USES_MPI -#include - -namespace gmm { - - template inline MPI_Datatype mpi_type(T) - { GMM_ASSERT1(false, "Sorry unsupported type"); return MPI_FLOAT; } - inline MPI_Datatype mpi_type(double) { return MPI_DOUBLE; } - inline MPI_Datatype mpi_type(float) { return MPI_FLOAT; } - inline MPI_Datatype mpi_type(long double) { return MPI_LONG_DOUBLE; } -#ifndef LAM_MPI - inline MPI_Datatype mpi_type(std::complex) { return MPI_COMPLEX; } - inline MPI_Datatype mpi_type(std::complex) { return MPI_DOUBLE_COMPLEX; } -#endif - inline MPI_Datatype mpi_type(int) { return MPI_INT; } - inline MPI_Datatype mpi_type(unsigned int) { return MPI_UNSIGNED; } - inline MPI_Datatype mpi_type(size_t) { - if (sizeof(int) == sizeof(size_t)) return MPI_UNSIGNED; - if (sizeof(long) == sizeof(size_t)) return MPI_UNSIGNED_LONG; - return MPI_LONG_LONG; - } - - - - template struct mpi_distributed_matrix { - MAT M; - - mpi_distributed_matrix(size_type n, size_type m) : M(n, m) {} - mpi_distributed_matrix() {} - - const MAT &local_matrix(void) const { return M; } - MAT &local_matrix(void) { return M; } - }; - - template inline MAT &eff_matrix(MAT &m) { return m; } - template inline - const MAT &eff_matrix(const MAT &m) { return m; } - template inline - MAT &eff_matrix(mpi_distributed_matrix &m) { return m.M; } - template inline - const MAT &eff_matrix(const mpi_distributed_matrix &m) { return m.M; } - - - template - inline void copy(const mpi_distributed_matrix &m1, - mpi_distributed_matrix &m2) - { copy(eff_matrix(m1), eff_matrix(m2)); } - template - inline void copy(const mpi_distributed_matrix &m1, - const mpi_distributed_matrix &m2) - { copy(m1.M, m2.M); } - - template - inline void copy(const mpi_distributed_matrix &m1, MAT2 &m2) - { copy(m1.M, m2); } - template - inline void copy(const mpi_distributed_matrix &m1, const MAT2 &m2) - { copy(m1.M, m2); } - - - template inline - typename strongest_value_type3::value_type - vect_sp(const mpi_distributed_matrix &ps, const V1 &v1, - const V2 &v2) { - typedef typename strongest_value_type3::value_type T; - T res = vect_sp(ps.M, v1, v2), rest; - MPI_Allreduce(&res, &rest, 1, mpi_type(T()), MPI_SUM,MPI_COMM_WORLD); - return rest; - } - - template - inline void mult_add(const mpi_distributed_matrix &m, const V1 &v1, - V2 &v2) { - typedef typename linalg_traits::value_type T; - std::vector v3(vect_size(v2)), v4(vect_size(v2)); - static double tmult_tot = 0.0; - static double tmult_tot2 = 0.0; - double t_ref = MPI_Wtime(); - gmm::mult(m.M, v1, v3); - if (is_sparse(v2)) GMM_WARNING2("Using a plain temporary, here."); - double t_ref2 = MPI_Wtime(); - MPI_Allreduce(&(v3[0]), &(v4[0]),gmm::vect_size(v2), mpi_type(T()), - MPI_SUM,MPI_COMM_WORLD); - tmult_tot2 = MPI_Wtime()-t_ref2; - cout << "reduce mult mpi = " << tmult_tot2 << endl; - gmm::add(v4, v2); - tmult_tot = MPI_Wtime()-t_ref; - cout << "tmult mpi = " << tmult_tot << endl; - } - - template - void mult_add(const mpi_distributed_matrix &m, const V1 &v1, - const V2 &v2_) - { mult_add(m, v1, const_cast(v2_)); } - - template - inline void mult(const mpi_distributed_matrix &m, const V1 &v1, - const V2 &v2_) - { V2 &v2 = const_cast(v2_); clear(v2); mult_add(m, v1, v2); } - - template - inline void mult(const mpi_distributed_matrix &m, const V1 &v1, - V2 &v2) - { clear(v2); mult_add(m, v1, v2); } - - template - inline void mult(const mpi_distributed_matrix &m, const V1 &v1, - const V2 &v2, const V3 &v3_) - { V3 &v3 = const_cast(v3_); gmm::copy(v2, v3); mult_add(m, v1, v3); } - - template - inline void mult(const mpi_distributed_matrix &m, const V1 &v1, - const V2 &v2, V3 &v3) - { gmm::copy(v2, v3); mult_add(m, v1, v3); } - - - template inline - size_type mat_nrows(const mpi_distributed_matrix &M) - { return mat_nrows(M.M); } - template inline - size_type mat_ncols(const mpi_distributed_matrix &M) - { return mat_nrows(M.M); } - template inline - void resize(mpi_distributed_matrix &M, size_type m, size_type n) - { resize(M.M, m, n); } - template inline void clear(mpi_distributed_matrix &M) - { clear(M.M); } - - - // For compute reduced system - template inline - void mult(const MAT1 &M1, const mpi_distributed_matrix &M2, - mpi_distributed_matrix &M3) - { mult(M1, M2.M, M3.M); } - template inline - void mult(const mpi_distributed_matrix &M2, - const MAT1 &M1, mpi_distributed_matrix &M3) - { mult(M2.M, M1, M3.M); } - template inline - void mult(const MAT1 &M1, const mpi_distributed_matrix &M2, - MAT3 &M3) - { mult(M1, M2.M, M3); } - template inline - void mult(const MAT1 &M1, const mpi_distributed_matrix &M2, - const MAT3 &M3) - { mult(M1, M2.M, M3); } - - template - struct sub_matrix_type *, SUBI1, SUBI2> - { typedef abstract_null_type matrix_type; }; - - template - struct sub_matrix_type *, SUBI1, SUBI2> - { typedef abstract_null_type matrix_type; }; - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - M *>::return_type - sub_matrix(mpi_distributed_matrix &m, const SUBI1 &si1, const SUBI2 &si2) - { return sub_matrix(m.M, si1, si2); } - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - const MAT *>::return_type - sub_matrix(const mpi_distributed_matrix &m, const SUBI1 &si1, - const SUBI2 &si2) - { return sub_matrix(m.M, si1, si2); } - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - M *>::return_type - sub_matrix(mpi_distributed_matrix &m, const SUBI1 &si1) - { return sub_matrix(m.M, si1, si1); } - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - const M *>::return_type - sub_matrix(const mpi_distributed_matrix &m, const SUBI1 &si1) - { return sub_matrix(m.M, si1, si1); } - - - template struct transposed_return *> - { typedef abstract_null_type return_type; }; - template struct transposed_return *> - { typedef abstract_null_type return_type; }; - - template inline typename transposed_return::return_type - transposed(const mpi_distributed_matrix &l) - { return transposed(l.M); } - - template inline typename transposed_return::return_type - transposed(mpi_distributed_matrix &l) - { return transposed(l.M); } - - - template - struct linalg_traits > { - typedef mpi_distributed_matrix this_type; - typedef MAT origin_type; - typedef linalg_false is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::storage_type storage_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_row_iterator; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_col_iterator; - typedef abstract_null_type sub_orientation; - typedef abstract_null_type index_sorted; - static size_type nrows(const this_type &m) { return nrows(m.M); } - static size_type ncols(const this_type &m) { return ncols(m.M); } - static void do_clear(this_type &m) { clear(m.M); } - }; - -} - - -#endif // GMM_USES_MPI - -namespace std { - template - void swap(gmm::row_matrix &m1, gmm::row_matrix &m2) - { m1.swap(m2); } - template - void swap(gmm::col_matrix &m1, gmm::col_matrix &m2) - { m1.swap(m2); } - template - void swap(gmm::dense_matrix &m1, gmm::dense_matrix &m2) - { m1.swap(m2); } - template void - swap(gmm::csc_matrix &m1, gmm::csc_matrix &m2) - { m1.swap(m2); } - template void - swap(gmm::csr_matrix &m1, gmm::csr_matrix &m2) - { m1.swap(m2); } -} - - - - -#endif /* GMM_MATRIX_H__ */ diff --git a/include/gmm/gmm_modified_gram_schmidt.h b/include/gmm/gmm_modified_gram_schmidt.h deleted file mode 100644 index 1f5b62481d7..00000000000 --- a/include/gmm/gmm_modified_gram_schmidt.h +++ /dev/null @@ -1,97 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 1997-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_modified_gram_schmidt.h - @author Andrew Lumsdaine , Lie-Quan Lee - @date October 13, 2002. - @brief Modified Gram-Schmidt orthogonalization -*/ - -#ifndef GMM_MODIFIED_GRAM_SCHMIDT_H -#define GMM_MODIFIED_GRAM_SCHMIDT_H - -#include "gmm_kernel.h" - -namespace gmm { - - template - class modified_gram_schmidt { - protected: - typedef dense_matrix MAT; - MAT M; - - public: - - modified_gram_schmidt(int restart, size_t s) : M(s, restart+1) {} - - typename linalg_traits::const_sub_col_type - operator[](size_t i) const { return mat_const_col(M, i); } - - typename linalg_traits::sub_col_type - operator[](size_t i) { return mat_col(M, i); } - - inline size_type nrows(void) const { return M.nrows(); } - inline size_type ncols(void) const { return M.ncols(); } - MAT &mat(void) { return M; } - const MAT &mat(void) const { return M; } - - }; - - template inline - void orthogonalize(modified_gram_schmidt& V, const VecHi& Hi_, size_t i) { - VecHi& Hi = const_cast(Hi_); - - for (size_t k = 0; k <= i; k++) { - Hi[k] = gmm::vect_hp(V[i+1], V[k]); - gmm::add(gmm::scaled(V[k], -Hi[k]), V[i+1]); - } - } - - template - void orthogonalize_with_refinment(modified_gram_schmidt& V, - const VecHi& Hi_, size_t i) { - VecHi& Hi = const_cast(Hi_); - orthogonalize(V, Hi_, i); - - sub_interval SUBI(0, V.nrows()), SUBJ(0, i+1); - std::vector corr(i+1); - gmm::mult(conjugated(sub_matrix(V.mat(), SUBI, SUBJ)), - V[i+1], corr); - gmm::mult(sub_matrix(V.mat(), SUBI, SUBJ), - scaled(corr, T(-1)), V[i+1],V[i+1]); - gmm::add(corr, sub_vector(Hi, SUBJ)); - } - - template - void combine(modified_gram_schmidt& V, const VecS& s, VecX& x, size_t i) - { for (size_t j = 0; j < i; ++j) gmm::add(gmm::scaled(V[j], s[j]), x); } -} - -#endif diff --git a/include/gmm/gmm_opt.h b/include/gmm/gmm_opt.h deleted file mode 100644 index 40d62f9d8c9..00000000000 --- a/include/gmm/gmm_opt.h +++ /dev/null @@ -1,125 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_opt.h - @author Yves Renard - @date July 9, 2003. - @brief Optimization for some small cases (inversion of 2x2 matrices etc.) -*/ -#ifndef GMM_OPT_H__ -#define GMM_OPT_H__ - -namespace gmm { - - /* ********************************************************************* */ - /* Optimized determinant and inverse for small matrices (2x2 and 3x3) */ - /* with dense_matrix. */ - /* ********************************************************************* */ - - template T lu_det(const dense_matrix &A) { - size_type n(mat_nrows(A)); - if (n) { - const T *p = &(A(0,0)); - switch (n) { - case 1 : return (*p); - case 2 : return (*p) * (*(p+3)) - (*(p+1)) * (*(p+2)); -// Not stable for nearly singular matrices -// case 3 : return (*p) * ((*(p+4)) * (*(p+8)) - (*(p+5)) * (*(p+7))) -// - (*(p+1)) * ((*(p+3)) * (*(p+8)) - (*(p+5)) * (*(p+6))) -// + (*(p+2)) * ((*(p+3)) * (*(p+7)) - (*(p+4)) * (*(p+6))); - default : - { - dense_matrix B(mat_nrows(A), mat_ncols(A)); - std::vector ipvt(mat_nrows(A)); - gmm::copy(A, B); - lu_factor(B, ipvt); - return lu_det(B, ipvt); - } - } - } - return T(1); - } - - - template T lu_inverse(const dense_matrix &A_) { - dense_matrix& A = const_cast &>(A_); - size_type N = mat_nrows(A); - T det(1); - if (N) { - T *p = &(A(0,0)); - if (N <= 2) { - switch (N) { - case 1 : { - det = *p; - GMM_ASSERT1(det!=T(0), "non invertible matrix"); - *p = T(1) / det; - } break; - case 2 : { - det = (*p) * (*(p+3)) - (*(p+1)) * (*(p+2)); - GMM_ASSERT1(det!=T(0), "non invertible matrix"); - std::swap(*p, *(p+3)); - *p++ /= det; *p++ /= -det; *p++ /= -det; *p++ /= det; - } break; -// case 3 : { // not stable for nearly singular matrices -// T a, b, c, d, e, f, g, h, i; -// a = (*(p+4)) * (*(p+8)) - (*(p+5)) * (*(p+7)); -// b = - (*(p+1)) * (*(p+8)) + (*(p+2)) * (*(p+7)); -// c = (*(p+1)) * (*(p+5)) - (*(p+2)) * (*(p+4)); -// d = - (*(p+3)) * (*(p+8)) + (*(p+5)) * (*(p+6)); -// e = (*(p+0)) * (*(p+8)) - (*(p+2)) * (*(p+6)); -// f = - (*(p+0)) * (*(p+5)) + (*(p+2)) * (*(p+3)); -// g = (*(p+3)) * (*(p+7)) - (*(p+4)) * (*(p+6)); -// h = - (*(p+0)) * (*(p+7)) + (*(p+1)) * (*(p+6)); -// i = (*(p+0)) * (*(p+4)) - (*(p+1)) * (*(p+3)); -// det = (*p) * a + (*(p+1)) * d + (*(p+2)) * g; -// GMM_ASSERT1(det!=T(0), "non invertible matrix"); -// *p++ = a / det; *p++ = b / det; *p++ = c / det; -// *p++ = d / det; *p++ = e / det; *p++ = f / det; -// *p++ = g / det; *p++ = h / det; *p++ = i / det; -// } break; - } - } - else { - dense_matrix B(mat_nrows(A), mat_ncols(A)); - std::vector ipvt(mat_nrows(A)); - gmm::copy(A, B); - size_type info = lu_factor(B, ipvt); - GMM_ASSERT1(!info, "non invertible matrix"); - lu_inverse(B, ipvt, A); - return lu_det(B, ipvt); - } - } - return det; - } - - -} - -#endif // GMM_OPT_H__ diff --git a/include/gmm/gmm_precond.h b/include/gmm/gmm_precond.h deleted file mode 100644 index 12a39d93592..00000000000 --- a/include/gmm/gmm_precond.h +++ /dev/null @@ -1,64 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2004-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== -#ifndef GMM_PRECOND_H -#define GMM_PRECOND_H - -#include "gmm_kernel.h" - -/** @file gmm_precond.h - @author Yves Renard - @date March 29, 2004. - @brief gmm preconditioners. - */ - -/* Preconditioner concept : */ -/* */ -/* A the matrix, P the preconditioner PA well conditioned. */ -/* PRECOND precontioner type. */ -/* mult(P, v, w) : w <- P v */ -/* transposed_mult(P, v, w) : w <- transposed(P) v */ -/* left_mult(P, v, w) : see qmr solver */ -/* right_mult(P, v, w) : see qmr solver */ -/* transposed_left_mult(P, v, w) : see qmr solver */ -/* transposed_right_mult(P, v, w) : see qmr solver */ -/* */ -/* PRECOND P() : empty preconditioner. */ -/* PRECOND P(A, ...) : preconditioner for the matrix A, with optional */ -/* parameters */ -/* PRECOND(...) : empty precondtioner with parameters set. */ -/* P.build_with(A) : build a precondtioner for A. */ -/* */ -/* *********************************************************************** */ - - - - -#endif - diff --git a/include/gmm/gmm_precond_diagonal.h b/include/gmm/gmm_precond_diagonal.h deleted file mode 100644 index fa698c4fc84..00000000000 --- a/include/gmm/gmm_precond_diagonal.h +++ /dev/null @@ -1,131 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_precond_diagonal.h - @author Yves Renard - @date June 5, 2003. - @brief Diagonal matrix preconditoner. -*/ - -#ifndef GMM_PRECOND_DIAGONAL_H -#define GMM_PRECOND_DIAGONAL_H - -#include "gmm_precond.h" - -namespace gmm { - - /** Diagonal preconditioner. */ - template struct diagonal_precond { - typedef typename linalg_traits::value_type value_type; - typedef typename number_traits::magnitude_type magnitude_type; - - std::vector diag; - - void build_with(const Matrix &M) { - diag.resize(mat_nrows(M)); - for (size_type i = 0; i < mat_nrows(M); ++i) { - magnitude_type x = gmm::abs(M(i, i)); - if (x == magnitude_type(0)) { - x = magnitude_type(1); - GMM_WARNING2("The matrix has a zero on its diagonal"); - } - diag[i] = magnitude_type(1) / x; - } - } - size_type memsize() const { return sizeof(*this) + diag.size() * sizeof(value_type); } - diagonal_precond(const Matrix &M) { build_with(M); } - diagonal_precond(void) {} - }; - - template inline - void mult_diag_p(const diagonal_precond& P, V2 &v2, abstract_sparse){ - typename linalg_traits::iterator it = vect_begin(v2), - ite = vect_end(v2); - for (; it != ite; ++it) *it *= P.diag[it.index()]; - } - - template inline - void mult_diag_p(const diagonal_precond& P,V2 &v2, abstract_skyline) - { mult_diag_p(P, v2, abstract_sparse()); } - - template inline - void mult_diag_p(const diagonal_precond& P, V2 &v2, abstract_dense){ - for (size_type i = 0; i < P.diag.size(); ++i) v2[i] *= P.diag[i]; - } - - template inline - void mult(const diagonal_precond& P, const V1 &v1, V2 &v2) { - GMM_ASSERT2(P.diag.size() == vect_size(v2),"dimensions mismatch"); - copy(v1, v2); - mult_diag_p(P, v2, typename linalg_traits::storage_type()); - } - - template inline - void transposed_mult(const diagonal_precond& P,const V1 &v1,V2 &v2) { - mult(P, v1, v2); - } - - // # define DIAG_LEFT_MULT_SQRT - - template inline - void left_mult(const diagonal_precond& P, const V1 &v1, V2 &v2) { - GMM_ASSERT2(P.diag.size() == vect_size(v2), "dimensions mismatch"); - copy(v1, v2); -# ifdef DIAG_LEFT_MULT_SQRT - for (size_type i= 0; i < P.diag.size(); ++i) v2[i] *= gmm::sqrt(P.diag[i]); -# else - for (size_type i= 0; i < P.diag.size(); ++i) v2[i] *= P.diag[i]; -# endif - } - - template inline - void transposed_left_mult(const diagonal_precond& P, - const V1 &v1, V2 &v2) - { left_mult(P, v1, v2); } - - template inline - void right_mult(const diagonal_precond& P, const V1 &v1, V2 &v2) { - typedef typename linalg_traits::value_type T; - GMM_ASSERT2(P.diag.size() == vect_size(v2), "dimensions mismatch"); - copy(v1, v2); -# ifdef DIAG_LEFT_MULT_SQRT - for (size_type i= 0; i < P.diag.size(); ++i) v2[i] *= gmm::sqrt(P.diag[i]); -# endif - } - - template inline - void transposed_right_mult(const diagonal_precond& P, - const V1 &v1, V2 &v2) - { right_mult(P, v1, v2); } - -} - -#endif - diff --git a/include/gmm/gmm_precond_ildlt.h b/include/gmm/gmm_precond_ildlt.h deleted file mode 100644 index bd0effca040..00000000000 --- a/include/gmm/gmm_precond_ildlt.h +++ /dev/null @@ -1,286 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of cholesky.h from ITL. -// See http://osl.iu.edu/research/itl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -#ifndef GMM_PRECOND_ILDLT_H -#define GMM_PRECOND_ILDLT_H - -/**@file gmm_precond_ildlt.h - @author Andrew Lumsdaine - @author Lie-Quan Lee - @author Yves Renard - @date June 5, 2003. - @brief Incomplete Level 0 ILDLT Preconditioner. -*/ - -#include "gmm_precond.h" - -namespace gmm { - - /** Incomplete Level 0 LDLT Preconditioner. - - For use with symmetric real or hermitian complex sparse matrices. - - Notes: The idea under a concrete Preconditioner such as Incomplete - Cholesky is to create a Preconditioner object to use in iterative - methods. - - - Y. Renard : Transformed in LDLT for stability reason. - - U=LT is stored in csr format. D is stored on the diagonal of U. - */ - template - class ildlt_precond { - - public : - typedef typename linalg_traits::value_type value_type; - typedef typename number_traits::magnitude_type magnitude_type; - typedef csr_matrix_ref tm_type; - - tm_type U; - - protected : - std::vector Tri_val; - std::vector Tri_ind, Tri_ptr; - - template void do_ildlt(const M& A, row_major); - void do_ildlt(const Matrix& A, col_major); - - public: - - size_type nrows(void) const { return mat_nrows(U); } - size_type ncols(void) const { return mat_ncols(U); } - value_type &D(size_type i) { return Tri_val[Tri_ptr[i]]; } - const value_type &D(size_type i) const { return Tri_val[Tri_ptr[i]]; } - ildlt_precond(void) {} - void build_with(const Matrix& A) { - Tri_ptr.resize(mat_nrows(A)+1); - do_ildlt(A, typename principal_orientation_type::sub_orientation>::potype()); - } - ildlt_precond(const Matrix& A) { build_with(A); } - size_type memsize() const { - return sizeof(*this) + - Tri_val.size() * sizeof(value_type) + - (Tri_ind.size()+Tri_ptr.size()) * sizeof(size_type); - } - }; - - template template - void ildlt_precond::do_ildlt(const M& A, row_major) { - typedef typename linalg_traits::storage_type store_type; - typedef value_type T; - typedef typename number_traits::magnitude_type R; - - size_type Tri_loc = 0, n = mat_nrows(A), d, g, h, i, j, k; - if (n == 0) return; - T z, zz; - Tri_ptr[0] = 0; - R prec = default_tol(R()); - R max_pivot = gmm::abs(A(0,0)) * prec; - - for (int count = 0; count < 2; ++count) { - if (count) { Tri_val.resize(Tri_loc); Tri_ind.resize(Tri_loc); } - for (Tri_loc = 0, i = 0; i < n; ++i) { - typedef typename linalg_traits::const_sub_row_type row_type; - row_type row = mat_const_row(A, i); - typename linalg_traits::const_iterator - it = vect_const_begin(row), ite = vect_const_end(row); - - if (count) { Tri_val[Tri_loc] = T(0); Tri_ind[Tri_loc] = i; } - ++Tri_loc; // diagonal element - - for (k = 0; it != ite; ++it, ++k) { - j = index_of_it(it, k, store_type()); - if (i == j) { - if (count) Tri_val[Tri_loc-1] = *it; - } - else if (j > i) { - if (count) { Tri_val[Tri_loc] = *it; Tri_ind[Tri_loc]=j; } - ++Tri_loc; - } - } - Tri_ptr[i+1] = Tri_loc; - } - } - - if (A(0,0) == T(0)) { - Tri_val[Tri_ptr[0]] = T(1); - GMM_WARNING2("pivot 0 is too small"); - } - - for (k = 0; k < n; k++) { - d = Tri_ptr[k]; - z = T(gmm::real(Tri_val[d])); Tri_val[d] = z; - if (gmm::abs(z) <= max_pivot) { - Tri_val[d] = z = T(1); - GMM_WARNING2("pivot " << k << " is too small [" << gmm::abs(z) << "]"); - } - max_pivot = std::max(max_pivot, std::min(gmm::abs(z) * prec, R(1))); - - for (i = d + 1; i < Tri_ptr[k+1]; ++i) Tri_val[i] /= z; - for (i = d + 1; i < Tri_ptr[k+1]; ++i) { - zz = gmm::conj(Tri_val[i] * z); - h = Tri_ind[i]; - g = i; - - for (j = Tri_ptr[h] ; j < Tri_ptr[h+1]; ++j) - for ( ; g < Tri_ptr[k+1] && Tri_ind[g] <= Tri_ind[j]; ++g) - if (Tri_ind[g] == Tri_ind[j]) - Tri_val[j] -= zz * Tri_val[g]; - } - } - U = tm_type(&(Tri_val[0]), &(Tri_ind[0]), &(Tri_ptr[0]), - n, mat_ncols(A)); - } - - template - void ildlt_precond::do_ildlt(const Matrix& A, col_major) - { do_ildlt(gmm::conjugated(A), row_major()); } - - template inline - void mult(const ildlt_precond& P, const V1 &v1, V2 &v2) { - gmm::copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < mat_nrows(P.U); ++i) v2[i] /= P.D(i); - gmm::upper_tri_solve(P.U, v2, true); - } - - template inline - void transposed_mult(const ildlt_precond& P,const V1 &v1,V2 &v2) - { mult(P, v1, v2); } - - template inline - void left_mult(const ildlt_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < mat_nrows(P.U); ++i) v2[i] /= P.D(i); - } - - template inline - void right_mult(const ildlt_precond& P, const V1 &v1, V2 &v2) - { copy(v1, v2); gmm::upper_tri_solve(P.U, v2, true); } - - template inline - void transposed_left_mult(const ildlt_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - gmm::upper_tri_solve(P.U, v2, true); - for (size_type i = 0; i < mat_nrows(P.U); ++i) v2[i] /= P.D(i); - } - - template inline - void transposed_right_mult(const ildlt_precond& P, const V1 &v1, - V2 &v2) - { copy(v1, v2); gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); } - - - - // for compatibility with old versions - - template - struct cholesky_precond : public ildlt_precond { - cholesky_precond(const Matrix& A) : ildlt_precond(A) {} - cholesky_precond(void) {} - } IS_DEPRECATED; - - template inline - void mult(const cholesky_precond& P, const V1 &v1, V2 &v2) { - gmm::copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < mat_nrows(P.U); ++i) v2[i] /= P.D(i); - gmm::upper_tri_solve(P.U, v2, true); - } - - template inline - void transposed_mult(const cholesky_precond& P,const V1 &v1,V2 &v2) - { mult(P, v1, v2); } - - template inline - void left_mult(const cholesky_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < mat_nrows(P.U); ++i) v2[i] /= P.D(i); - } - - template inline - void right_mult(const cholesky_precond& P, const V1 &v1, V2 &v2) - { copy(v1, v2); gmm::upper_tri_solve(P.U, v2, true); } - - template inline - void transposed_left_mult(const cholesky_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - gmm::upper_tri_solve(P.U, v2, true); - for (size_type i = 0; i < mat_nrows(P.U); ++i) v2[i] /= P.D(i); - } - - template inline - void transposed_right_mult(const cholesky_precond& P, const V1 &v1, - V2 &v2) - { copy(v1, v2); gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); } - -} - -#endif - diff --git a/include/gmm/gmm_precond_ildltt.h b/include/gmm/gmm_precond_ildltt.h deleted file mode 100644 index 207ecfb2fdc..00000000000 --- a/include/gmm/gmm_precond_ildltt.h +++ /dev/null @@ -1,217 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_precond_ildltt.h - @author Yves Renard - @date June 30, 2003. - @brief incomplete LDL^t (cholesky) preconditioner with fill-in and threshold. -*/ - -#ifndef GMM_PRECOND_ILDLTT_H -#define GMM_PRECOND_ILDLTT_H - -// Store U = LT and D in indiag. On each line, the fill-in is the number -// of non-zero elements on the line of the original matrix plus K, except if -// the matrix is dense. In this case the fill-in is K on each line. - -#include "gmm_precond_ilut.h" - -namespace gmm { - /** incomplete LDL^t (cholesky) preconditioner with fill-in and - threshold. */ - template - class ildltt_precond { - public : - typedef typename linalg_traits::value_type value_type; - typedef typename number_traits::magnitude_type magnitude_type; - - typedef rsvector svector; - - row_matrix U; - std::vector indiag; - - protected: - size_type K; - double eps; - - template void do_ildltt(const M&, row_major); - void do_ildltt(const Matrix&, col_major); - - public: - void build_with(const Matrix& A) { - gmm::resize(U, mat_nrows(A), mat_ncols(A)); - indiag.resize(std::min(mat_nrows(A), mat_ncols(A))); - do_ildltt(A, typename principal_orientation_type::sub_orientation>::potype()); - } - ildltt_precond(const Matrix& A, int k_, double eps_) - : U(mat_nrows(A),mat_ncols(A)), K(k_), eps(eps_) { build_with(A); } - ildltt_precond(void) { K=10; eps = 1E-7; } - ildltt_precond(size_type k_, double eps_) : K(k_), eps(eps_) {} - size_type memsize() const { - return sizeof(*this) + nnz(U)*sizeof(value_type) + indiag.size() * sizeof(magnitude_type); - } - }; - - template template - void ildltt_precond::do_ildltt(const M& A,row_major) { - typedef value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = mat_nrows(A); - if (n == 0) return; - svector w(n); - T tmp; - R prec = default_tol(R()), max_pivot = gmm::abs(A(0,0)) * prec; - - gmm::clear(U); - for (size_type i = 0; i < n; ++i) { - gmm::copy(mat_const_row(A, i), w); - double norm_row = gmm::vect_norm2(w); - - for (size_type krow = 0, k; krow < w.nb_stored(); ++krow) { - typename svector::iterator wk = w.begin() + krow; - if ((k = wk->c) >= i) break; - if (gmm::is_complex(wk->e)) { - tmp = gmm::conj(U(k, i))/indiag[k]; // not completely satisfactory .. - gmm::add(scaled(mat_row(U, k), -tmp), w); - } - else { - tmp = wk->e; - if (gmm::abs(tmp) < eps * norm_row) { w.sup(k); --krow; } - else { wk->e += tmp; gmm::add(scaled(mat_row(U, k), -tmp), w); } - } - } - tmp = w[i]; - - if (gmm::abs(gmm::real(tmp)) <= max_pivot) - { GMM_WARNING2("pivot " << i << " is too small"); tmp = T(1); } - - max_pivot = std::max(max_pivot, std::min(gmm::abs(tmp) * prec, R(1))); - indiag[i] = R(1) / gmm::real(tmp); - gmm::clean(w, eps * norm_row); - gmm::scale(w, T(indiag[i])); - std::sort(w.begin(), w.end(), elt_rsvector_value_less_()); - typename svector::const_iterator wit = w.begin(), wite = w.end(); - for (size_type nnu = 0; wit != wite; ++wit) // copy to be optimized ... - if (wit->c > i) { if (nnu < K) { U(i, wit->c) = wit->e; ++nnu; } } - } - } - - template - void ildltt_precond::do_ildltt(const Matrix& A, col_major) - { do_ildltt(gmm::conjugated(A), row_major()); } - - template inline - void mult(const ildltt_precond& P, const V1 &v1, V2 &v2) { - gmm::copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < P.indiag.size(); ++i) v2[i] *= P.indiag[i]; - gmm::upper_tri_solve(P.U, v2, true); - } - - template inline - void transposed_mult(const ildltt_precond& P,const V1 &v1, V2 &v2) - { mult(P, v1, v2); } - - template inline - void left_mult(const ildltt_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < P.indiag.size(); ++i) v2[i] *= P.indiag[i]; - } - - template inline - void right_mult(const ildltt_precond& P, const V1 &v1, V2 &v2) - { copy(v1, v2); gmm::upper_tri_solve(P.U, v2, true); } - - template inline - void transposed_left_mult(const ildltt_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - gmm::upper_tri_solve(P.U, v2, true); - for (size_type i = 0; i < P.indiag.size(); ++i) v2[i] *= P.indiag[i]; - } - - template inline - void transposed_right_mult(const ildltt_precond& P, const V1 &v1, - V2 &v2) - { copy(v1, v2); gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); } - - - // for compatibility with old versions - - template - struct choleskyt_precond : public ildltt_precond{ - choleskyt_precond(const Matrix& A, int k_, double eps_) - : ildltt_precond(A, k_, eps_) {} - choleskyt_precond(void) {} - } IS_DEPRECATED; - - template inline - void mult(const choleskyt_precond& P, const V1 &v1, V2 &v2) { - gmm::copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < P.indiag.size(); ++i) v2[i] *= P.indiag[i]; - gmm::upper_tri_solve(P.U, v2, true); - } - - template inline - void transposed_mult(const choleskyt_precond& P,const V1 &v1, V2 &v2) - { mult(P, v1, v2); } - - template inline - void left_mult(const choleskyt_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); - for (size_type i = 0; i < P.indiag.size(); ++i) v2[i] *= P.indiag[i]; - } - - template inline - void right_mult(const choleskyt_precond& P, const V1 &v1, V2 &v2) - { copy(v1, v2); gmm::upper_tri_solve(P.U, v2, true); } - - template inline - void transposed_left_mult(const choleskyt_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - gmm::upper_tri_solve(P.U, v2, true); - for (size_type i = 0; i < P.indiag.size(); ++i) v2[i] *= P.indiag[i]; - } - - template inline - void transposed_right_mult(const choleskyt_precond& P, const V1 &v1, - V2 &v2) - { copy(v1, v2); gmm::lower_tri_solve(gmm::conjugated(P.U), v2, true); } - -} - -#endif - diff --git a/include/gmm/gmm_precond_ilu.h b/include/gmm/gmm_precond_ilu.h deleted file mode 100644 index a71ef80101e..00000000000 --- a/include/gmm/gmm_precond_ilu.h +++ /dev/null @@ -1,280 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 1997-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of ilu.h from ITL. -// See http://osl.iu.edu/research/itl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -/**@file gmm_precond_ilu.h - @author Andrew Lumsdaine - @author Lie-Quan Lee - @author Yves Renard - @date June 5, 2003. - @brief Incomplete LU without fill-in Preconditioner. -*/ - -#ifndef GMM_PRECOND_ILU_H -#define GMM_PRECOND_ILU_H - -// -// Notes: The idea under a concrete Preconditioner such -// as Incomplete LU is to create a Preconditioner -// object to use in iterative methods. -// - -#include "gmm_precond.h" - -namespace gmm { - /** Incomplete LU without fill-in Preconditioner. */ - template - class ilu_precond { - - public : - typedef typename linalg_traits::value_type value_type; - typedef csr_matrix_ref tm_type; - - tm_type U, L; - bool invert; - protected : - std::vector L_val, U_val; - std::vector L_ind, U_ind, L_ptr, U_ptr; - - template void do_ilu(const M& A, row_major); - void do_ilu(const Matrix& A, col_major); - - public: - - size_type nrows(void) const { return mat_nrows(L); } - size_type ncols(void) const { return mat_ncols(U); } - - void build_with(const Matrix& A) { - invert = false; - L_ptr.resize(mat_nrows(A)+1); - U_ptr.resize(mat_nrows(A)+1); - do_ilu(A, typename principal_orientation_type::sub_orientation>::potype()); - } - ilu_precond(const Matrix& A) { build_with(A); } - ilu_precond(void) {} - size_type memsize() const { - return sizeof(*this) + - (L_val.size()+U_val.size()) * sizeof(value_type) + - (L_ind.size()+L_ptr.size()) * sizeof(size_type) + - (U_ind.size()+U_ptr.size()) * sizeof(size_type); - } - }; - - template template - void ilu_precond::do_ilu(const M& A, row_major) { - typedef typename linalg_traits::storage_type store_type; - typedef value_type T; - typedef typename number_traits::magnitude_type R; - - size_type L_loc = 0, U_loc = 0, n = mat_nrows(A), i, j, k; - if (n == 0) return; - L_ptr[0] = 0; U_ptr[0] = 0; - R prec = default_tol(R()); - R max_pivot = gmm::abs(A(0,0)) * prec; - - - for (int count = 0; count < 2; ++count) { - if (count) { - L_val.resize(L_loc); L_ind.resize(L_loc); - U_val.resize(U_loc); U_ind.resize(U_loc); - } - L_loc = U_loc = 0; - for (i = 0; i < n; ++i) { - typedef typename linalg_traits::const_sub_row_type row_type; - row_type row = mat_const_row(A, i); - typename linalg_traits::const_iterator - it = vect_const_begin(row), ite = vect_const_end(row); - - if (count) { U_val[U_loc] = T(0); U_ind[U_loc] = i; } - ++U_loc; // diagonal element - - for (k = 0; it != ite && k < 1000; ++it, ++k) { - // if a plain row is present, retains only the 1000 firsts - // nonzero elements. ---> a sort should be done. - j = index_of_it(it, k, store_type()); - if (j < i) { - if (count) { L_val[L_loc] = *it; L_ind[L_loc] = j; } - L_loc++; - } - else if (i == j) { - if (count) U_val[U_loc-1] = *it; - } - else { - if (count) { U_val[U_loc] = *it; U_ind[U_loc] = j; } - U_loc++; - } - } - L_ptr[i+1] = L_loc; U_ptr[i+1] = U_loc; - } - } - - if (A(0,0) == T(0)) { - U_val[U_ptr[0]] = T(1); - GMM_WARNING2("pivot 0 is too small"); - } - - size_type qn, pn, rn; - for (i = 1; i < n; i++) { - - pn = U_ptr[i]; - if (gmm::abs(U_val[pn]) <= max_pivot) { - U_val[pn] = T(1); - GMM_WARNING2("pivot " << i << " is too small"); - } - max_pivot = std::max(max_pivot, - std::min(gmm::abs(U_val[pn]) * prec, R(1))); - - for (j = L_ptr[i]; j < L_ptr[i+1]; j++) { - pn = U_ptr[L_ind[j]]; - - T multiplier = (L_val[j] /= U_val[pn]); - - qn = j + 1; - rn = U_ptr[i]; - - for (pn++; U_ind[pn] < i && pn < U_ptr[L_ind[j]+1]; pn++) { - while (L_ind[qn] < U_ind[pn] && qn < L_ptr[i+1]) - qn++; - if (U_ind[pn] == L_ind[qn] && qn < L_ptr[i+1]) - L_val[qn] -= multiplier * U_val[pn]; - } - for (; pn < U_ptr[L_ind[j]+1]; pn++) { - while (U_ind[rn] < U_ind[pn] && rn < U_ptr[i+1]) - rn++; - if (U_ind[pn] == U_ind[rn] && rn < U_ptr[i+1]) - U_val[rn] -= multiplier * U_val[pn]; - } - } - } - - L = tm_type(&(L_val[0]), &(L_ind[0]), &(L_ptr[0]), n, mat_ncols(A)); - U = tm_type(&(U_val[0]), &(U_ind[0]), &(U_ptr[0]), n, mat_ncols(A)); - } - - template - void ilu_precond::do_ilu(const Matrix& A, col_major) { - do_ilu(gmm::transposed(A), row_major()); - invert = true; - } - - template inline - void mult(const ilu_precond& P, const V1 &v1, V2 &v2) { - gmm::copy(v1, v2); - if (P.invert) { - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - else { - gmm::lower_tri_solve(P.L, v2, true); - gmm::upper_tri_solve(P.U, v2, false); - } - } - - template inline - void transposed_mult(const ilu_precond& P,const V1 &v1,V2 &v2) { - gmm::copy(v1, v2); - if (P.invert) { - gmm::lower_tri_solve(P.L, v2, true); - gmm::upper_tri_solve(P.U, v2, false); - } - else { - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - } - - template inline - void left_mult(const ilu_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - else gmm::lower_tri_solve(P.L, v2, true); - } - - template inline - void right_mult(const ilu_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - else gmm::upper_tri_solve(P.U, v2, false); - } - - template inline - void transposed_left_mult(const ilu_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::upper_tri_solve(P.U, v2, false); - else gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - - template inline - void transposed_right_mult(const ilu_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::lower_tri_solve(P.L, v2, true); - else gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - } - - -} - -#endif - diff --git a/include/gmm/gmm_precond_ilut.h b/include/gmm/gmm_precond_ilut.h deleted file mode 100644 index 4ed81a6b70f..00000000000 --- a/include/gmm/gmm_precond_ilut.h +++ /dev/null @@ -1,227 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 1997-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== -#ifndef GMM_PRECOND_ILUT_H -#define GMM_PRECOND_ILUT_H - -/**@file gmm_precond_ilut.h - @author Andrew Lumsdaine , Lie-Quan Lee - @date June 5, 2003. - @brief ILUT: Incomplete LU with threshold and K fill-in Preconditioner. -*/ - -/* - Performane comparing for SSOR, ILU and ILUT based on sherman 5 matrix - in Harwell-Boeing collection on Sun Ultra 30 UPA/PCI (UltraSPARC-II 296MHz) - Preconditioner & Factorization time & Number of Iteration \\ \hline - SSOR & 0.010577 & 41 \\ - ILU & 0.019336 & 32 \\ - ILUT with 0 fill-in and threshold of 1.0e-6 & 0.343612 & 23 \\ - ILUT with 5 fill-in and threshold of 1.0e-6 & 0.343612 & 18 \\ \hline -*/ - -#include "gmm_precond.h" - -namespace gmm { - - template struct elt_rsvector_value_less_ { - inline bool operator()(const elt_rsvector_& a, - const elt_rsvector_& b) const - { return (gmm::abs(a.e) > gmm::abs(b.e)); } - }; - - /** Incomplete LU with threshold and K fill-in Preconditioner. - - The algorithm of ILUT(A, 0, 1.0e-6) is slower than ILU(A). If No - fill-in is arrowed, you can use ILU instead of ILUT. - - Notes: The idea under a concrete Preconditioner such as ilut is to - create a Preconditioner object to use in iterative methods. - */ - template - class ilut_precond { - public : - typedef typename linalg_traits::value_type value_type; - typedef wsvector _wsvector; - typedef rsvector _rsvector; - typedef row_matrix<_rsvector> LU_Matrix; - - bool invert; - LU_Matrix L, U; - - protected: - size_type K; - double eps; - - template void do_ilut(const M&, row_major); - void do_ilut(const Matrix&, col_major); - - public: - void build_with(const Matrix& A) { - invert = false; - gmm::resize(L, mat_nrows(A), mat_ncols(A)); - gmm::resize(U, mat_nrows(A), mat_ncols(A)); - do_ilut(A, typename principal_orientation_type::sub_orientation>::potype()); - } - ilut_precond(const Matrix& A, int k_, double eps_) - : L(mat_nrows(A), mat_ncols(A)), U(mat_nrows(A), mat_ncols(A)), - K(k_), eps(eps_) { build_with(A); } - ilut_precond(size_type k_, double eps_) : K(k_), eps(eps_) {} - ilut_precond(void) { K = 10; eps = 1E-7; } - size_type memsize() const { - return sizeof(*this) + (nnz(U)+nnz(L))*sizeof(value_type); - } - }; - - template template - void ilut_precond::do_ilut(const M& A, row_major) { - typedef value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = mat_nrows(A); - if (n == 0) return; - std::vector indiag(n); - _wsvector w(mat_ncols(A)); - _rsvector ww(mat_ncols(A)), wL(mat_ncols(A)), wU(mat_ncols(A)); - T tmp; - gmm::clear(U); gmm::clear(L); - R prec = default_tol(R()); - R max_pivot = gmm::abs(A(0,0)) * prec; - - for (size_type i = 0; i < n; ++i) { - gmm::copy(mat_const_row(A, i), w); - double norm_row = gmm::vect_norm2(w); - - typename _wsvector::iterator wkold = w.end(); - for (typename _wsvector::iterator wk = w.begin(); - wk != w.end() && wk->first < i; ) { - size_type k = wk->first; - tmp = (wk->second) * indiag[k]; - if (gmm::abs(tmp) < eps * norm_row) w.erase(k); - else { wk->second += tmp; gmm::add(scaled(mat_row(U, k), -tmp), w); } - if (wkold == w.end()) wk = w.begin(); else { wk = wkold; ++wk; } - if (wk != w.end() && wk->first == k) - { if (wkold == w.end()) wkold = w.begin(); else ++wkold; ++wk; } - } - tmp = w[i]; - - if (gmm::abs(tmp) <= max_pivot) { - GMM_WARNING2("pivot " << i << " too small. try with ilutp ?"); - w[i] = tmp = T(1); - } - - max_pivot = std::max(max_pivot, std::min(gmm::abs(tmp) * prec, R(1))); - indiag[i] = T(1) / tmp; - gmm::clean(w, eps * norm_row); - gmm::copy(w, ww); - std::sort(ww.begin(), ww.end(), elt_rsvector_value_less_()); - typename _rsvector::const_iterator wit = ww.begin(), wite = ww.end(); - - size_type nnl = 0, nnu = 0; - wL.base_resize(K); wU.base_resize(K+1); - typename _rsvector::iterator witL = wL.begin(), witU = wU.begin(); - for (; wit != wite; ++wit) - if (wit->c < i) { if (nnl < K) { *witL++ = *wit; ++nnl; } } - else { if (nnu < K || wit->c == i) { *witU++ = *wit; ++nnu; } } - wL.base_resize(nnl); wU.base_resize(nnu); - std::sort(wL.begin(), wL.end()); - std::sort(wU.begin(), wU.end()); - gmm::copy(wL, L.row(i)); - gmm::copy(wU, U.row(i)); - } - - } - - template - void ilut_precond::do_ilut(const Matrix& A, col_major) { - do_ilut(gmm::transposed(A), row_major()); - invert = true; - } - - template inline - void mult(const ilut_precond& P, const V1 &v1, V2 &v2) { - gmm::copy(v1, v2); - if (P.invert) { - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - else { - gmm::lower_tri_solve(P.L, v2, true); - gmm::upper_tri_solve(P.U, v2, false); - } - } - - template inline - void transposed_mult(const ilut_precond& P,const V1 &v1,V2 &v2) { - gmm::copy(v1, v2); - if (P.invert) { - gmm::lower_tri_solve(P.L, v2, true); - gmm::upper_tri_solve(P.U, v2, false); - } - else { - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - } - - template inline - void left_mult(const ilut_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - else gmm::lower_tri_solve(P.L, v2, true); - } - - template inline - void right_mult(const ilut_precond& P, const V1 &v1, V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - else gmm::upper_tri_solve(P.U, v2, false); - } - - template inline - void transposed_left_mult(const ilut_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::upper_tri_solve(P.U, v2, false); - else gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - - template inline - void transposed_right_mult(const ilut_precond& P, const V1 &v1, - V2 &v2) { - copy(v1, v2); - if (P.invert) gmm::lower_tri_solve(P.L, v2, true); - else gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - } - -} - -#endif - diff --git a/include/gmm/gmm_precond_ilutp.h b/include/gmm/gmm_precond_ilutp.h deleted file mode 100644 index 29780cf1b91..00000000000 --- a/include/gmm/gmm_precond_ilutp.h +++ /dev/null @@ -1,281 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2004-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_precond_ilutp.h - @author Yves Renard - @date October 14, 2004. - @brief ILUTP: Incomplete LU with threshold and K fill-in Preconditioner and - column pivoting. - - -*/ -#ifndef GMM_PRECOND_ILUTP_H -#define GMM_PRECOND_ILUTP_H - -#include "gmm_precond_ilut.h" - -namespace gmm { - - /** - ILUTP: Incomplete LU with threshold and K fill-in Preconditioner and - column pivoting. - - See Yousef Saad, Iterative Methods for - sparse linear systems, PWS Publishing Company, section 10.4.4 - - TODO : store the permutation by cycles to avoid the temporary vector - */ - template - class ilutp_precond { - public : - typedef typename linalg_traits::value_type value_type; - typedef wsvector _wsvector; - typedef rsvector _rsvector; - typedef row_matrix<_rsvector> LU_Matrix; - typedef col_matrix<_wsvector> CLU_Matrix; - - bool invert; - LU_Matrix L, U; - gmm::unsorted_sub_index indperm; - gmm::unsorted_sub_index indperminv; - mutable std::vector temporary; - - protected: - size_type K; - double eps; - - template void do_ilutp(const M&, row_major); - void do_ilutp(const Matrix&, col_major); - - public: - void build_with(const Matrix& A) { - invert = false; - gmm::resize(L, mat_nrows(A), mat_ncols(A)); - gmm::resize(U, mat_nrows(A), mat_ncols(A)); - do_ilutp(A, typename principal_orientation_type::sub_orientation>::potype()); - } - ilutp_precond(const Matrix& A, size_type k_, double eps_) - : L(mat_nrows(A), mat_ncols(A)), U(mat_nrows(A), mat_ncols(A)), - K(k_), eps(eps_) { build_with(A); } - ilutp_precond(int k_, double eps_) : K(k_), eps(eps_) {} - ilutp_precond(void) { K = 10; eps = 1E-7; } - size_type memsize() const { - return sizeof(*this) + (nnz(U)+nnz(L))*sizeof(value_type); - } - }; - - - template template - void ilutp_precond::do_ilutp(const M& A, row_major) { - typedef value_type T; - typedef typename number_traits::magnitude_type R; - - size_type n = mat_nrows(A); - CLU_Matrix CU(n,n); - if (n == 0) return; - std::vector indiag(n); - temporary.resize(n); - std::vector ipvt(n), ipvtinv(n); - for (size_type i = 0; i < n; ++i) ipvt[i] = ipvtinv[i] = i; - indperm = unsorted_sub_index(ipvt); - indperminv = unsorted_sub_index(ipvtinv); - _wsvector w(mat_ncols(A)); - _rsvector ww(mat_ncols(A)); - - T tmp = T(0); - gmm::clear(L); gmm::clear(U); - R prec = default_tol(R()); - R max_pivot = gmm::abs(A(0,0)) * prec; - - for (size_type i = 0; i < n; ++i) { - - copy(sub_vector(mat_const_row(A, i), indperm), w); - double norm_row = gmm::vect_norm2(mat_const_row(A, i)); - - typename _wsvector::iterator wkold = w.end(); - for (typename _wsvector::iterator wk = w.begin(); - wk != w.end() && wk->first < i; ) { - size_type k = wk->first; - tmp = (wk->second) * indiag[k]; - if (gmm::abs(tmp) < eps * norm_row) w.erase(k); - else { wk->second += tmp; gmm::add(scaled(mat_row(U, k), -tmp), w); } - if (wkold == w.end()) wk = w.begin(); else { wk = wkold; ++wk; } - if (wk != w.end() && wk->first == k) - { if (wkold == w.end()) wkold = w.begin(); else ++wkold; ++wk; } - } - - gmm::clean(w, eps * norm_row); - gmm::copy(w, ww); - - std::sort(ww.begin(), ww.end(), elt_rsvector_value_less_()); - typename _rsvector::const_iterator wit = ww.begin(), wite = ww.end(); - size_type ip = size_type(-1); - - for (; wit != wite; ++wit) - if (wit->c >= i) { ip = wit->c; tmp = wit->e; break; } - if (ip == size_type(-1) || gmm::abs(tmp) <= max_pivot) - { GMM_WARNING2("pivot " << i << " too small"); ip=i; ww[i]=tmp=T(1); } - max_pivot = std::max(max_pivot, std::min(gmm::abs(tmp) * prec, R(1))); - indiag[i] = T(1) / tmp; - wit = ww.begin(); - - size_type nnl = 0, nnu = 0; - L[i].base_resize(K); U[i].base_resize(K+1); - typename _rsvector::iterator witL = L[i].begin(), witU = U[i].begin(); - for (; wit != wite; ++wit) { - if (wit->c < i) { if (nnl < K) { *witL++ = *wit; ++nnl; } } - else if (nnu < K || wit->c == i) - { CU(i, wit->c) = wit->e; *witU++ = *wit; ++nnu; } - } - L[i].base_resize(nnl); U[i].base_resize(nnu); - std::sort(L[i].begin(), L[i].end()); - std::sort(U[i].begin(), U[i].end()); - - if (ip != i) { - typename _wsvector::const_iterator iti = CU.col(i).begin(); - typename _wsvector::const_iterator itie = CU.col(i).end(); - typename _wsvector::const_iterator itp = CU.col(ip).begin(); - typename _wsvector::const_iterator itpe = CU.col(ip).end(); - - while (iti != itie && itp != itpe) { - if (iti->first < itp->first) - { U.row(iti->first).swap_indices(i, ip); ++iti; } - else if (iti->first > itp->first) - { U.row(itp->first).swap_indices(i,ip);++itp; } - else - { U.row(iti->first).swap_indices(i, ip); ++iti; ++itp; } - } - - for( ; iti != itie; ++iti) U.row(iti->first).swap_indices(i, ip); - for( ; itp != itpe; ++itp) U.row(itp->first).swap_indices(i, ip); - - CU.swap_col(i, ip); - - indperm.swap(i, ip); - indperminv.swap(ipvt[i], ipvt[ip]); - std::swap(ipvtinv[ipvt[i]], ipvtinv[ipvt[ip]]); - std::swap(ipvt[i], ipvt[ip]); - } - } - } - - template - void ilutp_precond::do_ilutp(const Matrix& A, col_major) { - do_ilutp(gmm::transposed(A), row_major()); - invert = true; - } - - template inline - void mult(const ilutp_precond& P, const V1 &v1, V2 &v2) { - if (P.invert) { - gmm::copy(gmm::sub_vector(v1, P.indperm), v2); - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - else { - gmm::copy(v1, P.temporary); - gmm::lower_tri_solve(P.L, P.temporary, true); - gmm::upper_tri_solve(P.U, P.temporary, false); - gmm::copy(gmm::sub_vector(P.temporary, P.indperminv), v2); - } - } - - template inline - void transposed_mult(const ilutp_precond& P,const V1 &v1,V2 &v2) { - if (P.invert) { - gmm::copy(v1, P.temporary); - gmm::lower_tri_solve(P.L, P.temporary, true); - gmm::upper_tri_solve(P.U, P.temporary, false); - gmm::copy(gmm::sub_vector(P.temporary, P.indperminv), v2); - } - else { - gmm::copy(gmm::sub_vector(v1, P.indperm), v2); - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - } - - template inline - void left_mult(const ilutp_precond& P, const V1 &v1, V2 &v2) { - if (P.invert) { - gmm::copy(gmm::sub_vector(v1, P.indperm), v2); - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - } - else { - copy(v1, v2); - gmm::lower_tri_solve(P.L, v2, true); - } - } - - template inline - void right_mult(const ilutp_precond& P, const V1 &v1, V2 &v2) { - if (P.invert) { - copy(v1, v2); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - else { - copy(v1, P.temporary); - gmm::upper_tri_solve(P.U, P.temporary, false); - gmm::copy(gmm::sub_vector(P.temporary, P.indperminv), v2); - } - } - - template inline - void transposed_left_mult(const ilutp_precond& P, const V1 &v1, - V2 &v2) { - if (P.invert) { - copy(v1, P.temporary); - gmm::upper_tri_solve(P.U, P.temporary, false); - gmm::copy(gmm::sub_vector(P.temporary, P.indperminv), v2); - } - else { - copy(v1, v2); - gmm::upper_tri_solve(gmm::transposed(P.L), v2, true); - } - } - - template inline - void transposed_right_mult(const ilutp_precond& P, const V1 &v1, - V2 &v2) { - if (P.invert) { - copy(v1, v2); - gmm::lower_tri_solve(P.L, v2, true); - } - else { - gmm::copy(gmm::sub_vector(v1, P.indperm), v2); - gmm::lower_tri_solve(gmm::transposed(P.U), v2, false); - } - } - -} - -#endif - diff --git a/include/gmm/gmm_precond_mr_approx_inverse.h b/include/gmm/gmm_precond_mr_approx_inverse.h deleted file mode 100644 index 498ede92aac..00000000000 --- a/include/gmm/gmm_precond_mr_approx_inverse.h +++ /dev/null @@ -1,148 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 1997-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of approximate_inverse.h from ITL. -// See http://osl.iu.edu/research/itl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -/**@file gmm_precond_mr_approx_inverse.h - @author Andrew Lumsdaine - @author Lie-Quan Lee - @author Yves Renard - @date June 5, 2003. - @brief Approximate inverse via MR iteration. -*/ - -#ifndef GMM_PRECOND_MR_APPROX_INVERSE_H -#define GMM_PRECOND_MR_APPROX_INVERSE_H - - -#include "gmm_precond.h" - -namespace gmm { - - /** Approximate inverse via MR iteration (see P301 of Saad book). - */ - template - struct mr_approx_inverse_precond { - - typedef typename linalg_traits::value_type value_type; - typedef typename number_traits::magnitude_type magnitude_type; - typedef typename principal_orientation_type::sub_orientation>::potype sub_orientation; - typedef wsvector VVector; - typedef col_matrix MMatrix; - - MMatrix M; - size_type nb_it; - magnitude_type threshold; - - void build_with(const Matrix& A); - mr_approx_inverse_precond(const Matrix& A, size_type nb_it_, - magnitude_type threshold_) - : M(mat_nrows(A), mat_ncols(A)) - { threshold = threshold_; nb_it = nb_it_; build_with(A); } - mr_approx_inverse_precond(void) - { threshold = magnitude_type(1E-7); nb_it = 5; } - mr_approx_inverse_precond(size_type nb_it_, magnitude_type threshold_) - { threshold = threshold_; nb_it = nb_it_; } - const MMatrix &approx_inverse(void) const { return M; } - }; - - template inline - void mult(const mr_approx_inverse_precond& P, const V1 &v1, V2 &v2) - { mult(P.M, v1, v2); } - - template inline - void transposed_mult(const mr_approx_inverse_precond& P, - const V1 &v1,V2 &v2) - { mult(gmm::conjugated(P.M), v1, v2); } - - template - void mr_approx_inverse_precond::build_with(const Matrix& A) { - gmm::resize(M, mat_nrows(A), mat_ncols(A)); - typedef value_type T; - typedef magnitude_type R; - VVector m(mat_ncols(A)),r(mat_ncols(A)),ei(mat_ncols(A)),Ar(mat_ncols(A)); - T alpha = mat_trace(A)/ mat_euclidean_norm_sqr(A); - if (alpha == T(0)) alpha = T(1); - - for (size_type i = 0; i < mat_nrows(A); ++i) { - gmm::clear(m); gmm::clear(ei); - m[i] = alpha; - ei[i] = T(1); - - for (size_type j = 0; j < nb_it; ++j) { - gmm::mult(A, gmm::scaled(m, T(-1)), r); - gmm::add(ei, r); - gmm::mult(A, r, Ar); - T nAr = vect_sp(Ar,Ar); - if (gmm::abs(nAr) > R(0)) { - gmm::add(gmm::scaled(r, gmm::safe_divide(vect_sp(r, Ar), vect_sp(Ar, Ar))), m); - gmm::clean(m, threshold * gmm::vect_norm2(m)); - } else gmm::clear(m); - } - if (gmm::vect_norm2(m) == R(0)) m[i] = alpha; - gmm::copy(m, M.col(i)); - } - } -} - -#endif - diff --git a/include/gmm/gmm_real_part.h b/include/gmm/gmm_real_part.h deleted file mode 100644 index d8efb8dfe7c..00000000000 --- a/include/gmm/gmm_real_part.h +++ /dev/null @@ -1,604 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_real_part.h - @author Yves Renard - @date September 18, 2003. - @brief extract the real/imaginary part of vectors/matrices -*/ -#ifndef GMM_REAL_PART_H -#define GMM_REAL_PART_H - -#include "gmm_def.h" -#include "gmm_vector.h" - -namespace gmm { - - struct linalg_real_part {}; - struct linalg_imag_part {}; - template struct which_part {}; - - template typename number_traits::magnitude_type - real_or_imag_part(C x, linalg_real_part) { return gmm::real(x); } - template typename number_traits::magnitude_type - real_or_imag_part(C x, linalg_imag_part) { return gmm::imag(x); } - template C - complex_from(T x, C y, OP op, linalg_real_part) { return std::complex(op(std::real(y), x), std::imag(y)); } - template C - complex_from(T x, C y, OP op,linalg_imag_part) { return std::complex(std::real(y), op(std::imag(y), x)); } - - template struct project2nd { - T operator()(T , T b) const { return b; } - }; - - template class ref_elt_vector > { - - R r; - - public : - - operator T() const { return real_or_imag_part(std::complex(r), PART()); } - ref_elt_vector(R r_) : r(r_) {} - inline ref_elt_vector &operator =(T v) - { r = complex_from(v, std::complex(r), gmm::project2nd(), PART()); return *this; } - inline bool operator ==(T v) const { return (r == v); } - inline bool operator !=(T v) const { return (r != v); } - inline ref_elt_vector &operator +=(T v) - { r = complex_from(v, std::complex(r), std::plus(), PART()); return *this; } - inline ref_elt_vector &operator -=(T v) - { r = complex_from(v, std::complex(r), std::minus(), PART()); return *this; } - inline ref_elt_vector &operator /=(T v) - { r = complex_from(v, std::complex(r), std::divides(), PART()); return *this; } - inline ref_elt_vector &operator *=(T v) - { r = complex_from(v, std::complex(r), std::multiplies(), PART()); return *this; } - inline ref_elt_vector &operator =(const ref_elt_vector &re) - { *this = T(re); return *this; } - T operator +() { return T(*this); } // necessary for unknow reason - T operator -() { return -T(*this); } // necessary for unknow reason - T operator +(T v) { return T(*this)+ v; } // necessary for unknow reason - T operator -(T v) { return T(*this)- v; } // necessary for unknow reason - T operator *(T v) { return T(*this)* v; } // necessary for unknow reason - T operator /(T v) { return T(*this)/ v; } // necessary for unknow reason - }; - - template struct ref_or_value_type { - template - static W r(const T &x, linalg_real_part, W) { - return gmm::real(x); - } - template - static W r(const T &x, linalg_imag_part, W) { - return gmm::imag(x); - } - }; - - template - struct ref_or_value_type > > { - template - static const T &r(const T &x, linalg_real_part, W) - { return x; } - template - static const T &r(const T &x, linalg_imag_part, W) { - return x; - } - template - static T &r(T &x, linalg_real_part, W) - { return x; } - template - static T &r(T &x, linalg_imag_part, W) { - return x; - } - }; - - - /* ********************************************************************* */ - /* Reference to the real part of (complex) vectors */ - /* ********************************************************************* */ - - template - struct part_vector_iterator { - typedef typename std::iterator_traits::value_type vtype; - typedef typename gmm::number_traits::magnitude_type value_type; - typedef value_type *pointer; - typedef ref_elt_vector::reference, PART> > reference; - typedef typename std::iterator_traits::difference_type difference_type; - typedef typename std::iterator_traits::iterator_category - iterator_category; - - IT it; - - part_vector_iterator(void) {} - explicit part_vector_iterator(const IT &i) : it(i) {} - part_vector_iterator(const part_vector_iterator &i) : it(i.it) {} - - - size_type index(void) const { return it.index(); } - part_vector_iterator operator ++(int) - { part_vector_iterator tmp = *this; ++it; return tmp; } - part_vector_iterator operator --(int) - { part_vector_iterator tmp = *this; --it; return tmp; } - part_vector_iterator &operator ++() { ++it; return *this; } - part_vector_iterator &operator --() { --it; return *this; } - part_vector_iterator &operator +=(difference_type i) - { it += i; return *this; } - part_vector_iterator &operator -=(difference_type i) - { it -= i; return *this; } - part_vector_iterator operator +(difference_type i) const - { part_vector_iterator itb = *this; return (itb += i); } - part_vector_iterator operator -(difference_type i) const - { part_vector_iterator itb = *this; return (itb -= i); } - difference_type operator -(const part_vector_iterator &i) const - { return difference_type(it - i.it); } - - reference operator *() const { return reference(*it); } - reference operator [](size_type ii) const { return reference(it[ii]); } - - bool operator ==(const part_vector_iterator &i) const - { return (i.it == it); } - bool operator !=(const part_vector_iterator &i) const - { return (i.it != it); } - bool operator < (const part_vector_iterator &i) const - { return (it < i.it); } - }; - - - template struct part_vector { - typedef part_vector this_type; - typedef typename std::iterator_traits::value_type V; - typedef V * CPT; - typedef typename select_ref::const_iterator, - typename linalg_traits::iterator, PT>::ref_type iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - size_type size_; - - size_type size(void) const { return size_; } - - reference operator[](size_type i) const { - return reference(ref_or_value_type::r( - linalg_traits::access(origin, begin_, end_, i), - PART(), value_type())); - } - - part_vector(V &v) - : begin_(vect_begin(v)), end_(vect_end(v)), - origin(linalg_origin(v)), size_(gmm::vect_size(v)) {} - part_vector(const V &v) - : begin_(vect_begin(const_cast(v))), - end_(vect_end(const_cast(v))), - origin(linalg_origin(const_cast(v))), size_(gmm::vect_size(v)) {} - part_vector() {} - part_vector(const part_vector &cr) - : begin_(cr.begin_),end_(cr.end_),origin(cr.origin), size_(cr.size_) {} - }; - - template inline - void set_to_begin(part_vector_iterator &it, - ORG o, part_vector *, linalg_modifiable) { - typedef part_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_begin(it.it, o, typename linalg_traits::pV(), ref_t()); - } - template inline - void set_to_begin(part_vector_iterator &it, - ORG o, const part_vector *, linalg_modifiable) { - typedef part_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_begin(it.it, o, typename linalg_traits::pV(), ref_t()); - } - template inline - void set_to_end(part_vector_iterator &it, - ORG o, part_vector *, linalg_modifiable) { - typedef part_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_end(it.it, o, typename linalg_traits::pV(), ref_t()); - } - template inline - void set_to_end(part_vector_iterator &it, - ORG o, const part_vector *, - linalg_modifiable) { - typedef part_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_end(it.it, o, typename linalg_traits::pV(), ref_t()); - } - - template - struct linalg_traits > { - typedef part_vector this_type; - typedef this_type * pthis_type; - typedef PT pV; - typedef typename std::iterator_traits::value_type V; - typedef typename linalg_traits::index_sorted index_sorted; - typedef typename linalg_traits::is_reference V_reference; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename linalg_traits::value_type vtype; - typedef typename number_traits::magnitude_type value_type; - typedef typename select_ref::reference, - PART> >, PT>::ref_type reference; - typedef typename select_ref::const_iterator, - typename linalg_traits::iterator, PT>::ref_type pre_iterator; - typedef typename select_ref, - PT>::ref_type iterator; - typedef part_vector_iterator::const_iterator, - pre_iterator, PART> const_iterator; - typedef typename linalg_traits::storage_type storage_type; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { - iterator it; it.it = v.begin_; - if (!is_const_reference(is_reference()) && is_sparse(storage_type())) - set_to_begin(it, v.origin, pthis_type(), is_reference()); - return it; - } - static const_iterator begin(const this_type &v) { - const_iterator it(v.begin_); - if (!is_const_reference(is_reference()) && is_sparse(storage_type())) - { set_to_begin(it, v.origin, pthis_type(), is_reference()); } - return it; - } - static iterator end(this_type &v) { - iterator it(v.end_); - if (!is_const_reference(is_reference()) && is_sparse(storage_type())) - set_to_end(it, v.origin, pthis_type(), is_reference()); - return it; - } - static const_iterator end(const this_type &v) { - const_iterator it(v.end_); - if (!is_const_reference(is_reference()) && is_sparse(storage_type())) - set_to_end(it, v.origin, pthis_type(), is_reference()); - return it; - } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - - static void clear(origin_type* o, const iterator &begin_, - const iterator &end_, abstract_sparse) { - std::deque ind; - iterator it = begin_; - for (; it != end_; ++it) ind.push_front(it.index()); - for (; !(ind.empty()); ind.pop_back()) - access(o, begin_, end_, ind.back()) = value_type(0); - } - static void clear(origin_type* o, const iterator &begin_, - const iterator &end_, abstract_skyline) { - clear(o, begin_, end_, abstract_sparse()); - } - static void clear(origin_type* o, const iterator &begin_, - const iterator &end_, abstract_dense) { - for (iterator it = begin_; it != end_; ++it) *it = value_type(0); - } - - static void clear(origin_type* o, const iterator &begin_, - const iterator &end_) - { clear(o, begin_, end_, storage_type()); } - static void do_clear(this_type &v) { clear(v.origin, begin(v), end(v)); } - static value_type access(const origin_type *o, const const_iterator &it, - const const_iterator &ite, size_type i) { - return real_or_imag_part(linalg_traits::access(o, it.it, ite.it,i), - PART()); - } - static reference access(origin_type *o, const iterator &it, - const iterator &ite, size_type i) - { return reference(linalg_traits::access(o, it.it, ite.it,i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const part_vector& m) - { gmm::write(o,m); return o; } - - - /* ********************************************************************* */ - /* Reference to the real or imaginary part of (complex) matrices */ - /* ********************************************************************* */ - - - template struct part_row_ref { - - typedef part_row_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef M * CPT; - typedef typename std::iterator_traits::reference ref_M; - typedef typename select_ref - ::const_row_iterator, typename linalg_traits - ::row_iterator, PT>::ref_type iterator; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - size_type nr, nc; - - part_row_ref(ref_M m) - : begin_(mat_row_begin(m)), end_(mat_row_end(m)), - origin(linalg_origin(m)), nr(mat_nrows(m)), nc(mat_ncols(m)) {} - - part_row_ref(const part_row_ref &cr) : - begin_(cr.begin_),end_(cr.end_), origin(cr.origin),nr(cr.nr),nc(cr.nc) {} - - reference operator()(size_type i, size_type j) const { - return reference(ref_or_value_type::r( - linalg_traits::access(begin_+j, i), - PART(), value_type())); - } - }; - - template - struct linalg_traits > { - typedef part_row_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type vtype; - typedef typename number_traits::magnitude_type value_type; - typedef typename linalg_traits::storage_type storage_type; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_col_iterator; - typedef typename linalg_traits::const_sub_row_type - pre_const_sub_row_type; - typedef typename linalg_traits::sub_row_type pre_sub_row_type; - typedef part_vector - const_sub_row_type; - typedef typename select_ref, PT>::ref_type sub_row_type; - typedef typename linalg_traits::const_row_iterator const_row_iterator; - typedef typename select_ref::row_iterator, PT>::ref_type row_iterator; - typedef typename select_ref< - typename linalg_traits::reference, - typename linalg_traits::reference, - PT>::ref_type reference; - typedef row_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type ncols(const this_type &v) { return v.nc; } - static size_type nrows(const this_type &v) { return v.nr; } - static const_sub_row_type row(const const_row_iterator &it) - { return const_sub_row_type(linalg_traits::row(it)); } - static sub_row_type row(const row_iterator &it) - { return sub_row_type(linalg_traits::row(it)); } - static row_iterator row_begin(this_type &m) { return m.begin_; } - static row_iterator row_end(this_type &m) { return m.end_; } - static const_row_iterator row_begin(const this_type &m) - { return m.begin_; } - static const_row_iterator row_end(const this_type &m) { return m.end_; } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void do_clear(this_type &v); - static value_type access(const const_row_iterator &itrow, size_type i) - { return real_or_imag_part(linalg_traits::access(itrow, i), PART()); } - static reference access(const row_iterator &itrow, size_type i) { - return reference(ref_or_value_type::r( - linalg_traits::access(itrow, i), - PART(), value_type())); - } - }; - - template - void linalg_traits >::do_clear(this_type &v) { - row_iterator it = mat_row_begin(v), ite = mat_row_end(v); - for (; it != ite; ++it) clear(row(it)); - } - - template std::ostream &operator << - (std::ostream &o, const part_row_ref& m) - { gmm::write(o,m); return o; } - - template struct part_col_ref { - - typedef part_col_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef M * CPT; - typedef typename std::iterator_traits::reference ref_M; - typedef typename select_ref - ::const_col_iterator, typename linalg_traits - ::col_iterator, PT>::ref_type iterator; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - size_type nr, nc; - - part_col_ref(ref_M m) - : begin_(mat_col_begin(m)), end_(mat_col_end(m)), - origin(linalg_origin(m)), nr(mat_nrows(m)), nc(mat_ncols(m)) {} - - part_col_ref(const part_col_ref &cr) : - begin_(cr.begin_),end_(cr.end_), origin(cr.origin),nr(cr.nr),nc(cr.nc) {} - - reference operator()(size_type i, size_type j) const { - return reference(ref_or_value_type::r( - linalg_traits::access(begin_+j, i), - PART(), value_type())); - } - }; - - template - struct linalg_traits > { - typedef part_col_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type vtype; - typedef typename number_traits::magnitude_type value_type; - typedef typename linalg_traits::storage_type storage_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_row_iterator; - typedef typename linalg_traits::const_sub_col_type - pre_const_sub_col_type; - typedef typename linalg_traits::sub_col_type pre_sub_col_type; - typedef part_vector - const_sub_col_type; - typedef typename select_ref, PT>::ref_type sub_col_type; - typedef typename linalg_traits::const_col_iterator const_col_iterator; - typedef typename select_ref::col_iterator, PT>::ref_type col_iterator; - typedef typename select_ref< - typename linalg_traits::reference, - typename linalg_traits::reference, - PT>::ref_type reference; - typedef col_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type nrows(const this_type &v) { return v.nr; } - static size_type ncols(const this_type &v) { return v.nc; } - static const_sub_col_type col(const const_col_iterator &it) - { return const_sub_col_type(linalg_traits::col(it)); } - static sub_col_type col(const col_iterator &it) - { return sub_col_type(linalg_traits::col(it)); } - static col_iterator col_begin(this_type &m) { return m.begin_; } - static col_iterator col_end(this_type &m) { return m.end_; } - static const_col_iterator col_begin(const this_type &m) - { return m.begin_; } - static const_col_iterator col_end(const this_type &m) { return m.end_; } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void do_clear(this_type &v); - static value_type access(const const_col_iterator &itcol, size_type i) - { return real_or_imag_part(linalg_traits::access(itcol, i), PART()); } - static reference access(const col_iterator &itcol, size_type i) { - return reference(ref_or_value_type::r( - linalg_traits::access(itcol, i), - PART(), value_type())); - } - }; - - template - void linalg_traits >::do_clear(this_type &v) { - col_iterator it = mat_col_begin(v), ite = mat_col_end(v); - for (; it != ite; ++it) clear(col(it)); - } - - template std::ostream &operator << - (std::ostream &o, const part_col_ref& m) - { gmm::write(o,m); return o; } - - - - - - -template - struct part_return_ { - typedef abstract_null_type return_type; - }; - template - struct part_return_ { - typedef typename std::iterator_traits::value_type L; - typedef typename select_return, - part_row_ref< L *, PART>, PT>::return_type return_type; - }; - template - struct part_return_ { - typedef typename std::iterator_traits::value_type L; - typedef typename select_return, - part_col_ref, PT>::return_type return_type; - }; - - template struct part_return__{ - typedef abstract_null_type return_type; - }; - - template - struct part_return__ { - typedef typename std::iterator_traits::value_type L; - typedef typename part_return_::sub_orientation>::potype, PART, - PT>::return_type return_type; - }; - - template - struct part_return__ { - typedef typename std::iterator_traits::value_type L; - typedef typename select_return, - part_vector, PT>::return_type return_type; - }; - - template struct part_return { - typedef typename std::iterator_traits::value_type L; - typedef typename part_return__::linalg_type>::return_type return_type; - }; - - template inline - typename part_return::return_type - real_part(const L &l) { - return typename part_return::return_type - (linalg_cast(const_cast(l))); - } - - template inline - typename part_return::return_type - real_part(L &l) { - return typename part_return::return_type(linalg_cast(l)); - } - - template inline - typename part_return::return_type - imag_part(const L &l) { - return typename part_return::return_type - (linalg_cast(const_cast(l))); - } - - template inline - typename part_return::return_type - imag_part(L &l) { - return typename part_return::return_type(linalg_cast(l)); - } - - - -} - -#endif // GMM_REAL_PART_H diff --git a/include/gmm/gmm_ref.h b/include/gmm/gmm_ref.h deleted file mode 100644 index fc3ca6d50a1..00000000000 --- a/include/gmm/gmm_ref.h +++ /dev/null @@ -1,525 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2000-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - - -#ifndef GMM_REF_H__ -#define GMM_REF_H__ - -/** @file gmm_ref.h - @author Yves Renard - @date August 26, 2000. - * @brief Provide some simple pseudo-containers. - * - * WARNING : modifiying the container infirm the validity of references. - */ - - -#include -#include "gmm_except.h" - -namespace gmm { - - /* ********************************************************************* */ - /* Simple reference. */ - /* ********************************************************************* */ - - template class tab_ref { - - protected : - - ITER begin_, end_; - - public : - - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::pointer const_pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::reference const_reference; - typedef typename std::iterator_traits::difference_type - difference_type; - typedef ITER iterator; - typedef ITER const_iterator; - typedef std::reverse_iterator const_reverse_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef size_t size_type; - - bool empty(void) const { return begin_ == end_; } - size_type size(void) const { return end_ - begin_; } - - const iterator &begin(void) { return begin_; } - const const_iterator &begin(void) const { return begin_; } - const iterator &end(void) { return end_; } - const const_iterator &end(void) const { return end_; } - reverse_iterator rbegin(void) { return reverse_iterator(end()); } - const_reverse_iterator rbegin(void) const - { return const_reverse_iterator(end()); } - reverse_iterator rend(void) { return reverse_iterator(begin()); } - const_reverse_iterator rend(void) const - { return const_reverse_iterator(begin()); } - - reference front(void) { return *begin(); } - const_reference front(void) const { return *begin(); } - reference back(void) { return *(--(end())); } - const_reference back(void) const { return *(--(end())); } - void pop_front(void) { ++begin_; } - - const_reference operator [](size_type ii) const { return *(begin_ + ii);} - reference operator [](size_type ii) { return *(begin_ + ii); } - - tab_ref(void) {} - tab_ref(const ITER &b, const ITER &e) : begin_(b), end_(e) {} - }; - - - /* ********************************************************************* */ - /* Reference with index. */ - /* ********************************************************************* */ - -// template struct tab_ref_index_iterator_ -// : public dynamic_array::const_iterator -// { -// typedef typename std::iterator_traits::value_type value_type; -// typedef typename std::iterator_traits::pointer pointer; -// typedef typename std::iterator_traits::reference reference; -// typedef typename std::iterator_traits::difference_type -// difference_type; -// typedef std::random_access_iterator_tag iterator_category; -// typedef size_t size_type; -// typedef dynamic_array::const_iterator dnas_iterator_; -// typedef tab_ref_index_iterator_ iterator; - - -// ITER piter; - -// iterator operator ++(int) -// { iterator tmp = *this; ++(*((dnas_iterator_ *)(this))); return tmp; } -// iterator operator --(int) -// { iterator tmp = *this; --(*((dnas_iterator_ *)(this))); return tmp; } -// iterator &operator ++() -// { ++(*((dnas_iterator_ *)(this))); return *this; } -// iterator &operator --() -// { --(*((dnas_iterator_ *)(this))); return *this; } -// iterator &operator +=(difference_type i) -// { (*((dnas_iterator_ *)(this))) += i; return *this; } -// iterator &operator -=(difference_type i) -// { (*((dnas_iterator_ *)(this))) -= i; return *this; } -// iterator operator +(difference_type i) const -// { iterator it = *this; return (it += i); } -// iterator operator -(difference_type i) const -// { iterator it = *this; return (it -= i); } -// difference_type operator -(const iterator &i) const -// { return *((dnas_iterator_ *)(this)) - *((dnas_iterator_ *)(&i)); } - -// reference operator *() const -// { return *(piter + *((*((dnas_iterator_ *)(this))))); } -// reference operator [](int ii) -// { return *(piter + *((*((dnas_iterator_ *)(this+ii))))); } - -// bool operator ==(const iterator &i) const -// { -// return ((piter) == ((i.piter)) -// && *((dnas_iterator_ *)(this)) == *((*((dnas_iterator_ *)(this))))); -// } -// bool operator !=(const iterator &i) const -// { return !(i == *this); } -// bool operator < (const iterator &i) const -// { -// return ((piter) == ((i.piter)) -// && *((dnas_iterator_ *)(this)) < *((*((dnas_iterator_ *)(this))))); -// } - -// tab_ref_index_iterator_(void) {} -// tab_ref_index_iterator_(const ITER &iter, const dnas_iterator_ &dnas_iter) -// : dnas_iterator_(dnas_iter), piter(iter) {} -// }; - - -// template class tab_ref_index -// { -// public : - -// typedef typename std::iterator_traits::value_type value_type; -// typedef typename std::iterator_traits::pointer pointer; -// typedef typename std::iterator_traits::pointer const_pointer; -// typedef typename std::iterator_traits::reference reference; -// typedef typename std::iterator_traits::reference const_reference; -// typedef typename std::iterator_traits::difference_type -// difference_type; -// typedef size_t size_type; -// typedef tab_ref_index_iterator_ iterator; -// typedef iterator const_iterator; -// typedef std::reverse_iterator const_reverse_iterator; -// typedef std::reverse_iterator reverse_iterator; - -// protected : - -// ITER begin_; -// dynamic_array index_; - -// public : - -// bool empty(void) const { return index_.empty(); } -// size_type size(void) const { return index_.size(); } - - -// iterator begin(void) { return iterator(begin_, index_.begin()); } -// const_iterator begin(void) const -// { return iterator(begin_, index_.begin()); } -// iterator end(void) { return iterator(begin_, index_.end()); } -// const_iterator end(void) const { return iterator(begin_, index_.end()); } -// reverse_iterator rbegin(void) { return reverse_iterator(end()); } -// const_reverse_iterator rbegin(void) const -// { return const_reverse_iterator(end()); } -// reverse_iterator rend(void) { return reverse_iterator(begin()); } -// const_reverse_iterator rend(void) const -// { return const_reverse_iterator(begin()); } - - -// reference front(void) { return *(begin_ +index_[0]); } -// const_reference front(void) const { return *(begin_ +index_[0]); } -// reference back(void) { return *(--(end())); } -// const_reference back(void) const { return *(--(end())); } - -// tab_ref_index(void) {} -// tab_ref_index(const ITER &b, const dynamic_array &ind) -// { begin_ = b; index_ = ind; } - -// // to be changed in a const_reference ? -// value_type operator [](size_type ii) const -// { return *(begin_ + index_[ii]);} -// reference operator [](size_type ii) { return *(begin_ + index_[ii]); } - -// }; - - - /// iterator over a gmm::tab_ref_index_ref - template - struct tab_ref_index_ref_iterator_ - { - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::difference_type - difference_type; - typedef std::random_access_iterator_tag iterator_category; - typedef tab_ref_index_ref_iterator_ iterator; - typedef size_t size_type; - - ITER piter; - ITER_INDEX iter_index; - - iterator operator ++(int) - { iterator tmp = *this; ++iter_index; return tmp; } - iterator operator --(int) - { iterator tmp = *this; --iter_index; return tmp; } - iterator &operator ++() { ++iter_index; return *this; } - iterator &operator --() { --iter_index; return *this; } - iterator &operator +=(difference_type i) - { iter_index += i; return *this; } - iterator &operator -=(difference_type i) - { iter_index -= i; return *this; } - iterator operator +(difference_type i) const - { iterator it = *this; return (it += i); } - iterator operator -(difference_type i) const - { iterator it = *this; return (it -= i); } - difference_type operator -(const iterator &i) const - { return iter_index - i.iter_index; } - - reference operator *() const - { return *(piter + *iter_index); } - reference operator [](size_type ii) const - { return *(piter + *(iter_index+ii)); } - - bool operator ==(const iterator &i) const - { return ((piter) == ((i.piter)) && iter_index == i.iter_index); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const - { return ((piter) == ((i.piter)) && iter_index < i.iter_index); } - - tab_ref_index_ref_iterator_(void) {} - tab_ref_index_ref_iterator_(const ITER &iter, - const ITER_INDEX &dnas_iter) - : piter(iter), iter_index(dnas_iter) {} - - }; - - /** - convenience template function for quick obtention of a indexed iterator - without having to specify its (long) typename - */ - template - tab_ref_index_ref_iterator_ - index_ref_iterator(ITER it, ITER_INDEX it_i) { - return tab_ref_index_ref_iterator_(it, it_i); - } - - /** indexed array reference (given a container X, and a set of indexes I, - this class provides a pseudo-container Y such that - @code Y[i] = X[I[i]] @endcode - */ - template class tab_ref_index_ref { - public : - - typedef std::iterator_traits traits_type; - typedef typename traits_type::value_type value_type; - typedef typename traits_type::pointer pointer; - typedef typename traits_type::pointer const_pointer; - typedef typename traits_type::reference reference; - typedef typename traits_type::reference const_reference; - typedef typename traits_type::difference_type difference_type; - typedef size_t size_type; - typedef tab_ref_index_ref_iterator_ iterator; - typedef iterator const_iterator; - typedef std::reverse_iterator const_reverse_iterator; - typedef std::reverse_iterator reverse_iterator; - - protected : - - ITER begin_; - ITER_INDEX index_begin_, index_end_; - - public : - - bool empty(void) const { return index_begin_ == index_end_; } - size_type size(void) const { return index_end_ - index_begin_; } - - iterator begin(void) { return iterator(begin_, index_begin_); } - const_iterator begin(void) const - { return iterator(begin_, index_begin_); } - iterator end(void) { return iterator(begin_, index_end_); } - const_iterator end(void) const { return iterator(begin_, index_end_); } - reverse_iterator rbegin(void) { return reverse_iterator(end()); } - const_reverse_iterator rbegin(void) const - { return const_reverse_iterator(end()); } - reverse_iterator rend(void) { return reverse_iterator(begin()); } - const_reverse_iterator rend(void) const - { return const_reverse_iterator(begin()); } - - reference front(void) { return *(begin_ + *index_begin_); } - const_reference front(void) const { return *(begin_ + *index_begin_); } - reference back(void) { return *(--(end())); } - const_reference back(void) const { return *(--(end())); } - void pop_front(void) { ++index_begin_; } - - tab_ref_index_ref(void) {} - tab_ref_index_ref(const ITER &b, const ITER_INDEX &bi, - const ITER_INDEX &ei) - : begin_(b), index_begin_(bi), index_end_(ei) {} - - // to be changed in a const_reference ? - const_reference operator [](size_type ii) const - { return *(begin_ + index_begin_[ii]);} - reference operator [](size_type ii) - { return *(begin_ + index_begin_[ii]); } - - }; - - - /* ********************************************************************* */ - /* Reference on regularly spaced elements. */ - /* ********************************************************************* */ - - template struct tab_ref_reg_spaced_iterator_ { - - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::difference_type - difference_type; - typedef typename std::iterator_traits::iterator_category - iterator_category; - typedef size_t size_type; - typedef tab_ref_reg_spaced_iterator_ iterator; - - ITER it; - size_type N, i; - - iterator operator ++(int) { iterator tmp = *this; i++; return tmp; } - iterator operator --(int) { iterator tmp = *this; i--; return tmp; } - iterator &operator ++() { i++; return *this; } - iterator &operator --() { i--; return *this; } - iterator &operator +=(difference_type ii) { i+=ii; return *this; } - iterator &operator -=(difference_type ii) { i-=ii; return *this; } - iterator operator +(difference_type ii) const - { iterator itt = *this; return (itt += ii); } - iterator operator -(difference_type ii) const - { iterator itt = *this; return (itt -= ii); } - difference_type operator -(const iterator &ii) const - { return (N ? (it - ii.it) / N : 0) + i - ii.i; } - - reference operator *() const { return *(it + i*N); } - reference operator [](size_type ii) const { return *(it + (i+ii)*N); } - - bool operator ==(const iterator &ii) const - { return (*this - ii) == difference_type(0); } - bool operator !=(const iterator &ii) const - { return (*this - ii) != difference_type(0); } - bool operator < (const iterator &ii) const - { return (*this - ii) < difference_type(0); } - - tab_ref_reg_spaced_iterator_(void) {} - tab_ref_reg_spaced_iterator_(const ITER &iter, size_type n, size_type ii) - : it(iter), N(n), i(ii) { } - - }; - - /** - convenience template function for quick obtention of a strided iterator - without having to specify its (long) typename - */ - template tab_ref_reg_spaced_iterator_ - reg_spaced_iterator(ITER it, size_t stride) { - return tab_ref_reg_spaced_iterator_(it, stride); - } - - /** - provide a "strided" view a of container - */ - template class tab_ref_reg_spaced { - public : - - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::pointer const_pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::reference const_reference; - typedef typename std::iterator_traits::difference_type - difference_type; - typedef size_t size_type; - typedef tab_ref_reg_spaced_iterator_ iterator; - typedef iterator const_iterator; - typedef std::reverse_iterator const_reverse_iterator; - typedef std::reverse_iterator reverse_iterator; - - protected : - - ITER begin_; - size_type N, size_; - - public : - - bool empty(void) const { return size_ == 0; } - size_type size(void) const { return size_; } - - iterator begin(void) { return iterator(begin_, N, 0); } - const_iterator begin(void) const { return iterator(begin_, N, 0); } - iterator end(void) { return iterator(begin_, N, size_); } - const_iterator end(void) const { return iterator(begin_, N, size_); } - reverse_iterator rbegin(void) { return reverse_iterator(end()); } - const_reverse_iterator rbegin(void) const - { return const_reverse_iterator(end()); } - reverse_iterator rend(void) { return reverse_iterator(begin()); } - const_reverse_iterator rend(void) const - { return const_reverse_iterator(begin()); } - - reference front(void) { return *begin_; } - const_reference front(void) const { return *begin_; } - reference back(void) { return *(begin_ + N * (size_-1)); } - const_reference back(void) const { return *(begin_ + N * (size_-1)); } - void pop_front(void) { begin_ += N; } - - tab_ref_reg_spaced(void) {} - tab_ref_reg_spaced(const ITER &b, size_type n, size_type s) - : begin_(b), N(n), size_(s) {} - - - const_reference operator [](size_type ii) const - { return *(begin_ + ii * N);} - reference operator [](size_type ii) { return *(begin_ + ii * N); } - - }; - - /// iterator over a tab_ref_with_selection - template - struct tab_ref_with_selection_iterator_ : public ITER { - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::difference_type - difference_type; - typedef std::forward_iterator_tag iterator_category; - typedef tab_ref_with_selection_iterator_ iterator; - const COND cond; - - void forward(void) { while (!(cond)(*this)) ITER::operator ++(); } - iterator &operator ++() - { ITER::operator ++(); forward(); return *this; } - iterator operator ++(int) - { iterator tmp = *this; ++(*this); return tmp; } - - tab_ref_with_selection_iterator_(void) {} - tab_ref_with_selection_iterator_(const ITER &iter, const COND c) - : ITER(iter), cond(c) {} - - }; - - /** - given a container X and a predicate P, provide pseudo-container Y - of all elements of X such that P(X[i]). - */ - template class tab_ref_with_selection { - - protected : - - ITER begin_, end_; - COND cond; - - public : - - typedef typename std::iterator_traits::value_type value_type; - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::pointer const_pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::reference const_reference; - typedef size_t size_type; - typedef tab_ref_with_selection_iterator_ iterator; - typedef iterator const_iterator; - - iterator begin(void) const - { iterator it(begin_, cond); it.forward(); return it; } - iterator end(void) const { return iterator(end_, cond); } - bool empty(void) const { return begin_ == end_; } - - value_type front(void) const { return *begin(); } - void pop_front(void) { ++begin_; begin_ = begin(); } - - COND &condition(void) { return cond; } - const COND &condition(void) const { return cond; } - - tab_ref_with_selection(void) {} - tab_ref_with_selection(const ITER &b, const ITER &e, const COND &c) - : begin_(b), end_(e), cond(c) { begin_ = begin(); } - - }; - -} - -#endif /* GMM_REF_H__ */ diff --git a/include/gmm/gmm_scaled.h b/include/gmm/gmm_scaled.h deleted file mode 100644 index a9922d8995b..00000000000 --- a/include/gmm/gmm_scaled.h +++ /dev/null @@ -1,427 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_scaled.h - @author Yves Renard - @date November 10, 2002. - @brief get a scaled view of a vector/matrix. -*/ -#ifndef GMM_SCALED_H__ -#define GMM_SCALED_H__ - -#include "gmm_def.h" - -namespace gmm { - - /* ********************************************************************* */ - /* Scaled references on vectors */ - /* ********************************************************************* */ - - template struct scaled_const_iterator { - typedef typename strongest_numeric_type::value_type, - S>::T value_type; - - typedef typename std::iterator_traits::pointer pointer; - typedef typename std::iterator_traits::reference reference; - typedef typename std::iterator_traits::difference_type difference_type; - typedef typename std::iterator_traits::iterator_category - iterator_category; - - IT it; - S r; - - scaled_const_iterator(void) {} - scaled_const_iterator(const IT &i, S x) : it(i), r(x) {} - - inline size_type index(void) const { return it.index(); } - inline scaled_const_iterator operator ++(int) - { scaled_const_iterator tmp = *this; ++it; return tmp; } - inline scaled_const_iterator operator --(int) - { scaled_const_iterator tmp = *this; --it; return tmp; } - inline scaled_const_iterator &operator ++() { ++it; return *this; } - inline scaled_const_iterator &operator --() { --it; return *this; } - inline scaled_const_iterator &operator +=(difference_type i) - { it += i; return *this; } - inline scaled_const_iterator &operator -=(difference_type i) - { it -= i; return *this; } - inline scaled_const_iterator operator +(difference_type i) const - { scaled_const_iterator itb = *this; return (itb += i); } - inline scaled_const_iterator operator -(difference_type i) const - { scaled_const_iterator itb = *this; return (itb -= i); } - inline difference_type operator -(const scaled_const_iterator &i) const - { return difference_type(it - i.it); } - - inline value_type operator *() const { return (*it) * value_type(r); } - inline value_type operator [](size_type ii) const { return it[ii] * r; } - - inline bool operator ==(const scaled_const_iterator &i) const - { return (i.it == it); } - inline bool operator !=(const scaled_const_iterator &i) const - { return (i.it != it); } - inline bool operator < (const scaled_const_iterator &i) const - { return (it < i.it); } - }; - - template struct scaled_vector_const_ref { - typedef scaled_vector_const_ref this_type; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::const_iterator iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::origin_type origin_type; - - iterator begin_, end_; - const origin_type *origin; - size_type size_; - S r; - - scaled_vector_const_ref(const V &v, S rr) - : begin_(vect_const_begin(v)), end_(vect_const_end(v)), - origin(linalg_origin(v)), size_(vect_size(v)), r(rr) {} - - reference operator[](size_type i) const - { return value_type(r) * linalg_traits::access(origin, begin_, end_, i); } - }; - - template struct linalg_traits > { - typedef scaled_vector_const_ref this_type; - typedef linalg_const is_reference; - typedef abstract_vector linalg_type; - typedef typename strongest_numeric_type::value_type>::T value_type; - typedef typename linalg_traits::origin_type origin_type; - typedef value_type reference; - typedef abstract_null_type iterator; - typedef scaled_const_iterator::const_iterator, S> - const_iterator; - typedef typename linalg_traits::storage_type storage_type; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type size(const this_type &v) { return v.size_; } - static const_iterator begin(const this_type &v) - { return const_iterator(v.begin_, v.r); } - static const_iterator end(const this_type &v) - { return const_iterator(v.end_, v.r); } - static const origin_type* origin(const this_type &v) { return v.origin; } - static value_type access(const origin_type *o, const const_iterator &it, - const const_iterator &ite, size_type i) - { return it.r * (linalg_traits::access(o, it.it, ite.it, i)); } - - }; - - template std::ostream &operator << - (std::ostream &o, const scaled_vector_const_ref& m) - { gmm::write(o,m); return o; } - - /* ********************************************************************* */ - /* Scaled references on matrices */ - /* ********************************************************************* */ - - template struct scaled_row_const_iterator { - typedef scaled_row_const_iterator iterator; - typedef typename linalg_traits::const_row_iterator ITER; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - - ITER it; - S r; - - inline iterator operator ++(int) { iterator tmp=*this; it++; return tmp; } - inline iterator operator --(int) { iterator tmp=*this; it--; return tmp; } - inline iterator &operator ++() { it++; return *this; } - inline iterator &operator --() { it--; return *this; } - iterator &operator +=(difference_type i) { it += i; return *this; } - iterator &operator -=(difference_type i) { it -= i; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const - { return it - i.it; } - - inline ITER operator *() const { return it; } - inline ITER operator [](int i) { return it + i; } - - inline bool operator ==(const iterator &i) const { return (it == i.it); } - inline bool operator !=(const iterator &i) const { return !(i == *this); } - inline bool operator < (const iterator &i) const { return (it < i.it); } - - scaled_row_const_iterator(void) {} - scaled_row_const_iterator(const ITER &i, S rr) - : it(i), r(rr) { } - - }; - - template struct scaled_row_matrix_const_ref { - - typedef scaled_row_matrix_const_ref this_type; - typedef typename linalg_traits::const_row_iterator iterator; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::origin_type origin_type; - - iterator begin_, end_; - const origin_type *origin; - S r; - size_type nr, nc; - - scaled_row_matrix_const_ref(const M &m, S rr) - : begin_(mat_row_begin(m)), end_(mat_row_end(m)), - origin(linalg_origin(m)), r(rr), nr(mat_nrows(m)), nc(mat_ncols(m)) {} - - value_type operator()(size_type i, size_type j) const - { return r * linalg_traits::access(begin_+i, j); } - }; - - template struct linalg_traits > { - typedef scaled_row_matrix_const_ref this_type; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::origin_type origin_type; - typedef typename strongest_numeric_type::value_type>::T value_type; - typedef value_type reference; - typedef typename linalg_traits::storage_type storage_type; - typedef typename linalg_traits::const_sub_row_type vector_type; - typedef scaled_vector_const_ref sub_row_type; - typedef scaled_vector_const_ref const_sub_row_type; - typedef scaled_row_const_iterator row_iterator; - typedef scaled_row_const_iterator const_row_iterator; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_col_iterator; - typedef abstract_null_type col_iterator; - typedef row_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type nrows(const this_type &m) - { return m.nr; } - static size_type ncols(const this_type &m) - { return m.nc; } - static const_sub_row_type row(const const_row_iterator &it) - { return scaled(linalg_traits::row(it.it), it.r); } - static const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m.begin_, m.r); } - static const_row_iterator row_end(const this_type &m) - { return const_row_iterator(m.end_, m.r); } - static const origin_type* origin(const this_type &m) { return m.origin; } - static value_type access(const const_row_iterator &it, size_type i) - { return it.r * (linalg_traits::access(it.it, i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const scaled_row_matrix_const_ref& m) - { gmm::write(o,m); return o; } - - - template struct scaled_col_const_iterator { - typedef scaled_col_const_iterator iterator; - typedef typename linalg_traits::const_col_iterator ITER; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - - ITER it; - S r; - - iterator operator ++(int) { iterator tmp = *this; it++; return tmp; } - iterator operator --(int) { iterator tmp = *this; it--; return tmp; } - iterator &operator ++() { it++; return *this; } - iterator &operator --() { it--; return *this; } - iterator &operator +=(difference_type i) { it += i; return *this; } - iterator &operator -=(difference_type i) { it -= i; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const - { return it - i.it; } - - ITER operator *() const { return it; } - ITER operator [](int i) { return it + i; } - - bool operator ==(const iterator &i) const { return (it == i.it); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (it < i.it); } - - scaled_col_const_iterator(void) {} - scaled_col_const_iterator(const ITER &i, S rr) - : it(i), r(rr) { } - - }; - - template struct scaled_col_matrix_const_ref { - - typedef scaled_col_matrix_const_ref this_type; - typedef typename linalg_traits::const_col_iterator iterator; - typedef typename linalg_traits::value_type value_type; - typedef typename linalg_traits::origin_type origin_type; - - iterator begin_, end_; - const origin_type *origin; - S r; - size_type nr, nc; - - scaled_col_matrix_const_ref(const M &m, S rr) - : begin_(mat_col_begin(m)), end_(mat_col_end(m)), - origin(linalg_origin(m)), r(rr), nr(mat_nrows(m)), nc(mat_ncols(m)) {} - - value_type operator()(size_type i, size_type j) const - { return r * linalg_traits::access(begin_+j, i); } - }; - - template struct linalg_traits > { - typedef scaled_col_matrix_const_ref this_type; - typedef linalg_const is_reference; - typedef abstract_matrix linalg_type; - typedef typename strongest_numeric_type::value_type>::T value_type; - typedef typename linalg_traits::origin_type origin_type; - typedef value_type reference; - typedef typename linalg_traits::storage_type storage_type; - typedef typename linalg_traits::const_sub_col_type vector_type; - typedef abstract_null_type sub_col_type; - typedef scaled_vector_const_ref const_sub_col_type; - typedef abstract_null_type col_iterator; - typedef scaled_col_const_iterator const_col_iterator; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_row_iterator; - typedef abstract_null_type row_iterator; - typedef col_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type ncols(const this_type &m) - { return m.nc; } - static size_type nrows(const this_type &m) - { return m.nr; } - static const_sub_col_type col(const const_col_iterator &it) - { return scaled(linalg_traits::col(it.it), it.r); } - static const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m.begin_, m.r); } - static const_col_iterator col_end(const this_type &m) - { return const_col_iterator(m.end_, m.r); } - static const origin_type* origin(const this_type &m) { return m.origin; } - static value_type access(const const_col_iterator &it, size_type i) - { return it.r * (linalg_traits::access(it.it, i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const scaled_col_matrix_const_ref& m) - { gmm::write(o,m); return o; } - - - template struct scaled_return__ { - typedef abstract_null_type return_type; - }; - template struct scaled_return__ - { typedef scaled_row_matrix_const_ref return_type; }; - template struct scaled_return__ - { typedef scaled_col_matrix_const_ref return_type; }; - - - template struct scaled_return_ { - typedef abstract_null_type return_type; - }; - template struct scaled_return_ - { typedef scaled_vector_const_ref return_type; }; - template struct scaled_return_ { - typedef typename scaled_return__::sub_orientation>::potype>::return_type return_type; - }; - - template struct scaled_return { - typedef typename scaled_return_::linalg_type>::return_type return_type; - }; - - template inline - typename scaled_return::return_type - scaled(const L &v, S x) - { return scaled(v, x, typename linalg_traits::linalg_type()); } - - template inline - typename scaled_return::return_type - scaled(const V &v, S x, abstract_vector) - { return scaled_vector_const_ref(v, x); } - - template inline - typename scaled_return::return_type - scaled(const M &m, S x,abstract_matrix) { - return scaled(m, x, typename principal_orientation_type::sub_orientation>::potype()); - } - - template inline - typename scaled_return::return_type - scaled(const M &m, S x, row_major) { - return scaled_row_matrix_const_ref(m, x); - } - - template inline - typename scaled_return::return_type - scaled(const M &m, S x, col_major) { - return scaled_col_matrix_const_ref(m, x); - } - - - /* ******************************************************************** */ - /* matrix or vector scale */ - /* ******************************************************************** */ - - template inline - void scale(L& l, typename linalg_traits::value_type a) - { scale(l, a, typename linalg_traits::linalg_type()); } - - template inline - void scale(const L& l, typename linalg_traits::value_type a) - { scale(linalg_const_cast(l), a); } - - template inline - void scale(L& l, typename linalg_traits::value_type a, abstract_vector) { - typename linalg_traits::iterator it = vect_begin(l), ite = vect_end(l); - for ( ; it != ite; ++it) *it *= a; - } - - template - void scale(L& l, typename linalg_traits::value_type a, abstract_matrix) { - scale(l, a, typename principal_orientation_type::sub_orientation>::potype()); - } - - template - void scale(L& l, typename linalg_traits::value_type a, row_major) { - typename linalg_traits::row_iterator it = mat_row_begin(l), - ite = mat_row_end(l); - for ( ; it != ite; ++it) scale(linalg_traits::row(it), a); - } - - template - void scale(L& l, typename linalg_traits::value_type a, col_major) { - typename linalg_traits::col_iterator it = mat_col_begin(l), - ite = mat_col_end(l); - for ( ; it != ite; ++it) scale(linalg_traits::col(it), a); - } - -} - -#endif // GMM_SCALED_H__ diff --git a/include/gmm/gmm_solver_Newton.h b/include/gmm/gmm_solver_Newton.h deleted file mode 100644 index 3473e066ca1..00000000000 --- a/include/gmm/gmm_solver_Newton.h +++ /dev/null @@ -1,137 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2006-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_solver_Newton.h - @author Yves Renard - @author Michel Fournie - @date January 24, 2006. -*/ -#ifndef GMM_SOLVERS_NEWTON_H__ -#define GMM_SOLVERS_NEWTON_H__ - -namespace gmm { - -#include "gmm_kernel.h" - - /* ***************************************************************** */ - /* Line search definition */ - /* ***************************************************************** */ - - struct abstract_newton_line_search { - double conv_alpha, conv_r; - size_t it, itmax, glob_it; - virtual void init_search(double r, size_t git) = 0; - virtual double next_try(void) = 0; - virtual bool is_converged(double) = 0; - virtual double converged_value(void) { return conv_alpha; }; - virtual double converged_residual(void) { return conv_r; }; - virtual ~abstract_newton_line_search() {} - }; - - - struct simplest_newton_line_search : public abstract_newton_line_search { - double alpha, alpha_mult, first_res, alpha_max_ratio, alpha_min; - virtual void init_search(double r, size_t git) { - glob_it = git; - conv_alpha = alpha = double(1); conv_r = first_res = r; it = 0; - } - virtual double next_try(void) - { conv_alpha = alpha; alpha *= alpha_mult; ++it; return conv_alpha; } - virtual bool is_converged(double r) { - conv_r = r; - return ((it <= 1 && r < first_res) - || (r <= first_res * alpha_max_ratio) - || (conv_alpha <= alpha_min) - || it >= itmax); - } - simplest_newton_line_search - (size_t imax = size_t(-1), double a_max_ratio = 6.0/5.0, - double a_min = 1.0/1000.0, double a_mult = 3.0/5.0) - : alpha_mult(a_mult), alpha_max_ratio(a_max_ratio), alpha_min(a_min) - { itmax = imax; } - }; - - struct default_newton_line_search : public abstract_newton_line_search { - double alpha, alpha_mult, first_res, alpha_max_ratio; - double alpha_min, prev_res, alpha_max_augment; - virtual void init_search(double r, size_t git) { - glob_it = git; - conv_alpha = alpha = double(1); - prev_res = conv_r = first_res = r; it = 0; - } - virtual double next_try(void) - { conv_alpha = alpha; alpha *= alpha_mult; ++it; return conv_alpha; } - virtual bool is_converged(double r) { - if (glob_it == 0 || (r < first_res / double(2)) - || (conv_alpha <= alpha_min && r < first_res * alpha_max_augment) - || it >= itmax) - { conv_r = r; return true; } - if (it > 1 && r > prev_res && prev_res < alpha_max_ratio * first_res) - return true; - prev_res = conv_r = r; - return false; - } - default_newton_line_search - (size_t imax = size_t(-1), - double a_max_ratio = 5.0/3.0, - double a_min = 1.0/1000.0, double a_mult = 3.0/5.0, double a_augm = 2.0) - : alpha_mult(a_mult), alpha_max_ratio(a_max_ratio), - alpha_min(a_min), alpha_max_augment(a_augm) { itmax = imax; } - }; - - - struct systematic_newton_line_search : public abstract_newton_line_search { - double alpha, alpha_mult, first_res; - double alpha_min, prev_res; - bool first; - virtual void init_search(double r, size_t git) { - glob_it = git; - conv_alpha = alpha = double(1); - prev_res = conv_r = first_res = r; it = 0; first = true; - } - virtual double next_try(void) - { double a = alpha; alpha *= alpha_mult; ++it; return a; } - virtual bool is_converged(double r) { - // cout << "a = " << alpha / alpha_mult << " r = " << r << endl; - if (r < conv_r || first) - { conv_r = r; conv_alpha = alpha / alpha_mult; first = false; } - if ((alpha <= alpha_min*alpha_mult) || it >= itmax) return true; - return false; - } - systematic_newton_line_search - (size_t imax = size_t(-1), - double a_min = 1.0/10000.0, double a_mult = 3.0/5.0) - : alpha_mult(a_mult), alpha_min(a_min) { itmax = imax; } - }; - -} - - -#endif diff --git a/include/gmm/gmm_solver_Schwarz_additive.h b/include/gmm/gmm_solver_Schwarz_additive.h deleted file mode 100644 index 2b994154e9d..00000000000 --- a/include/gmm/gmm_solver_Schwarz_additive.h +++ /dev/null @@ -1,746 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_solver_Schwarz_additive.h - @author Yves Renard - @author Michel Fournie - @date October 13, 2002. -*/ - -#ifndef GMM_SOLVERS_SCHWARZ_ADDITIVE_H__ -#define GMM_SOLVERS_SCHWARZ_ADDITIVE_H__ - -#include "gmm_kernel.h" -#include "gmm_superlu_interface.h" -#include "gmm_solver_cg.h" -#include "gmm_solver_gmres.h" -#include "gmm_solver_bicgstab.h" -#include "gmm_solver_qmr.h" -#include "gmm_solver_Newton.h" - -namespace gmm { - - /* ******************************************************************** */ - /* Additive Schwarz interfaced local solvers */ - /* ******************************************************************** */ - - struct using_cg {}; - struct using_gmres {}; - struct using_bicgstab {}; - struct using_qmr {}; - - template - struct actual_precond { - typedef P APrecond; - static const APrecond &transform(const P &PP) { return PP; } - }; - - template - void AS_local_solve(using_cg, const Matrix1 &A, Vector &x, const Vector &b, - const Precond &P, iteration &iter) - { cg(A, x, b, P, iter); } - - template - void AS_local_solve(using_gmres, const Matrix1 &A, Vector &x, - const Vector &b, const Precond &P, iteration &iter) - { gmres(A, x, b, P, 100, iter); } - - template - void AS_local_solve(using_bicgstab, const Matrix1 &A, Vector &x, - const Vector &b, const Precond &P, iteration &iter) - { bicgstab(A, x, b, P, iter); } - - template - void AS_local_solve(using_qmr, const Matrix1 &A, Vector &x, - const Vector &b, const Precond &P, iteration &iter) - { qmr(A, x, b, P, iter); } - -#if defined(GMM_USES_SUPERLU) - struct using_superlu {}; - - template - struct actual_precond { - typedef typename linalg_traits::value_type value_type; - typedef SuperLU_factor APrecond; - template - static APrecond transform(const PR &) { return APrecond(); } - static const APrecond &transform(const APrecond &PP) { return PP; } - }; - - template - void AS_local_solve(using_superlu, const Matrix1 &, Vector &x, - const Vector &b, const Precond &P, iteration &iter) - { P.solve(x, b); iter.set_iteration(1); } -#endif - - /* ******************************************************************** */ - /* Additive Schwarz Linear system */ - /* ******************************************************************** */ - - template - struct add_schwarz_mat{ - typedef typename linalg_traits::value_type value_type; - - const Matrix1 *A; - const std::vector *vB; - std::vector vAloc; - mutable iteration iter; - double residual; - mutable size_type itebilan; - mutable std::vector > gi, fi; - std::vector::APrecond> precond1; - - void init(const Matrix1 &A_, const std::vector &vB_, - iteration iter_, const Precond &P, double residual_); - - add_schwarz_mat(void) {} - add_schwarz_mat(const Matrix1 &A_, const std::vector &vB_, - iteration iter_, const Precond &P, double residual_) - { init(A_, vB_, iter_, P, residual_); } - }; - - template - void add_schwarz_mat::init( - const Matrix1 &A_, const std::vector &vB_, - iteration iter_, const Precond &P, double residual_) { - - vB = &vB_; A = &A_; iter = iter_; - residual = residual_; - - size_type nb_sub = vB->size(); - vAloc.resize(nb_sub); - gi.resize(nb_sub); fi.resize(nb_sub); - precond1.resize(nb_sub); - std::fill(precond1.begin(), precond1.end(), - actual_precond::transform(P)); - itebilan = 0; - - if (iter.get_noisy()) cout << "Init pour sub dom "; -#ifdef GMM_USES_MPI - int size,tranche,borne_sup,borne_inf,rank,tag1=11,tag2=12,tag3=13,sizepr = 0; - // int tab[4]; - double t_ref,t_final; - MPI_Status status; - t_ref=MPI_Wtime(); - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - tranche=nb_sub/size; - borne_inf=rank*tranche; - borne_sup=(rank+1)*tranche; - // if (rank==size-1) borne_sup = nb_sub; - - cout << "Nombre de sous domaines " << borne_sup - borne_inf << endl; - - int sizeA = mat_nrows(*A); - gmm::csr_matrix Acsr(sizeA, sizeA), Acsrtemp(sizeA, sizeA); - gmm::copy(gmm::eff_matrix(*A), Acsr); - int next = (rank + 1) % size; - int previous = (rank + size - 1) % size; - //communication of local information on ring pattern - //Each process receive Nproc-1 contributions - - for (int nproc = 0; nproc < size; ++nproc) { - for (size_type i = size_type(borne_inf); i < size_type(borne_sup); ++i) { -// for (size_type i = 0; i < nb_sub/size; ++i) { -// for (size_type i = 0; i < nb_sub; ++i) { - // size_type i=(rank+size*(j-1)+nb_sub)%nb_sub; - - cout << "Sous domaines " << i << " : " << mat_ncols((*vB)[i]) << endl; -#else - for (size_type i = 0; i < nb_sub; ++i) { -#endif - - if (iter.get_noisy()) cout << i << " " << std::flush; - Matrix2 Maux(mat_ncols((*vB)[i]), mat_nrows((*vB)[i])); - -#ifdef GMM_USES_MPI - Matrix2 Maux2(mat_ncols((*vB)[i]), mat_ncols((*vB)[i])); - if (nproc == 0) { - gmm::resize(vAloc[i], mat_ncols((*vB)[i]), mat_ncols((*vB)[i])); - gmm::clear(vAloc[i]); - } - gmm::mult(gmm::transposed((*vB)[i]), Acsr, Maux); - gmm::mult(Maux, (*vB)[i], Maux2); - gmm::add(Maux2, vAloc[i]); -#else - gmm::resize(vAloc[i], mat_ncols((*vB)[i]), mat_ncols((*vB)[i])); - gmm::mult(gmm::transposed((*vB)[i]), *A, Maux); - gmm::mult(Maux, (*vB)[i], vAloc[i]); -#endif - -#ifdef GMM_USES_MPI - if (nproc == size - 1 ) { -#endif - precond1[i].build_with(vAloc[i]); - gmm::resize(fi[i], mat_ncols((*vB)[i])); - gmm::resize(gi[i], mat_ncols((*vB)[i])); -#ifdef GMM_USES_MPI - } -#else - } -#endif -#ifdef GMM_USES_MPI - } - if (nproc != size - 1) { - MPI_Sendrecv(Acsr.jc, sizeA+1, MPI_INT, next, tag2, - Acsrtemp.jc, sizeA+1,MPI_INT,previous,tag2, - MPI_COMM_WORLD,&status); - if (Acsrtemp.jc[sizeA] > size_type(sizepr)) { - sizepr = Acsrtemp.jc[sizeA]; - delete[] Acsrtemp.pr; delete[] Acsrtemp.ir; - Acsrtemp.pr = new value_type[sizepr]; - Acsrtemp.ir = new unsigned int[sizepr]; - } - MPI_Sendrecv(Acsr.ir, Acsr.jc[sizeA], MPI_INT, next, tag1, - Acsrtemp.ir, Acsrtemp.jc[sizeA],MPI_INT,previous,tag1, - MPI_COMM_WORLD,&status); - - MPI_Sendrecv(Acsr.pr, Acsr.jc[sizeA], mpi_type(value_type()), next, tag3, - Acsrtemp.pr, Acsrtemp.jc[sizeA],mpi_type(value_type()),previous,tag3, - MPI_COMM_WORLD,&status); - gmm::copy(Acsrtemp, Acsr); - } - } - t_final=MPI_Wtime(); - cout<<"temps boucle precond "<< t_final-t_ref< - void mult(const add_schwarz_mat &M, - const Vector2 &p, Vector3 &q) { - size_type itebilan = 0; -#ifdef GMM_USES_MPI - static double tmult_tot = 0.0; - double t_ref = MPI_Wtime(); -#endif - // cout << "tmult AS begin " << endl; - mult(*(M.A), p, q); -#ifdef GMM_USES_MPI - tmult_tot += MPI_Wtime()-t_ref; - cout << "tmult_tot = " << tmult_tot << endl; -#endif - std::vector qbis(gmm::vect_size(q)); - std::vector qter(gmm::vect_size(q)); -#ifdef GMM_USES_MPI - // MPI_Status status; - // MPI_Request request,request1; - // int tag=111; - int size,tranche,borne_sup,borne_inf,rank; - size_type nb_sub=M.fi.size(); - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - tranche=nb_sub/size; - borne_inf=rank*tranche; - borne_sup=(rank+1)*tranche; - // if (rank==size-1) borne_sup=nb_sub; - // int next = (rank + 1) % size; - // int previous = (rank + size - 1) % size; - t_ref = MPI_Wtime(); - for (size_type i = size_type(borne_inf); i < size_type(borne_sup); ++i) -// for (size_type i = 0; i < nb_sub/size; ++i) - // for (size_type j = 0; j < nb_sub; ++j) -#else - for (size_type i = 0; i < M.fi.size(); ++i) -#endif - { -#ifdef GMM_USES_MPI - // size_type i=j; // (rank+size*(j-1)+nb_sub)%nb_sub; -#endif - gmm::mult(gmm::transposed((*(M.vB))[i]), q, M.fi[i]); - M.iter.init(); - AS_local_solve(local_solver(), (M.vAloc)[i], (M.gi)[i], - (M.fi)[i],(M.precond1)[i],M.iter); - itebilan = std::max(itebilan, M.iter.get_iteration()); - } - -#ifdef GMM_USES_MPI - cout << "First AS loop time " << MPI_Wtime() - t_ref << endl; -#endif - - gmm::clear(q); -#ifdef GMM_USES_MPI - t_ref = MPI_Wtime(); - // for (size_type j = 0; j < nb_sub; ++j) - for (size_type i = size_type(borne_inf); i < size_type(borne_sup); ++i) - -#else - for (size_type i = 0; i < M.gi.size(); ++i) -#endif - { - -#ifdef GMM_USES_MPI - // size_type i=j; // (rank+size*(j-1)+nb_sub)%nb_sub; -// gmm::mult((*(M.vB))[i], M.gi[i], qbis,qbis); - gmm::mult((*(M.vB))[i], M.gi[i], qter); - add(qter,qbis,qbis); -#else - gmm::mult((*(M.vB))[i], M.gi[i], q, q); -#endif - } -#ifdef GMM_USES_MPI - //WARNING this add only if you use the ring pattern below - // need to do this below if using a n explicit ring pattern communication - -// add(qbis,q,q); - cout << "Second AS loop time " << MPI_Wtime() - t_ref << endl; -#endif - - -#ifdef GMM_USES_MPI - // int tag1=11; - static double t_tot = 0.0; - double t_final; - t_ref=MPI_Wtime(); -// int next = (rank + 1) % size; -// int previous = (rank + size - 1) % size; - //communication of local information on ring pattern - //Each process receive Nproc-1 contributions - -// if (size > 1) { -// for (int nproc = 0; nproc < size-1; ++nproc) -// { - -// MPI_Sendrecv(&(qbis[0]), gmm::vect_size(q), MPI_DOUBLE, next, tag1, -// &(qter[0]), gmm::vect_size(q),MPI_DOUBLE,previous,tag1, -// MPI_COMM_WORLD,&status); -// gmm::copy(qter, qbis); -// add(qbis,q,q); -// } -// } - MPI_Allreduce(&(qbis[0]), &(q[0]),gmm::vect_size(q), MPI_DOUBLE, - MPI_SUM,MPI_COMM_WORLD); - t_final=MPI_Wtime(); - t_tot += t_final-t_ref; - cout<<"["<< rank<<"] temps reduce Resol "<< t_final-t_ref << " t_tot = " << t_tot << endl; -#endif - - if (M.iter.get_noisy() > 0) cout << "itebloc = " << itebilan << endl; - M.itebilan += itebilan; - M.iter.set_resmax((M.iter.get_resmax() + M.residual) * 0.5); - } - - template - void mult(const add_schwarz_mat &M, - const Vector2 &p, const Vector3 &q) { - mult(M, p, const_cast(q)); - } - - template - void mult(const add_schwarz_mat &M, - const Vector2 &p, const Vector3 &p2, Vector4 &q) - { mult(M, p, q); add(p2, q); } - - template - void mult(const add_schwarz_mat &M, - const Vector2 &p, const Vector3 &p2, const Vector4 &q) - { mult(M, p, const_cast(q)); add(p2, q); } - - /* ******************************************************************** */ - /* Additive Schwarz interfaced global solvers */ - /* ******************************************************************** */ - - template - void AS_global_solve(using_cg, const ASM_type &ASM, Vect &x, - const Vect &b, iteration &iter) - { cg(ASM, x, b, *(ASM.A), identity_matrix(), iter); } - - template - void AS_global_solve(using_gmres, const ASM_type &ASM, Vect &x, - const Vect &b, iteration &iter) - { gmres(ASM, x, b, identity_matrix(), 100, iter); } - - template - void AS_global_solve(using_bicgstab, const ASM_type &ASM, Vect &x, - const Vect &b, iteration &iter) - { bicgstab(ASM, x, b, identity_matrix(), iter); } - - template - void AS_global_solve(using_qmr,const ASM_type &ASM, Vect &x, - const Vect &b, iteration &iter) - { qmr(ASM, x, b, identity_matrix(), iter); } - -#if defined(GMM_USES_SUPERLU) - template - void AS_global_solve(using_superlu, const ASM_type &, Vect &, - const Vect &, iteration &) { - GMM_ASSERT1(false, "You cannot use SuperLU as " - "global solver in additive Schwarz meethod"); - } -#endif - - /* ******************************************************************** */ - /* Linear Additive Schwarz method */ - /* ******************************************************************** */ - /* ref : Domain decomposition algorithms for the p-version finite */ - /* element method for elliptic problems, Luca F. Pavarino, */ - /* PhD thesis, Courant Institute of Mathematical Sciences, 1992. */ - /* ******************************************************************** */ - - /** Function to call if the ASM matrix is precomputed for successive solve - * with the same system. - */ - template - void additive_schwarz( - add_schwarz_mat &ASM, Vector3 &u, - const Vector2 &f, iteration &iter, const global_solver&) { - - typedef typename linalg_traits::value_type value_type; - - size_type nb_sub = ASM.vB->size(), nb_dof = gmm::vect_size(f); - ASM.itebilan = 0; - std::vector g(nb_dof); - std::vector gbis(nb_dof); -#ifdef GMM_USES_MPI - double t_init=MPI_Wtime(); - int size,tranche,borne_sup,borne_inf,rank; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - tranche=nb_sub/size; - borne_inf=rank*tranche; - borne_sup=(rank+1)*tranche; - // if (rank==size-1) borne_sup=nb_sub*size; - for (size_type i = size_type(borne_inf); i < size_type(borne_sup); ++i) -// for (size_type i = 0; i < nb_sub/size; ++i) - // for (size_type j = 0; j < nb_sub; ++j) - // for (size_type i = rank; i < nb_sub; i+=size) -#else - for (size_type i = 0; i < nb_sub; ++i) -#endif - { - -#ifdef GMM_USES_MPI - // size_type i=j; // (rank+size*(j-1)+nb_sub)%nb_sub; -#endif - gmm::mult(gmm::transposed((*(ASM.vB))[i]), f, ASM.fi[i]); - ASM.iter.init(); - AS_local_solve(local_solver(), ASM.vAloc[i], ASM.gi[i], ASM.fi[i], - ASM.precond1[i], ASM.iter); - ASM.itebilan = std::max(ASM.itebilan, ASM.iter.get_iteration()); -#ifdef GMM_USES_MPI - gmm::mult((*(ASM.vB))[i], ASM.gi[i], gbis,gbis); -#else - gmm::mult((*(ASM.vB))[i], ASM.gi[i], g, g); -#endif - } -#ifdef GMM_USES_MPI - cout<<"temps boucle init "<< MPI_Wtime()-t_init< - void additive_schwarz(const Matrix1 &A, Vector3 &u, - const Vector2 &f, const Precond &P, - const std::vector &vB, - iteration &iter, local_solver, - global_solver) { - iter.set_rhsnorm(vect_norm2(f)); - if (iter.get_rhsnorm() == 0.0) { gmm::clear(u); return; } - iteration iter2 = iter; iter2.reduce_noisy(); - iter2.set_maxiter(size_type(-1)); - add_schwarz_mat - ASM(A, vB, iter2, P, iter.get_resmax()); - additive_schwarz(ASM, u, f, iter, global_solver()); - } - - /* ******************************************************************** */ - /* Sequential Non-Linear Additive Schwarz method */ - /* ******************************************************************** */ - /* ref : Nonlinearly Preconditionned Inexact Newton Algorithms, */ - /* Xiao-Chuan Cai, David E. Keyes, */ - /* SIAM J. Sci. Comp. 24: p183-200. l */ - /* ******************************************************************** */ - - template - class NewtonAS_struct { - - public : - typedef Matrixt tangent_matrix_type; - typedef MatrixBi B_matrix_type; - typedef typename linalg_traits::value_type value_type; - typedef std::vector Vector; - - virtual size_type size(void) = 0; - virtual const std::vector &get_vB() = 0; - - virtual void compute_F(Vector &f, Vector &x) = 0; - virtual void compute_tangent_matrix(Matrixt &M, Vector &x) = 0; - // compute Bi^T grad(F(X)) Bi - virtual void compute_sub_tangent_matrix(Matrixt &Mloc, Vector &x, - size_type i) = 0; - // compute Bi^T F(X) - virtual void compute_sub_F(Vector &fi, Vector &x, size_type i) = 0; - - virtual ~NewtonAS_struct() {} - }; - - template - struct AS_exact_gradient { - const std::vector &vB; - std::vector vM; - std::vector vMloc; - - void init(void) { - for (size_type i = 0; i < vB.size(); ++i) { - Matrixt aux(gmm::mat_ncols(vB[i]), gmm::mat_ncols(vM[i])); - gmm::resize(vMloc[i], gmm::mat_ncols(vB[i]), gmm::mat_ncols(vB[i])); - gmm::mult(gmm::transposed(vB[i]), vM[i], aux); - gmm::mult(aux, vB[i], vMloc[i]); - } - } - AS_exact_gradient(const std::vector &vB_) : vB(vB_) { - vM.resize(vB.size()); vMloc.resize(vB.size()); - for (size_type i = 0; i < vB.size(); ++i) { - gmm::resize(vM[i], gmm::mat_nrows(vB[i]), gmm::mat_nrows(vB[i])); - } - } - }; - - template - void mult(const AS_exact_gradient &M, - const Vector2 &p, Vector3 &q) { - gmm::clear(q); - typedef typename gmm::linalg_traits::value_type T; - std::vector v(gmm::vect_size(p)), w, x; - for (size_type i = 0; i < M.vB.size(); ++i) { - w.resize(gmm::mat_ncols(M.vB[i])); - x.resize(gmm::mat_ncols(M.vB[i])); - gmm::mult(M.vM[i], p, v); - gmm::mult(gmm::transposed(M.vB[i]), v, w); - double rcond; - SuperLU_solve(M.vMloc[i], x, w, rcond); - // gmm::iteration iter(1E-10, 0, 100000); - //gmm::gmres(M.vMloc[i], x, w, gmm::identity_matrix(), 50, iter); - gmm::mult_add(M.vB[i], x, q); - } - } - - template - void mult(const AS_exact_gradient &M, - const Vector2 &p, const Vector3 &q) { - mult(M, p, const_cast(q)); - } - - template - void mult(const AS_exact_gradient &M, - const Vector2 &p, const Vector3 &p2, Vector4 &q) - { mult(M, p, q); add(p2, q); } - - template - void mult(const AS_exact_gradient &M, - const Vector2 &p, const Vector3 &p2, const Vector4 &q) - { mult(M, p, const_cast(q)); add(p2, q); } - - - - template - void Newton_additive_Schwarz(NewtonAS_struct &NS, - const Vector &u_, - iteration &iter, const Precond &P, - local_solver, global_solver) { - Vector &u = const_cast(u_); - typedef typename linalg_traits::value_type value_type; - typedef typename number_traits::magnitude_type mtype; - typedef actual_precond chgt_precond; - - double residual = iter.get_resmax(); - - default_newton_line_search internal_ls; - default_newton_line_search external_ls(size_t(-1), 5.0/3, 1.0/1000, 3.0/5); - - // systematic_newton_line_search external_ls(size_t(-1), 1.0/10000.0, 3.0/100.0); - - typename chgt_precond::APrecond PP = chgt_precond::transform(P); - iter.set_rhsnorm(mtype(1)); - iteration iternc(iter); - iternc.reduce_noisy(); iternc.set_maxiter(size_type(-1)); - iteration iter2(iternc); - iteration iter3(iter2); iter3.reduce_noisy(); - iteration iter4(iter3); - iternc.set_name("Local Newton"); - iter2.set_name("Linear System for Global Newton"); - iternc.set_resmax(residual/100.0); - iter3.set_resmax(residual/10000.0); - iter2.set_resmax(residual/1000.0); - iter4.set_resmax(residual/1000.0); - std::vector rhs(NS.size()), x(NS.size()), d(NS.size()); - std::vector xi, xii, fi, di; - - std::vector< std::vector > vx(NS.get_vB().size()); - for (size_type i = 0; i < NS.get_vB().size(); ++i) // for exact gradient - vx[i].resize(NS.size()); // for exact gradient - - Matrixt Mloc, M(NS.size(), NS.size()); - NS.compute_F(rhs, u); - mtype act_res=gmm::vect_norm2(rhs), act_res_new(0), precond_res = act_res; - mtype alpha; - - while(!iter.finished(std::min(act_res, precond_res))) { - for (int SOR_step = 0; SOR_step >= 0; --SOR_step) { - gmm::clear(rhs); - for (size_type isd = 0; isd < NS.get_vB().size(); ++isd) { - const MatrixBi &Bi = (NS.get_vB())[isd]; - size_type si = mat_ncols(Bi); - gmm::resize(Mloc, si, si); - xi.resize(si); xii.resize(si); fi.resize(si); di.resize(si); - - iternc.init(); - iternc.set_maxiter(30); // ? - if (iternc.get_noisy()) - cout << "Non-linear local problem " << isd << endl; - gmm::clear(xi); - gmm::copy(u, x); - NS.compute_sub_F(fi, x, isd); gmm::scale(fi, value_type(-1)); - mtype r = gmm::vect_norm2(fi), r_t(r); - if (r > value_type(0)) { - iternc.set_rhsnorm(std::max(r, mtype(1))); - while(!iternc.finished(r)) { - NS.compute_sub_tangent_matrix(Mloc, x, isd); - - PP.build_with(Mloc); - iter3.init(); - AS_local_solve(local_solver(), Mloc, di, fi, PP, iter3); - - internal_ls.init_search(r, iternc.get_iteration()); - do { - alpha = internal_ls.next_try(); - gmm::add(xi, gmm::scaled(di, -alpha), xii); - gmm::mult(Bi, gmm::scaled(xii, -1.0), u, x); - NS.compute_sub_F(fi, x, isd); gmm::scale(fi, value_type(-1)); - r_t = gmm::vect_norm2(fi); - } while (!internal_ls.is_converged(r_t)); - - if (alpha != internal_ls.converged_value()) { - alpha = internal_ls.converged_value(); - gmm::add(xi, gmm::scaled(di, -alpha), xii); - gmm::mult(Bi, gmm::scaled(xii, -1.0), u, x); - NS.compute_sub_F(fi, x, isd); gmm::scale(fi, value_type(-1)); - r_t = gmm::vect_norm2(fi); - } - gmm::copy(x, vx[isd]); // for exact gradient - - if (iternc.get_noisy()) cout << "(step=" << alpha << ")\t"; - ++iternc; r = r_t; gmm::copy(xii, xi); - } - if (SOR_step) gmm::mult(Bi, gmm::scaled(xii, -1.0), u, u); - gmm::mult(Bi, gmm::scaled(xii, -1.0), rhs, rhs); - } - } - precond_res = gmm::vect_norm2(rhs); - if (SOR_step) cout << "SOR step residual = " << precond_res << endl; - if (precond_res < residual) break; - cout << "Precond residual = " << precond_res << endl; - } - - iter2.init(); - // solving linear system for the global Newton method - if (0) { - NS.compute_tangent_matrix(M, u); - add_schwarz_mat - ASM(M, NS.get_vB(), iter4, P, iter.get_resmax()); - AS_global_solve(global_solver(), ASM, d, rhs, iter2); - } - else { // for exact gradient - AS_exact_gradient eg(NS.get_vB()); - for (size_type i = 0; i < NS.get_vB().size(); ++i) { - NS.compute_tangent_matrix(eg.vM[i], vx[i]); - } - eg.init(); - gmres(eg, d, rhs, gmm::identity_matrix(), 50, iter2); - } - - // gmm::add(gmm::scaled(rhs, 0.1), u); ++iter; - external_ls.init_search(act_res, iter.get_iteration()); - do { - alpha = external_ls.next_try(); - gmm::add(gmm::scaled(d, alpha), u, x); - NS.compute_F(rhs, x); - act_res_new = gmm::vect_norm2(rhs); - } while (!external_ls.is_converged(act_res_new)); - - if (alpha != external_ls.converged_value()) { - alpha = external_ls.converged_value(); - gmm::add(gmm::scaled(d, alpha), u, x); - NS.compute_F(rhs, x); - act_res_new = gmm::vect_norm2(rhs); - } - - if (iter.get_noisy() > 1) cout << endl; - act_res = act_res_new; - if (iter.get_noisy()) cout << "(step=" << alpha << ")\t unprecond res = " << act_res << " "; - - - ++iter; gmm::copy(x, u); - } - } - -} - - -#endif // GMM_SOLVERS_SCHWARZ_ADDITIVE_H__ diff --git a/include/gmm/gmm_solver_bfgs.h b/include/gmm/gmm_solver_bfgs.h deleted file mode 100644 index 88512a68467..00000000000 --- a/include/gmm/gmm_solver_bfgs.h +++ /dev/null @@ -1,207 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2004-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_solver_bfgs.h - @author Yves Renard - @date October 14 2004. - @brief Implements BFGS (Broyden, Fletcher, Goldfarb, Shanno) algorithm. - */ -#ifndef GMM_BFGS_H -#define GMM_BFGS_H - -#include "gmm_kernel.h" -#include "gmm_iter.h" - -namespace gmm { - - // BFGS algorithm (Broyden, Fletcher, Goldfarb, Shanno) - // Quasi Newton method for optimization problems. - // with Wolfe Line search. - - - // delta[k] = x[k+1] - x[k] - // gamma[k] = grad f(x[k+1]) - grad f(x[k]) - // H[0] = I - // BFGS : zeta[k] = delta[k] - H[k] gamma[k] - // DFP : zeta[k] = H[k] gamma[k] - // tau[k] = gamma[k]^T zeta[k] - // rho[k] = 1 / gamma[k]^T delta[k] - // BFGS : H[k+1] = H[k] + rho[k](zeta[k] delta[k]^T + delta[k] zeta[k]^T) - // - rho[k]^2 tau[k] delta[k] delta[k]^T - // DFP : H[k+1] = H[k] + rho[k] delta[k] delta[k]^T - // - (1/tau[k])zeta[k] zeta[k]^T - - // Object representing the inverse of the Hessian - template struct bfgs_invhessian { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - std::vector delta, gamma, zeta; - std::vector tau, rho; - int version; - - template void hmult(const VEC1 &X, VEC2 &Y) { - copy(X, Y); - for (size_type k = 0 ; k < delta.size(); ++k) { - T xdelta = vect_sp(X, delta[k]), xzeta = vect_sp(X, zeta[k]); - switch (version) { - case 0 : // BFGS - add(scaled(zeta[k], rho[k]*xdelta), Y); - add(scaled(delta[k], rho[k]*(xzeta-rho[k]*tau[k]*xdelta)), Y); - break; - case 1 : // DFP - add(scaled(delta[k], rho[k]*xdelta), Y); - add(scaled(zeta[k], -xzeta/tau[k]), Y); - break; - } - } - } - - void restart(void) { - delta.resize(0); gamma.resize(0); zeta.resize(0); - tau.resize(0); rho.resize(0); - } - - template - void update(const VECT1 &deltak, const VECT2 &gammak) { - size_type N = vect_size(deltak), k = delta.size(); - VECTOR Y(N); - hmult(gammak, Y); - delta.resize(k+1); gamma.resize(k+1); zeta.resize(k+1); - tau.resize(k+1); rho.resize(k+1); - resize(delta[k], N); resize(gamma[k], N); resize(zeta[k], N); - gmm::copy(deltak, delta[k]); - gmm::copy(gammak, gamma[k]); - rho[k] = R(1) / vect_sp(deltak, gammak); - if (version == 0) - add(delta[k], scaled(Y, -1), zeta[k]); - else - gmm::copy(Y, zeta[k]); - tau[k] = vect_sp(gammak, zeta[k]); - } - - bfgs_invhessian(int v = 0) { version = v; } - }; - - - template - void bfgs(FUNCTION f, DERIVATIVE grad, VECTOR &x, - int restart, iteration& iter, int version = 0, - double lambda_init=0.001, double print_norm=1.0) { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - bfgs_invhessian invhessian(version); - VECTOR r(vect_size(x)), d(vect_size(x)), y(vect_size(x)), r2(vect_size(x)); - grad(x, r); - R lambda = lambda_init, valx = f(x), valy; - int nb_restart(0); - - if (iter.get_noisy() >= 1) cout << "value " << valx / print_norm << " "; - while (! iter.finished_vect(r)) { - - invhessian.hmult(r, d); gmm::scale(d, T(-1)); - - // Wolfe Line search - R derivative = gmm::vect_sp(r, d); - R lambda_min(0), lambda_max(0), m1 = 0.27, m2 = 0.57; - bool unbounded = true, blocked = false, grad_computed = false; - - for(;;) { - add(x, scaled(d, lambda), y); - valy = f(y); - if (iter.get_noisy() >= 2) { - cout.precision(15); - cout << "Wolfe line search, lambda = " << lambda - << " value = " << valy /print_norm << endl; -// << " derivative = " << derivative -// << " lambda min = " << lambda_min << " lambda max = " -// << lambda_max << endl; getchar(); - } - if (valy <= valx + m1 * lambda * derivative) { - grad(y, r2); grad_computed = true; - T derivative2 = gmm::vect_sp(r2, d); - if (derivative2 >= m2*derivative) break; - lambda_min = lambda; - } - else { - lambda_max = lambda; - unbounded = false; - } - if (unbounded) lambda *= R(10); - else lambda = (lambda_max + lambda_min) / R(2); - if (lambda == lambda_max || lambda == lambda_min) break; - // valy <= R(2)*valx replaced by - // valy <= valx + gmm::abs(derivative)*lambda_init - // for compatibility with negative values (08.24.07). - if (valy <= valx + R(2)*gmm::abs(derivative)*lambda && - (lambda < R(lambda_init*1E-8) || - (!unbounded && lambda_max-lambda_min < R(lambda_init*1E-8)))) - { blocked = true; lambda = lambda_init; break; } - } - - // Rank two update - ++iter; - if (!grad_computed) grad(y, r2); - gmm::add(scaled(r2, -1), r); - if (iter.get_iteration() % restart == 0 || blocked) { - if (iter.get_noisy() >= 1) cout << "Restart\n"; - invhessian.restart(); - if (++nb_restart > 10) { - if (iter.get_noisy() >= 1) cout << "BFGS is blocked, exiting\n"; - return; - } - } - else { - invhessian.update(gmm::scaled(d,lambda), gmm::scaled(r,-1)); - nb_restart = 0; - } - copy(r2, r); copy(y, x); valx = valy; - if (iter.get_noisy() >= 1) - cout << "BFGS value " << valx/print_norm << "\t"; - } - - } - - - template - inline void dfp(FUNCTION f, DERIVATIVE grad, VECTOR &x, - int restart, iteration& iter, int version = 1) { - bfgs(f, grad, x, restart, iter, version); - - } - - -} - -#endif - diff --git a/include/gmm/gmm_solver_bicgstab.h b/include/gmm/gmm_solver_bicgstab.h deleted file mode 100644 index c702b20aadb..00000000000 --- a/include/gmm/gmm_solver_bicgstab.h +++ /dev/null @@ -1,160 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of bicgstab.h from ITL. -// See http://osl.iu.edu/research/itl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -/**@file gmm_solver_bicgstab.h - @author Andrew Lumsdaine - @author Lie-Quan Lee - @author Yves Renard - @date October 13, 2002. - @brief BiCGStab iterative solver. -*/ - -#ifndef GMM_SOLVER_BICGSTAB_H__ -#define GMM_SOLVER_BICGSTAB_H__ - -#include "gmm_kernel.h" -#include "gmm_iter.h" - -namespace gmm { - - /* ******************************************************************** */ - /* BiConjugate Gradient Stabilized */ - /* (preconditionned, with parametrable scalar product) */ - /* ******************************************************************** */ - - template - void bicgstab(const Matrix& A, Vector& x, const VectorB& b, - const Preconditioner& M, iteration &iter) { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - typedef typename temporary_dense_vector::vector_type temp_vector; - - T rho_1, rho_2(0), alpha(0), beta, omega(0); - temp_vector p(vect_size(x)), phat(vect_size(x)), s(vect_size(x)), - shat(vect_size(x)), - t(vect_size(x)), v(vect_size(x)), r(vect_size(x)), rtilde(vect_size(x)); - - gmm::mult(A, gmm::scaled(x, -T(1)), b, r); - gmm::copy(r, rtilde); - R norm_r = gmm::vect_norm2(r); - iter.set_rhsnorm(gmm::vect_norm2(b)); - - if (iter.get_rhsnorm() == 0.0) { clear(x); return; } - - while (!iter.finished(norm_r)) { - - rho_1 = gmm::vect_sp(rtilde, r); - if (rho_1 == T(0)) { - if (iter.get_maxiter() == size_type(-1)) - { GMM_ASSERT1(false, "Bicgstab failed to converge"); } - else { GMM_WARNING1("Bicgstab failed to converge"); return; } - } - - if (iter.first()) - gmm::copy(r, p); - else { - if (omega == T(0)) { - if (iter.get_maxiter() == size_type(-1)) - { GMM_ASSERT1(false, "Bicgstab failed to converge"); } - else { GMM_WARNING1("Bicgstab failed to converge"); return; } - } - - beta = (rho_1 / rho_2) * (alpha / omega); - - gmm::add(gmm::scaled(v, -omega), p); - gmm::add(r, gmm::scaled(p, beta), p); - } - gmm::mult(M, p, phat); - gmm::mult(A, phat, v); - alpha = rho_1 / gmm::vect_sp(v, rtilde); - gmm::add(r, gmm::scaled(v, -alpha), s); - - if (iter.finished_vect(s)) - { gmm::add(gmm::scaled(phat, alpha), x); break; } - - gmm::mult(M, s, shat); - gmm::mult(A, shat, t); - omega = gmm::vect_sp(t, s) / gmm::vect_norm2_sqr(t); - - gmm::add(gmm::scaled(phat, alpha), x); - gmm::add(gmm::scaled(shat, omega), x); - gmm::add(s, gmm::scaled(t, -omega), r); - norm_r = gmm::vect_norm2(r); - rho_2 = rho_1; - - ++iter; - } - } - - template - void bicgstab(const Matrix& A, const Vector& x, const VectorB& b, - const Preconditioner& M, iteration &iter) - { bicgstab(A, linalg_const_cast(x), b, M, iter); } - -} - - -#endif // GMM_SOLVER_BICGSTAB_H__ diff --git a/include/gmm/gmm_solver_cg.h b/include/gmm/gmm_solver_cg.h deleted file mode 100644 index c42aad6499b..00000000000 --- a/include/gmm/gmm_solver_cg.h +++ /dev/null @@ -1,212 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of cg.h from ITL. -// See http://osl.iu.edu/research/itl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -/**@file gmm_solver_cg.h - @author Andrew Lumsdaine - @author Lie-Quan Lee - @author Yves Renard - @date October 13, 2002. - @brief Conjugate gradient iterative solver. -*/ -#ifndef GMM_SOLVER_CG_H__ -#define GMM_SOLVER_CG_H__ - -#include "gmm_kernel.h" -#include "gmm_iter.h" - -namespace gmm { - - /* ******************************************************************** */ - /* conjugate gradient */ - /* (preconditionned, with parametrable additional scalar product) */ - /* ******************************************************************** */ - - template - void cg(const Matrix& A, Vector1& x, const Vector2& b, const Matps& PS, - const Precond &P, iteration &iter) { - - typedef typename temporary_dense_vector::vector_type temp_vector; - typedef typename linalg_traits::value_type T; - - T rho, rho_1(0), a; - temp_vector p(vect_size(x)), q(vect_size(x)), r(vect_size(x)), - z(vect_size(x)); - iter.set_rhsnorm(gmm::sqrt(gmm::abs(vect_hp(PS, b, b)))); - - if (iter.get_rhsnorm() == 0.0) - clear(x); - else { - mult(A, scaled(x, T(-1)), b, r); - mult(P, r, z); - rho = vect_hp(PS, z, r); - copy(z, p); - -// #ifdef GMM_USES_MPI -// double t_ref, t_prec = MPI_Wtime(), t_tot = 0; -// static double tmult_tot = 0.0; -// #endif - while (!iter.finished_vect(r)) { - - if (!iter.first()) { - mult(P, r, z); - rho = vect_hp(PS, z, r); - add(z, scaled(p, rho / rho_1), p); - } -// #ifdef GMM_USES_MPI -// t_ref = MPI_Wtime(); -// cout << "mult CG " << endl; -// #endif - mult(A, p, q); -// #ifdef GMM_USES_MPI -// tmult_tot += MPI_Wtime()-t_ref; -// cout << "tmult_tot CG = " << tmult_tot << endl; -// #endif - a = rho / vect_hp(PS, q, p); - add(scaled(p, a), x); - add(scaled(q, -a), r); - rho_1 = rho; - -// #ifdef GMM_USES_MPI -// t_tot = MPI_Wtime() - t_prec; -// cout << "temps CG : " << t_tot << endl; -// #endif - ++iter; - } - } - } - - template - void cg(const Matrix& A, Vector1& x, const Vector2& b, const Matps& PS, - const gmm::identity_matrix &, iteration &iter) { - - typedef typename temporary_dense_vector::vector_type temp_vector; - typedef typename linalg_traits::value_type T; - - T rho, rho_1(0), a; - temp_vector p(vect_size(x)), q(vect_size(x)), r(vect_size(x)); - iter.set_rhsnorm(gmm::sqrt(gmm::abs(vect_hp(PS, b, b)))); - - if (iter.get_rhsnorm() == 0.0) - clear(x); - else { - mult(A, scaled(x, T(-1)), b, r); - rho = vect_hp(PS, r, r); - copy(r, p); - -// #ifdef GMM_USES_MPI -// double t_ref, t_prec = MPI_Wtime(), t_tot = 0; -// static double tmult_tot = 0.0; -// #endif - while (!iter.finished_vect(r)) { - - if (!iter.first()) { - rho = vect_hp(PS, r, r); - add(r, scaled(p, rho / rho_1), p); - } -// #ifdef GMM_USES_MPI -// t_ref = MPI_Wtime(); -// cout << "mult CG " << endl; -// #endif - mult(A, p, q); -// #ifdef GMM_USES_MPI -// tmult_tot += MPI_Wtime()-t_ref; -// cout << "tmult_tot CG = " << tmult_tot << endl; -// #endif - a = rho / vect_hp(PS, q, p); - add(scaled(p, a), x); - add(scaled(q, -a), r); - rho_1 = rho; - -// #ifdef GMM_USES_MPI -// t_tot = MPI_Wtime() - t_prec; -// cout << "temps CG : " << t_tot << endl; -// #endif - ++iter; - } - } - } - - template inline - void cg(const Matrix& A, const Vector1& x, const Vector2& b, const Matps& PS, - const Precond &P, iteration &iter) - { cg(A, linalg_const_cast(x), b, PS, P, iter); } - - template inline - void cg(const Matrix& A, Vector1& x, const Vector2& b, - const Precond &P, iteration &iter) - { cg(A, x , b, identity_matrix(), P, iter); } - - template inline - void cg(const Matrix& A, const Vector1& x, const Vector2& b, - const Precond &P, iteration &iter) - { cg(A, x , b , identity_matrix(), P , iter); } - -} - - -#endif // GMM_SOLVER_CG_H__ diff --git a/include/gmm/gmm_solver_constrained_cg.h b/include/gmm/gmm_solver_constrained_cg.h deleted file mode 100644 index 7761412b4e3..00000000000 --- a/include/gmm/gmm_solver_constrained_cg.h +++ /dev/null @@ -1,166 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_solver_constrained_cg.h - @author Yves Renard - @date October 13, 2002. - @brief Constrained conjugate gradient. */ -// preconditionning does not work - -#ifndef GMM_SOLVER_CCG_H__ -#define GMM_SOLVER_CCG_H__ - -#include "gmm_kernel.h" -#include "gmm_iter.h" - -namespace gmm { - - template - void pseudo_inverse(const CMatrix &C, CINVMatrix &CINV, - const Matps& /* PS */, VectorX&) { - // compute the pseudo inverse of the non-square matrix C such - // CINV = inv(C * trans(C)) * C. - // based on a conjugate gradient method. - - // optimisable : copie de la ligne, precalcul de C * trans(C). - - typedef VectorX TmpVec; - typedef size_t size_type; - typedef typename linalg_traits::value_type value_type; - - size_type nr = mat_nrows(C), nc = mat_ncols(C); - - TmpVec d(nr), e(nr), l(nc), p(nr), q(nr), r(nr); - value_type rho, rho_1, alpha; - clear(d); - clear(CINV); - - for (size_type i = 0; i < nr; ++i) { - d[i] = 1.0; rho = 1.0; - clear(e); - copy(d, r); - copy(d, p); - - while (rho >= 1E-38) { /* conjugate gradient to compute e */ - /* which is the i nd row of inv(C * trans(C)) */ - mult(gmm::transposed(C), p, l); - mult(C, l, q); - alpha = rho / vect_sp(p, q); - add(scaled(p, alpha), e); - add(scaled(q, -alpha), r); - rho_1 = rho; - rho = vect_sp(r, r); - add(r, scaled(p, rho / rho_1), p); - } - - mult(transposed(C), e, l); /* l is the i nd row of CINV */ - // cout << "l = " << l << endl; - clean(l, 1E-15); - copy(l, mat_row(CINV, i)); - - d[i] = 0.0; - } - } - - /** Compute the minimum of @f$ 1/2((Ax).x) - bx @f$ under the contraint @f$ Cx <= f @f$ */ - template < typename Matrix, typename CMatrix, typename Matps, - typename VectorX, typename VectorB, typename VectorF, - typename Preconditioner > - void constrained_cg(const Matrix& A, const CMatrix& C, VectorX& x, - const VectorB& b, const VectorF& f,const Matps& PS, - const Preconditioner& M, iteration &iter) { - typedef typename temporary_dense_vector::vector_type TmpVec; - typedef typename temporary_vector::vector_type TmpCVec; - typedef row_matrix TmpCmat; - - typedef size_t size_type; - typedef typename linalg_traits::value_type value_type; - value_type rho = 1.0, rho_1, lambda, gamma; - TmpVec p(vect_size(x)), q(vect_size(x)), q2(vect_size(x)), - r(vect_size(x)), old_z(vect_size(x)), z(vect_size(x)), - memox(vect_size(x)); - std::vector satured(mat_nrows(C)); - clear(p); - iter.set_rhsnorm(sqrt(vect_sp(PS, b, b))); - if (iter.get_rhsnorm() == 0.0) iter.set_rhsnorm(1.0); - - TmpCmat CINV(mat_nrows(C), mat_ncols(C)); - pseudo_inverse(C, CINV, PS, x); - - while(true) { - // computation of residu - copy(z, old_z); - copy(x, memox); - mult(A, scaled(x, -1.0), b, r); - mult(M, r, z); // preconditionner not coherent - bool transition = false; - for (size_type i = 0; i < mat_nrows(C); ++i) { - value_type al = vect_sp(mat_row(C, i), x) - f[i]; - if (al >= -1.0E-15) { - if (!satured[i]) { satured[i] = true; transition = true; } - value_type bb = vect_sp(mat_row(CINV, i), z); - if (bb > 0.0) add(scaled(mat_row(C, i), -bb), z); - } - else - satured[i] = false; - } - - // descent direction - rho_1 = rho; rho = vect_sp(PS, r, z); // ... - - if (iter.finished(rho)) break; - - if (iter.get_noisy() > 0 && transition) std::cout << "transition\n"; - if (transition || iter.first()) gamma = 0.0; - else gamma = std::max(0.0, (rho - vect_sp(PS, old_z, z) ) / rho_1); - // std::cout << "gamma = " << gamma << endl; - // itl::add(r, itl::scaled(p, gamma), p); - add(z, scaled(p, gamma), p); // ... - - ++iter; - // one dimensionnal optimization - mult(A, p, q); - lambda = rho / vect_sp(PS, q, p); - for (size_type i = 0; i < mat_nrows(C); ++i) - if (!satured[i]) { - value_type bb = vect_sp(mat_row(C, i), p) - f[i]; - if (bb > 0.0) - lambda = std::min(lambda, (f[i]-vect_sp(mat_row(C, i), x)) / bb); - } - add(x, scaled(p, lambda), x); - add(memox, scaled(x, -1.0), memox); - - } - } - -} - -#endif // GMM_SOLVER_CCG_H__ diff --git a/include/gmm/gmm_solver_gmres.h b/include/gmm/gmm_solver_gmres.h deleted file mode 100644 index 9222c04a1b7..00000000000 --- a/include/gmm/gmm_solver_gmres.h +++ /dev/null @@ -1,173 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 1997-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of gmres.h from ITL. -// See http://osl.iu.edu/research/itl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -/**@file gmm_solver_gmres.h - @author Andrew Lumsdaine - @author Lie-Quan Lee - @author Yves Renard - @date October 13, 2002. - @brief GMRES (Generalized Minimum Residual) iterative solver. -*/ -#ifndef GMM_KRYLOV_GMRES_H -#define GMM_KRYLOV_GMRES_H - -#include "gmm_kernel.h" -#include "gmm_iter.h" -#include "gmm_modified_gram_schmidt.h" - -namespace gmm { - - /** Generalized Minimum Residual - - This solve the unsymmetric linear system Ax = b using restarted GMRES. - - See: Y. Saad and M. Schulter. GMRES: A generalized minimum residual - algorithm for solving nonsysmmetric linear systems, SIAM - J. Sci. Statist. Comp. 7(1986), pp, 856-869 - */ - template - void gmres(const Mat &A, Vec &x, const VecB &b, const Precond &M, - int restart, iteration &outer, Basis& KS) { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - std::vector w(vect_size(x)), r(vect_size(x)), u(vect_size(x)); - std::vector c_rot(restart+1), s_rot(restart+1), s(restart+1); - gmm::dense_matrix H(restart+1, restart); -#ifdef GMM_USES_MPI - double t_ref, t_prec = MPI_Wtime(), t_tot = 0; - static double tmult_tot = 0.0; -t_ref = MPI_Wtime(); - cout << "GMRES " << endl; -#endif - mult(M,b,r); - outer.set_rhsnorm(gmm::vect_norm2(r)); - if (outer.get_rhsnorm() == 0.0) { clear(x); return; } - - mult(A, scaled(x, -1), b, w); - mult(M, w, r); - R beta = gmm::vect_norm2(r), beta_old = beta; - int blocked = 0; - - iteration inner = outer; - inner.reduce_noisy(); - inner.set_maxiter(restart); - inner.set_name("GMRes inner"); - - while (! outer.finished(beta)) { - - gmm::copy(gmm::scaled(r, R(1)/beta), KS[0]); - gmm::clear(s); - s[0] = beta; - - size_type i = 0; inner.init(); - - do { - mult(A, KS[i], u); - mult(M, u, KS[i+1]); - orthogonalize(KS, mat_col(H, i), i); - R a = gmm::vect_norm2(KS[i+1]); - H(i+1, i) = T(a); - gmm::scale(KS[i+1], T(1) / a); - for (size_type k = 0; k < i; ++k) - Apply_Givens_rotation_left(H(k,i), H(k+1,i), c_rot[k], s_rot[k]); - - Givens_rotation(H(i,i), H(i+1,i), c_rot[i], s_rot[i]); - Apply_Givens_rotation_left(H(i,i), H(i+1,i), c_rot[i], s_rot[i]); - Apply_Givens_rotation_left(s[i], s[i+1], c_rot[i], s_rot[i]); - - ++inner, ++outer, ++i; - } while (! inner.finished(gmm::abs(s[i]))); - - upper_tri_solve(H, s, i, false); - combine(KS, s, x, i); - mult(A, gmm::scaled(x, -1), b, w); - mult(M, w, r); - beta_old = std::min(beta, beta_old); beta = gmm::vect_norm2(r); - if (int(inner.get_iteration()) < restart -1 || beta_old <= beta) - ++blocked; else blocked = 0; - if (blocked > 10) { - if (outer.get_noisy()) cout << "Gmres is blocked, exiting\n"; - break; - } -#ifdef GMM_USES_MPI - t_tot = MPI_Wtime() - t_ref; - cout << "temps GMRES : " << t_tot << endl; -#endif - } - } - - - template - void gmres(const Mat &A, Vec &x, const VecB &b, - const Precond &M, int restart, iteration& outer) { - typedef typename linalg_traits::value_type T; - modified_gram_schmidt orth(restart, vect_size(x)); - gmres(A, x, b, M, restart, outer, orth); - } - -} - -#endif diff --git a/include/gmm/gmm_solver_idgmres.h b/include/gmm/gmm_solver_idgmres.h deleted file mode 100644 index 7778e639247..00000000000 --- a/include/gmm/gmm_solver_idgmres.h +++ /dev/null @@ -1,804 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_solver_idgmres.h - @author Caroline Lecalvez - @author Yves Renard - @date October 6, 2003. - @brief Implicitly restarted and deflated Generalized Minimum Residual. -*/ -#ifndef GMM_IDGMRES_H -#define GMM_IDGMRES_H - -#include "gmm_kernel.h" -#include "gmm_iter.h" -#include "gmm_dense_sylvester.h" - -namespace gmm { - - template compare_vp { - bool operator()(const std::pair &a, - const std::pair &b) const - { return (gmm::abs(a.first) > gmm::abs(b.first)); } - } - - struct idgmres_state { - size_type m, tb_deb, tb_def, p, k, nb_want, nb_unwant; - size_type nb_nolong, tb_deftot, tb_defwant, conv, nb_un, fin; - bool ok; - - idgmres_state(size_type mm, size_type pp, size_type kk) - : m(mm), tb_deb(1), tb_def(0), p(pp), k(kk), nb_want(0), - nb_unwant(0), nb_nolong(0), tb_deftot(0), tb_defwant(0), - conv(0), nb_un(0), fin(0), ok(false); {} - } - - idgmres_state(size_type mm, size_type pp, size_type kk) - : m(mm), tb_deb(1), tb_def(0), p(pp), k(kk), nb_want(0), - nb_unwant(0), nb_nolong(0), tb_deftot(0), tb_defwant(0), - conv(0), nb_un(0), fin(0), ok(false); {} - - - template - apply_permutation(CONT &cont, const IND &ind) { - size_type m = ind.end() - ind.begin(); - std::vector sorted(m, false); - - for (size_type l = 0; l < m; ++l) - if (!sorted[l] && ind[l] != l) { - - typeid(cont[0]) aux = cont[l]; - k = ind[l]; - cont[l] = cont[k]; - sorted[l] = true; - - for(k2 = ind[k]; k2 != l; k2 = ind[k]) { - cont[k] = cont[k2]; - sorted[k] = true; - k = k2; - } - cont[k] = aux; - } - } - - - /** Implicitly restarted and deflated Generalized Minimum Residual - - See: C. Le Calvez, B. Molina, Implicitly restarted and deflated - FOM and GMRES, numerical applied mathematics, - (30) 2-3 (1999) pp191-212. - - @param A real or complex unsymmetric matrix. - @param x initial guess vector and final result. - @param b right hand side - @param M preconditionner - @param m size of the subspace between two restarts - @param p number of converged ritz values seeked - @param k size of the remaining Krylov subspace when the p ritz values - have not yet converged 0 <= p <= k < m. - @param tol_vp : tolerance on the ritz values. - @param outer - @param KS - */ - template < typename Mat, typename Vec, typename VecB, typename Precond, - typename Basis > - void idgmres(const Mat &A, Vec &x, const VecB &b, const Precond &M, - size_type m, size_type p, size_type k, double tol_vp, - iteration &outer, Basis& KS) { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - R a, beta; - idgmres_state st(m, p, k); - - std::vector w(vect_size(x)), r(vect_size(x)), u(vect_size(x)); - std::vector c_rot(m+1), s_rot(m+1), s(m+1); - std::vector y(m+1), ztest(m+1), gam(m+1); - std::vector gamma(m+1); - gmm::dense_matrix H(m+1, m), Hess(m+1, m), - Hobl(m+1, m), W(vect_size(x), m+1); - - gmm::clear(H); - - outer.set_rhsnorm(gmm::vect_norm2(b)); - if (outer.get_rhsnorm() == 0.0) { clear(x); return; } - - mult(A, scaled(x, -1.0), b, w); - mult(M, w, r); - beta = gmm::vect_norm2(r); - - iteration inner = outer; - inner.reduce_noisy(); - inner.set_maxiter(m); - inner.set_name("GMRes inner iter"); - - while (! outer.finished(beta)) { - - gmm::copy(gmm::scaled(r, 1.0/beta), KS[0]); - gmm::clear(s); - s[0] = beta; - gmm::copy(s, gamma); - - inner.set_maxiter(m - st.tb_deb + 1); - size_type i = st.tb_deb - 1; inner.init(); - - do { - mult(A, KS[i], u); - mult(M, u, KS[i+1]); - orthogonalize_with_refinment(KS, mat_col(H, i), i); - H(i+1, i) = a = gmm::vect_norm2(KS[i+1]); - gmm::scale(KS[i+1], R(1) / a); - - gmm::copy(mat_col(H, i), mat_col(Hess, i)); - gmm::copy(mat_col(H, i), mat_col(Hobl, i)); - - - for (size_type l = 0; l < i; ++l) - Apply_Givens_rotation_left(H(l,i), H(l+1,i), c_rot[l], s_rot[l]); - - Givens_rotation(H(i,i), H(i+1,i), c_rot[i], s_rot[i]); - Apply_Givens_rotation_left(H(i,i), H(i+1,i), c_rot[i], s_rot[i]); - H(i+1, i) = T(0); - Apply_Givens_rotation_left(s[i], s[i+1], c_rot[i], s_rot[i]); - - ++inner, ++outer, ++i; - } while (! inner.finished(gmm::abs(s[i]))); - - if (inner.converged()) { - gmm::copy(s, y); - upper_tri_solve(H, y, i, false); - combine(KS, y, x, i); - mult(A, gmm::scaled(x, T(-1)), b, w); - mult(M, w, r); - beta = gmm::vect_norm2(r); // + verif sur beta ... à faire - break; - } - - gmm::clear(gam); gam[m] = s[i]; - for (size_type l = m; l > 0; --l) - Apply_Givens_rotation_left(gam[l-1], gam[l], gmm::conj(c_rot[l-1]), - -s_rot[l-1]); - - mult(KS.mat(), gam, r); - beta = gmm::vect_norm2(r); - - mult(Hess, scaled(y, T(-1)), gamma, ztest); - // En fait, d'après Caroline qui s'y connait ztest et gam devrait - // être confondus - // Quand on aura vérifié que ça marche, il faudra utiliser gam à la - // place de ztest. - if (st.tb_def < p) { - T nss = H(m,m-1) / ztest[m]; - nss /= gmm::abs(nss); // ns à calculer plus tard aussi - gmm::copy(KS.mat(), W); gmm::copy(scaled(r, nss /beta), mat_col(W, m)); - - // Computation of the oblique matrix - sub_interval SUBI(0, m); - add(scaled(sub_vector(ztest, SUBI), -Hobl(m, m-1) / ztest[m]), - sub_vector(mat_col(Hobl, m-1), SUBI)); - Hobl(m, m-1) *= nss * beta / ztest[m]; - - /* **************************************************************** */ - /* Locking */ - /* **************************************************************** */ - - // Computation of the Ritz eigenpairs. - std::vector > eval(m); - dense_matrix YB(m-st.tb_def, m-st.tb_def); - std::vector pure(m-st.tb_def, 0); - gmm::clear(YB); - - select_eval(Hobl, eval, YB, pure, st); - - if (st.conv != 0) { - // DEFLATION using the QR Factorization of YB - - T alpha = Lock(W, Hobl, - sub_matrix(YB, sub_interval(0, m-st.tb_def)), - sub_interval(st.tb_def, m-st.tb_def), - (st.tb_defwant < p)); - // ns *= alpha; // à calculer plus tard ?? - // V(:,m+1) = alpha*V(:, m+1); ça devait servir à qlq chose ... - - - // Clean the portions below the diagonal corresponding - // to the lock Schur vectors - - for (size_type j = st.tb_def; j < st.tb_deftot; ++j) { - if ( pure[j-st.tb_def] == 0) - gmm::clear(sub_vector(mat_col(Hobl,j), sub_interval(j+1,m-j))); - else if (pure[j-st.tb_def] == 1) { - gmm::clear(sub_matrix(Hobl, sub_interval(j+2,m-j-1), - sub_interval(j, 2))); - ++j; - } - else GMM_ASSERT3(false, "internal error"); - } - - if (!st.ok) { - - // attention si m = 0; - size_type mm = std::min(k+st.nb_unwant+st.nb_nolong, m-1); - - if (eval_sort[m-mm-1].second != R(0) - && eval_sort[m-mm-1].second == -eval_sort[m-mm].second) ++mm; - - std::vector > shifts(m-mm); - for (size_type i = 0; i < m-mm; ++i) - shifts[i] = eval_sort[i].second; - - apply_shift_to_Arnoldi_factorization(W, Hobl, shifts, mm, - m-mm, true); - - st.fin = mm; - } - else - st.fin = st.tb_deftot; - - - /* ************************************************************** */ - /* Purge */ - /* ************************************************************** */ - - if (st.nb_nolong + st.nb_unwant > 0) { - - std::vector > eval(m); - dense_matrix YB(st.fin, st.tb_deftot); - std::vector pure(st.tb_deftot, 0); - gmm::clear(YB); - st.nb_un = st.nb_nolong + st.nb_unwant; - - select_eval_for_purging(Hobl, eval, YB, pure, st); - - T alpha = Lock(W, Hobl, YB, sub_interval(0, st.fin), ok); - - // Clean the portions below the diagonal corresponding - // to the unwanted lock Schur vectors - - for (size_type j = 0; j < st.tb_deftot; ++j) { - if ( pure[j] == 0) - gmm::clear(sub_vector(mat_col(Hobl,j), sub_interval(j+1,m-j))); - else if (pure[j] == 1) { - gmm::clear(sub_matrix(Hobl, sub_interval(j+2,m-j-1), - sub_interval(j, 2))); - ++j; - } - else GMM_ASSERT3(false, "internal error"); - } - - gmm::dense_matrix z(st.nb_un, st.fin - st.nb_un); - sub_interval SUBI(0, st.nb_un), SUBJ(st.nb_un, st.fin - st.nb_un); - sylvester(sub_matrix(Hobl, SUBI), - sub_matrix(Hobl, SUBJ), - sub_matrix(gmm::scaled(Hobl, -T(1)), SUBI, SUBJ), z); - - } - - } - - } - } - } - - - template < typename Mat, typename Vec, typename VecB, typename Precond > - void idgmres(const Mat &A, Vec &x, const VecB &b, - const Precond &M, size_type m, iteration& outer) { - typedef typename linalg_traits::value_type T; - modified_gram_schmidt orth(m, vect_size(x)); - gmres(A, x, b, M, m, outer, orth); - } - - - // Lock stage of an implicit restarted Arnoldi process. - // 1- QR factorization of YB through Householder matrices - // Q(Rl) = YB - // (0 ) - // 2- Update of the Arnoldi factorization. - // H <- Q*HQ, W <- WQ - // 3- Restore the Hessemberg form of H. - - template - void Lock(gmm::dense_matrix &W, gmm::dense_matrix &H, - const MATYB &YB, const sub_interval SUB, - bool restore, T &ns) { - - size_type n = mat_nrows(W), m = mat_ncols(W) - 1; - size_type ncols = mat_ncols(YB), nrows = mat_nrows(YB); - size_type begin = min(SUB); end = max(SUB) - 1; - sub_interval SUBR(0, nrows), SUBC(0, ncols); - T alpha(1); - - GMM_ASSERT2(((end-begin) == ncols) && (m == mat_nrows(H)) - && (m+1 == mat_ncols(H)), "dimensions mismatch"); - - // DEFLATION using the QR Factorization of YB - - dense_matrix QR(n_rows, n_rows); - gmmm::copy(YB, sub_matrix(QR, SUBR, SUBC)); - gmm::clear(submatrix(QR, SUBR, sub_interval(ncols, nrows-ncols))); - qr_factor(QR); - - - apply_house_left(QR, sub_matrix(H, SUB)); - apply_house_right(QR, sub_matrix(H, SUBR, SUB)); - apply_house_right(QR, sub_matrix(W, sub_interval(0, n), SUB)); - - // Restore to the initial block hessenberg form - - if (restore) { - - // verifier quand m = 0 ... - gmm::dense_matrix tab_p(end - st.tb_deftot, end - st.tb_deftot); - gmm::copy(identity_matrix(), tab_p); - - for (size_type j = end-1; j >= st.tb_deftot+2; --j) { - - size_type jm = j-1; - std::vector v(jm - st.tb_deftot); - sub_interval SUBtot(st.tb_deftot, jm - st.tb_deftot); - sub_interval SUBtot2(st.tb_deftot, end - st.tb_deftot); - gmm::copy(sub_vector(mat_row(H, j), SUBtot), v); - house_vector_last(v); - w.resize(end); - col_house_update(sub_matrix(H, SUBI, SUBtot), v, w); - w.resize(end - st.tb_deftot); - row_house_update(sub_matrix(H, SUBtot, SUBtot2), v, w); - gmm::clear(sub_vector(mat_row(H, j), - sub_interval(st.tb_deftot, j-1-st.tb_deftot))); - w.resize(end - st.tb_deftot); - col_house_update(sub_matrix(tab_p, sub_interval(0, end-st.tb_deftot), - sub_interval(0, jm-st.tb_deftot)), v, w); - w.resize(n); - col_house_update(sub_matrix(W, sub_interval(0, n), SUBtot), v, w); - } - - // restore positive subdiagonal elements - - std::vector d(fin-st.tb_deftot); d[0] = T(1); - - // We compute d[i+1] in order - // (d[i+1] * H(st.tb_deftot+i+1,st.tb_deftoti)) / d[i] - // be equal to |H(st.tb_deftot+i+1,st.tb_deftot+i))|. - for (size_type j = 0; j+1 < end-st.tb_deftot; ++j) { - T e = H(st.tb_deftot+j, st.tb_deftot+j-1); - d[j+1] = (e == T(0)) ? T(1) : d[j] * gmm::abs(e) / e; - scale(sub_vector(mat_row(H, st.tb_deftot+j+1), - sub_interval(st.tb_deftot, m-st.tb_deftot)), d[j+1]); - scale(mat_col(H, st.tb_deftot+j+1), T(1) / d[j+1]); - scale(mat_col(W, st.tb_deftot+j+1), T(1) / d[j+1]); - } - - alpha = tab_p(end-st.tb_deftot-1, end-st.tb_deftot-1) / d[end-st.tb_deftot-1]; - alpha /= gmm::abs(alpha); - scale(mat_col(W, m), alpha); - - } - - return alpha; - } - - - - - - - - - // Apply p implicit shifts to the Arnoldi factorization - // AV = VH+H(k+p+1,k+p) V(:,k+p+1) e_{k+p}* - // and produces the following new Arnoldi factorization - // A(VQ) = (VQ)(Q*HQ)+H(k+p+1,k+p) V(:,k+p+1) e_{k+p}* Q - // where only the first k columns are relevant. - // - // Dan Sorensen and Richard J. Radke, 11/95 - template - apply_shift_to_Arnoldi_factorization(dense_matrix V, dense_matrix H, - std::vector Lambda, size_type &k, - size_type p, bool true_shift = false) { - - - size_type k1 = 0, num = 0, kend = k+p, kp1 = k + 1; - bool mark = false; - T c, s, x, y, z; - - dense_matrix q(1, kend); - gmm::clear(q); q(0,kend-1) = T(1); - std::vector hv(3), w(std::max(kend, mat_nrows(V))); - - for(size_type jj = 0; jj < p; ++jj) { - // compute and apply a bulge chase sweep initiated by the - // implicit shift held in w(jj) - - if (abs(Lambda[jj].real()) == 0.0) { - // apply a real shift using 2 by 2 Givens rotations - - for (size_type k1 = 0, k2 = 0; k2 != kend-1; k1 = k2+1) { - k2 = k1; - while (h(k2+1, k2) != T(0) && k2 < kend-1) ++k2; - - Givens_rotation(H(k1, k1) - Lambda[jj], H(k1+1, k1), c, s); - - for (i = k1; i <= k2; ++i) { - if (i > k1) Givens_rotation(H(i, i-1), H(i+1, i-1), c, s); - - // Ne pas oublier de nettoyer H(i+1,i-1) (le mettre à zéro). - // Vérifier qu'au final H(i+1,i) est bien un réel positif. - - // apply rotation from left to rows of H - row_rot(sub_matrix(H, sub_interval(i,2), sub_interval(i, kend-i)), - c, s, 0, 0); - - // apply rotation from right to columns of H - size_type ip2 = std::min(i+2, kend); - col_rot(sub_matrix(H, sub_interval(0, ip2), sub_interval(i, 2)) - c, s, 0, 0); - - // apply rotation from right to columns of V - col_rot(V, c, s, i, i+1); - - // accumulate e' Q so residual can be updated k+p - Apply_Givens_rotation_left(q(0,i), q(0,i+1), c, s); - // peut être que nous utilisons G au lieu de G* et que - // nous allons trop loin en k2. - } - } - - num = num + 1; - } - else { - - // Apply a double complex shift using 3 by 3 Householder - // transformations - - if (jj == p || mark) - mark = false; // skip application of conjugate shift - else { - num = num + 2; // mark that a complex conjugate - mark = true; // pair has been applied - - // Indices de fin de boucle à surveiller... de près ! - for (size_type k1 = 0, k3 = 0; k3 != kend-2; k1 = k3+1) { - k3 = k1; - while (h(k3+1, k3) != T(0) && k3 < kend-2) ++k3; - size_type k2 = k1+1; - - - x = H(k1,k1) * H(k1,k1) + H(k1,k2) * H(k2,k1) - - 2.0*Lambda[jj].real() * H(k1,k1) + gmm::abs_sqr(Lambda[jj]); - y = H(k2,k1) * (H(k1,k1) + H(k2,k2) - 2.0*Lambda[jj].real()); - z = H(k2+1,k2) * H(k2,k1); - - for (size_type i = k1; i <= k3; ++i) { - if (i > k1) { - x = H(i, i-1); - y = H(i+1, i-1); - z = H(i+2, i-1); - // Ne pas oublier de nettoyer H(i+1,i-1) et H(i+2,i-1) - // (les mettre à zéro). - } - - hv[0] = x; hv[1] = y; hv[2] = z; - house_vector(v); - - // Vérifier qu'au final H(i+1,i) est bien un réel positif - - // apply transformation from left to rows of H - w.resize(kend-i); - row_house_update(sub_matrix(H, sub_interval(i, 2), - sub_interval(i, kend-i)), v, w); - - // apply transformation from right to columns of H - - size_type ip3 = std::min(kend, i + 3); - w.resize(ip3); - col_house_update(sub_matrix(H, sub_interval(0, ip3), - sub_interval(i, 2)), v, w); - - // apply transformation from right to columns of V - - w.resize(mat_nrows(V)); - col_house_update(sub_matrix(V, sub_interval(0, mat_nrows(V)), - sub_interval(i, 2)), v, w); - - // accumulate e' Q so residual can be updated k+p - - w.resize(1); - col_house_update(sub_matrix(q, sub_interval(0,1), - sub_interval(i,2)), v, w); - - } - } - - // clean up step with Givens rotation - - i = kend-2; - c = x; s = y; - if (i > k1) Givens_rotation(H(i, i-1), H(i+1, i-1), c, s); - - // Ne pas oublier de nettoyer H(i+1,i-1) (le mettre à zéro). - // Vérifier qu'au final H(i+1,i) est bien un réel positif. - - // apply rotation from left to rows of H - row_rot(sub_matrix(H, sub_interval(i,2), sub_interval(i, kend-i)), - c, s, 0, 0); - - // apply rotation from right to columns of H - size_type ip2 = std::min(i+2, kend); - col_rot(sub_matrix(H, sub_interval(0, ip2), sub_interval(i, 2)) - c, s, 0, 0); - - // apply rotation from right to columns of V - col_rot(V, c, s, i, i+1); - - // accumulate e' Q so residual can be updated k+p - Apply_Givens_rotation_left(q(0,i), q(0,i+1), c, s); - - } - } - } - - // update residual and store in the k+1 -st column of v - - k = kend - num; - scale(mat_col(V, kend), q(0, k)); - - if (k < mat_nrows(H)) { - if (true_shift) - gmm::copy(mat_col(V, kend), mat_col(V, k)); - else - // v(:,k+1) = v(:,kend+1) + v(:,k+1)*h(k+1,k); - // v(:,k+1) = v(:,kend+1) ; - gmm::add(scaled(mat_col(V, kend), H(kend, kend-1)), - scaled(mat_col(V, k), H(k, k-1)), mat_col(V, k)); - } - - H(k, k-1) = vect_norm2(mat_col(V, k)); - scale(mat_col(V, kend), T(1) / H(k, k-1)); - } - - - - template - void select_eval(const MAT &Hobl, EVAL &eval, MAT &YB, PURE &pure, - idgmres_state &st) { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - size_type m = st.m; - - // Computation of the Ritz eigenpairs. - - col_matrix< std::vector > evect(m-st.tb_def, m-st.tb_def); - // std::vector > eval(m); - std::vector ritznew(m, T(-1)); - - // dense_matrix evect_lock(st.tb_def, st.tb_def); - - sub_interval SUB1(st.tb_def, m-st.tb_def); - implicit_qr_algorithm(sub_matrix(Hobl, SUB1), - sub_vector(eval, SUB1), evect); - sub_interval SUB2(0, st.tb_def); - implicit_qr_algorithm(sub_matrix(Hobl, SUB2), - sub_vector(eval, SUB2), /* evect_lock */); - - for (size_type l = st.tb_def; l < m; ++l) - ritznew[l] = gmm::abs(evect(m-st.tb_def-1, l-st.tb_def) * Hobl(m, m-1)); - - std::vector< std::pair > eval_sort(m); - for (size_type l = 0; l < m; ++l) - eval_sort[l] = std::pair(eval[l], l); - std::sort(eval_sort.begin(), eval_sort.end(), compare_vp()); - - std::vector index(m); - for (size_type l = 0; l < m; ++l) index[l] = eval_sort[l].second; - - std::vector kept(m, false); - std::fill(kept.begin(), kept.begin()+st.tb_def, true); - - apply_permutation(eval, index); - apply_permutation(evect, index); - apply_permutation(ritznew, index); - apply_permutation(kept, index); - - // Which are the eigenvalues that converged ? - // - // nb_want is the number of eigenvalues of - // Hess(tb_def+1:n,tb_def+1:n) that converged and are WANTED - // - // nb_unwant is the number of eigenvalues of - // Hess(tb_def+1:n,tb_def+1:n) that converged and are UNWANTED - // - // nb_nolong is the number of eigenvalues of - // Hess(1:tb_def,1:tb_def) that are NO LONGER WANTED. - // - // tb_deftot is the number of the deflated eigenvalues - // that is tb_def + nb_want + nb_unwant - // - // tb_defwant is the number of the wanted deflated eigenvalues - // that is tb_def + nb_want - nb_nolong - - st.nb_want = 0, st.nb_unwant = 0, st.nb_nolong = 0; - size_type j, ind; - - for (j = 0, ind = 0; j < m-p; ++j) { - if (ritznew[j] == R(-1)) { - if (std::imag(eval[j]) != R(0)) { - st.nb_nolong += 2; ++j; // à adapter dans le cas complexe ... - } - else st.nb_nolong++; - } - else { - if (ritznew[j] - < tol_vp * gmm::abs(eval[j])) { - - for (size_type l = 0, l < m-st.tb_def; ++l) - YB(l, ind) = std::real(evect(l, j)); - kept[j] = true; - ++j; ++st.nb_unwant; ind++; - - if (std::imag(eval[j]) != R(0)) { - for (size_type l = 0, l < m-st.tb_def; ++l) - YB(l, ind) = std::imag(evect(l, j)); - pure[ind-1] = 1; - pure[ind] = 2; - - kept[j] = true; - - st.nb_unwant++; - ++ind; - } - } - } - } - - - for (; j < m; ++j) { - if (ritznew[j] != R(-1)) { - - for (size_type l = 0, l < m-st.tb_def; ++l) - YB(l, ind) = std::real(evect(l, j)); - pure[ind] = 1; - ++ind; - kept[j] = true; - ++st.nb_want; - - if (ritznew[j] - < tol_vp * gmm::abs(eval[j])) { - for (size_type l = 0, l < m-st.tb_def; ++l) - YB(l, ind) = std::imag(evect(l, j)); - pure[ind] = 2; - - j++; - kept[j] = true; - - st.nb_want++; - ++ind; - } - } - } - - std::vector shift(m - st.tb_def - st.nb_want - st.nb_unwant); - for (size_type j = 0, i = 0; j < m; ++j) - if (!kept[j]) shift[i++] = eval[j]; - - // st.conv (st.nb_want+st.nb_unwant) is the number of eigenpairs that - // have just converged. - // st.tb_deftot is the total number of eigenpairs that have converged. - - size_type st.conv = ind; - size_type st.tb_deftot = st.tb_def + st.conv; - size_type st.tb_defwant = st.tb_def + st.nb_want - st.nb_nolong; - - sub_interval SUBYB(0, st.conv); - - if ( st.tb_defwant >= p ) { // An invariant subspace has been found. - - st.nb_unwant = 0; - st.nb_want = p + st.nb_nolong - st.tb_def; - st.tb_defwant = p; - - if ( pure[st.conv - st.nb_want + 1] == 2 ) { - ++st.nb_want; st.tb_defwant = ++p;// il faudrait que ce soit un p local - } - - SUBYB = sub_interval(st.conv - st.nb_want, st.nb_want); - // YB = YB(:, st.conv-st.nb_want+1 : st.conv); // On laisse en suspend .. - // pure = pure(st.conv-st.nb_want+1 : st.conv,1); // On laisse suspend .. - st.conv = st.nb_want; - st.tb_deftot = st.tb_def + st.conv; - st.ok = true; - } - - } - - - - template - void select_eval_for_purging(const MAT &Hobl, EVAL &eval, MAT &YB, - PURE &pure, idgmres_state &st) { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - size_type m = st.m; - - // Computation of the Ritz eigenpairs. - - col_matrix< std::vector > evect(st.tb_deftot, st.tb_deftot); - - sub_interval SUB1(0, st.tb_deftot); - implicit_qr_algorithm(sub_matrix(Hobl, SUB1), - sub_vector(eval, SUB1), evect); - std::fill(eval.begin() + st.tb_deftot, eval.end(), std::complex(0)); - - std::vector< std::pair > eval_sort(m); - for (size_type l = 0; l < m; ++l) - eval_sort[l] = std::pair(eval[l], l); - std::sort(eval_sort.begin(), eval_sort.end(), compare_vp()); - - std::vector sorted(m); - std::fill(sorted.begin(), sorted.end(), false); - - std::vector ind(m); - for (size_type l = 0; l < m; ++l) ind[l] = eval_sort[l].second; - - std::vector kept(m, false); - std::fill(kept.begin(), kept.begin()+st.tb_def, true); - - apply_permutation(eval, ind); - apply_permutation(evect, ind); - - size_type j; - for (j = 0; j < st.tb_deftot; ++j) { - - for (size_type l = 0, l < st.tb_deftot; ++l) - YB(l, j) = std::real(evect(l, j)); - - if (std::imag(eval[j]) != R(0)) { - for (size_type l = 0, l < m-st.tb_def; ++l) - YB(l, j+1) = std::imag(evect(l, j)); - pure[j] = 1; - pure[j+1] = 2; - - j += 2; - } - else ++j; - } - } - - - - - - -} - -#endif diff --git a/include/gmm/gmm_solver_qmr.h b/include/gmm/gmm_solver_qmr.h deleted file mode 100644 index f236e83be37..00000000000 --- a/include/gmm/gmm_solver_qmr.h +++ /dev/null @@ -1,209 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 1997-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -// This file is a modified version of qmr.h from ITL. -// See http://osl.iu.edu/research/itl/ -// Following the corresponding Copyright notice. -//=========================================================================== -// -// Copyright (c) 1997-2001, The Trustees of Indiana University. -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the University of California, Berkeley nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE TRUSTEES OF INDIANA UNIVERSITY AND -// CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, -// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE TRUSTEES -// OF INDIANA UNIVERSITY AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -//=========================================================================== - -/**@file gmm_solver_qmr.h - @author Andrew Lumsdaine - @author Lie-Quan Lee - @author Yves Renard - @date October 13, 2002. - @brief Quasi-Minimal Residual iterative solver. -*/ -#ifndef GMM_QMR_H -#define GMM_QMR_H - -#include "gmm_kernel.h" -#include "gmm_iter.h" - -namespace gmm { - - /** Quasi-Minimal Residual. - - This routine solves the unsymmetric linear system Ax = b using - the Quasi-Minimal Residual method. - - See: R. W. Freund and N. M. Nachtigal, A quasi-minimal residual - method for non-Hermitian linear systems, Numerical Math., - 60(1991), pp. 315-339 - - Preconditioner - Incomplete LU, Incomplete LU with threshold, - SSOR or identity_preconditioner. - */ - template - void qmr(const Matrix &A, Vector &x, const VectorB &b, const Precond1 &M1, - iteration& iter) { - - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - T delta(0), ep(0), beta(0), theta_1(0), gamma_1(0); - T theta(0), gamma(1), eta(-1); - R rho_1(0), rho, xi; - - typedef typename temporary_vector::vector_type TmpVec; - size_type nn = vect_size(x); - TmpVec r(nn), v_tld(nn), y(nn), w_tld(nn), z(nn), v(nn), w(nn); - TmpVec y_tld(nn), z_tld(nn), p(nn), q(nn), p_tld(nn), d(nn), s(nn); - - iter.set_rhsnorm(double(gmm::vect_norm2(b))); - if (iter.get_rhsnorm() == 0.0) { clear(x); return; } - - gmm::mult(A, gmm::scaled(x, T(-1)), b, r); - gmm::copy(r, v_tld); - - gmm::left_mult(M1, v_tld, y); - rho = gmm::vect_norm2(y); - - gmm::copy(r, w_tld); - gmm::transposed_right_mult(M1, w_tld, z); - xi = gmm::vect_norm2(z); - - while (! iter.finished_vect(r)) { - - if (rho == R(0) || xi == R(0)) { - if (iter.get_maxiter() == size_type(-1)) - { GMM_ASSERT1(false, "QMR failed to converge"); } - else { GMM_WARNING1("QMR failed to converge"); return; } - } - gmm::copy(gmm::scaled(v_tld, T(R(1)/rho)), v); - gmm::scale(y, T(R(1)/rho)); - - gmm::copy(gmm::scaled(w_tld, T(R(1)/xi)), w); - gmm::scale(z, T(R(1)/xi)); - - delta = gmm::vect_sp(z, y); - if (delta == T(0)) { - if (iter.get_maxiter() == size_type(-1)) - { GMM_ASSERT1(false, "QMR failed to converge"); } - else { GMM_WARNING1("QMR failed to converge"); return; } - } - gmm::right_mult(M1, y, y_tld); - gmm::transposed_left_mult(M1, z, z_tld); - - if (iter.first()) { - gmm::copy(y_tld, p); - gmm::copy(z_tld, q); - } else { - gmm::add(y_tld, gmm::scaled(p, -(T(xi * delta) / ep)), p); - gmm::add(z_tld, gmm::scaled(q, -(T(rho * delta) / ep)), q); - } - - gmm::mult(A, p, p_tld); - - ep = gmm::vect_sp(q, p_tld); - if (ep == T(0)) { - if (iter.get_maxiter() == size_type(-1)) - { GMM_ASSERT1(false, "QMR failed to converge"); } - else { GMM_WARNING1("QMR failed to converge"); return; } - } - beta = ep / delta; - if (beta == T(0)) { - if (iter.get_maxiter() == size_type(-1)) - { GMM_ASSERT1(false, "QMR failed to converge"); } - else { GMM_WARNING1("QMR failed to converge"); return; } - } - gmm::add(p_tld, gmm::scaled(v, -beta), v_tld); - gmm::left_mult(M1, v_tld, y); - - rho_1 = rho; - rho = gmm::vect_norm2(y); - - gmm::mult(gmm::transposed(A), q, w_tld); - gmm::add(w_tld, gmm::scaled(w, -beta), w_tld); - gmm::transposed_right_mult(M1, w_tld, z); - - xi = gmm::vect_norm2(z); - - gamma_1 = gamma; - theta_1 = theta; - - theta = rho / (gamma_1 * beta); - gamma = T(1) / gmm::sqrt(T(1) + gmm::sqr(theta)); - - if (gamma == T(0)) { - if (iter.get_maxiter() == size_type(-1)) - { GMM_ASSERT1(false, "QMR failed to converge"); } - else { GMM_WARNING1("QMR failed to converge"); return; } - } - eta = -eta * T(rho_1) * gmm::sqr(gamma) / (beta * gmm::sqr(gamma_1)); - - if (iter.first()) { - gmm::copy(gmm::scaled(p, eta), d); - gmm::copy(gmm::scaled(p_tld, eta), s); - } else { - T tmp = gmm::sqr(theta_1 * gamma); - gmm::add(gmm::scaled(p, eta), gmm::scaled(d, tmp), d); - gmm::add(gmm::scaled(p_tld, eta), gmm::scaled(s, tmp), s); - } - gmm::add(d, x); - gmm::add(gmm::scaled(s, T(-1)), r); - - ++iter; - } - } - - -} - -#endif - diff --git a/include/gmm/gmm_std.h b/include/gmm/gmm_std.h deleted file mode 100644 index 336fd20ccbb..00000000000 --- a/include/gmm/gmm_std.h +++ /dev/null @@ -1,255 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 1995-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_std.h - @author Yves Renard , - @author Julien Pommier - @date June 01, 1995. - @brief basic setup for gmm (includes, typedefs etc.) -*/ -#ifndef GMM_STD_H__ -#define GMM_STD_H__ - -#ifndef __USE_STD_IOSTREAM -# define __USE_STD_IOSTREAM -#endif - -#ifndef __USE_BSD -# define __USE_BSD -#endif - -#ifndef __USE_ISOC99 -# define __USE_ISOC99 -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1400 // Secure versions for VC++ -# define GMM_SECURE_CRT -# define SECURE_NONCHAR_SSCANF sscanf_s -# define SECURE_NONCHAR_FSCANF fscanf_s -# define SECURE_STRNCPY(a, la, b, lb) strncpy_s(a, la, b, lb) -# define SECURE_FOPEN(F, filename, mode) (*(F) = 0, fopen_s(F, filename, mode)) -# define SECURE_SPRINTF1(S, l, st, p1) sprintf_s(S, l, st, p1) -# define SECURE_SPRINTF2(S, l, st, p1, p2) sprintf_s(S, l, st, p1, p2) -# define SECURE_SPRINTF4(S, l, st, p1, p2, p3, p4) sprintf_s(S, l, st, p1, p2, p3, p4) -# define SECURE_STRDUP(s) _strdup(s) -# ifndef _SCL_SECURE_NO_DEPRECATE -# error Add the option /D_SCL_SECURE_NO_DEPRECATE to the compilation command -# endif -#else -# define SECURE_NONCHAR_SSCANF sscanf -# define SECURE_NONCHAR_FSCANF fscanf -# define SECURE_STRNCPY(a, la, b, lb) strncpy(a, b, lb) -# define SECURE_FOPEN(F, filename, mode) ((*(F)) = fopen(filename, mode)) -# define SECURE_SPRINTF1(S, l, st, p1) sprintf(S, st, p1) -# define SECURE_SPRINTF2(S, l, st, p1, p2) sprintf(S, st, p1, p2) -# define SECURE_SPRINTF4(S, l, st, p1, p2, p3, p4) sprintf(S, st, p1, p2, p3, p4) -# define SECURE_STRDUP(s) strdup(s) -#endif - - -#if !defined(GMM_USES_MPI) && GETFEM_PARA_LEVEL > 0 -# define GMM_USES_MPI -#endif - -/* ********************************************************************** */ -/* Compilers detection. */ -/* ********************************************************************** */ - -/* for sun CC 5.0 ... -#if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x500 -# include -# undef _RWSTD_NO_CLASS_PARTIAL_SPEC -# undef _RWSTD_NO_NAMESPACE -#endif -*/ -/* for VISUAL C++ ... - #if defined(_MSC_VER) // && !defined(__MWERKS__) - #define _GETFEM_MSVCPP_ _MSC_VER - #endif -*/ - -#if defined(__GNUC__) -# if (__GNUC__ < 3) -# error : PLEASE UPDATE g++ TO AT LEAST 3.0 VERSION -# endif -#endif - -/* ********************************************************************** */ -/* C++ Standard Headers. */ -/* ********************************************************************** */ -#include -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -using std::endl; using std::cout; using std::cerr; -using std::ends; using std::cin; - -namespace gmm { - - /* ******************************************************************* */ - /* Clock functions. */ - /* ******************************************************************* */ - -# if defined(HAVE_SYS_TIMES) - inline double uclock_sec(void) { - static double ttclk = 0.; - if (ttclk == 0.) ttclk = sysconf(_SC_CLK_TCK); - tms t; times(&t); return double(t.tms_utime) / ttclk; - } -# else - inline double uclock_sec(void) - { return double(clock())/double(CLOCKS_PER_SEC); } -# endif - - /* ******************************************************************** */ - /* Fixed size integer types. */ - /* ******************************************************************** */ - // Remark : the test program dynamic_array tests the lenght of - // resulting integers - - template struct fixed_size_integer_generator { - typedef void int_base_type; - typedef void uint_base_type; - }; - - template <> struct fixed_size_integer_generator { - typedef signed char int_base_type; - typedef unsigned char uint_base_type; - }; - - template <> struct fixed_size_integer_generator { - typedef signed short int int_base_type; - typedef unsigned short int uint_base_type; - }; - - template <> struct fixed_size_integer_generator { - typedef signed int int_base_type; - typedef unsigned int uint_base_type; - }; - - template <> struct fixed_size_integer_generator { - typedef signed long int_base_type; - typedef unsigned long uint_base_type; - }; - - template <> struct fixed_size_integer_generator { - typedef signed long long int_base_type; - typedef unsigned long long uint_base_type; - }; - - typedef fixed_size_integer_generator<1>::int_base_type int8_type; - typedef fixed_size_integer_generator<1>::uint_base_type uint8_type; - typedef fixed_size_integer_generator<2>::int_base_type int16_type; - typedef fixed_size_integer_generator<2>::uint_base_type uint16_type; - typedef fixed_size_integer_generator<4>::int_base_type int32_type; - typedef fixed_size_integer_generator<4>::uint_base_type uint32_type; - typedef fixed_size_integer_generator<8>::int_base_type int64_type; - typedef fixed_size_integer_generator<8>::uint_base_type uint64_type; - -// #if INT_MAX == 32767 -// typedef signed int int16_type; -// typedef unsigned int uint16_type; -// #elif SHRT_MAX == 32767 -// typedef signed short int int16_type; -// typedef unsigned short int uint16_type; -// #else -// # error "impossible to build a 16 bits integer" -// #endif - -// #if INT_MAX == 2147483647 -// typedef signed int int32_type; -// typedef unsigned int uint32_type; -// #elif SHRT_MAX == 2147483647 -// typedef signed short int int32_type; -// typedef unsigned short int uint32_type; -// #elif LONG_MAX == 2147483647 -// typedef signed long int int32_type; -// typedef unsigned long int uint32_type; -// #else -// # error "impossible to build a 32 bits integer" -// #endif - -// #if INT_MAX == 9223372036854775807L || INT_MAX == 9223372036854775807 -// typedef signed int int64_type; -// typedef unsigned int uint64_type; -// #elif LONG_MAX == 9223372036854775807L || LONG_MAX == 9223372036854775807 -// typedef signed long int int64_type; -// typedef unsigned long int uint64_type; -// #elif LLONG_MAX == 9223372036854775807LL || LLONG_MAX == 9223372036854775807L || LLONG_MAX == 9223372036854775807 -// typedef signed long long int int64_type; -// typedef unsigned long long int uint64_type; -// #else -// # error "impossible to build a 64 bits integer" -// #endif - -#if defined(__GNUC__) && !defined(__ICC) -/* - g++ can issue a warning at each usage of a function declared with this special attribute - (also works with typedefs and variable declarations) -*/ -# define IS_DEPRECATED __attribute__ ((__deprecated__)) -/* - the specified function is inlined at any optimization level -*/ -# define ALWAYS_INLINE __attribute__((always_inline)) -#else -# define IS_DEPRECATED -# define ALWAYS_INLINE -#endif - -} - -#endif /* GMM_STD_H__ */ - diff --git a/include/gmm/gmm_sub_index.h b/include/gmm/gmm_sub_index.h deleted file mode 100644 index e56e6fcd3a3..00000000000 --- a/include/gmm/gmm_sub_index.h +++ /dev/null @@ -1,217 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_sub_index.h - @author Yves Renard - @date October 13, 2002. - @brief sub-indices. -*/ - -#ifndef GMM_SUB_INDEX_H__ -#define GMM_SUB_INDEX_H__ - -#include "gmm_def.h" - -namespace gmm { - - /* ******************************************************************** */ - /* sub indices */ - /* ******************************************************************** */ - - struct basic_index : public std::vector { - - mutable size_type nb_ref; - // size_type key1; faire la somme des composantes - // const basic_index *rind; rindex s'il existe - - - size_t operator[](size_type i) const { - return (i < size()) ? std::vector::operator[](i) : size_type(-1); - } - - basic_index() : nb_ref(1) {} - basic_index(size_type j) : std::vector(j), nb_ref(1) {} - template basic_index(IT b, IT e) - : std::vector(e-b), nb_ref(1) { std::copy(b, e, begin()); } - basic_index(const basic_index *pbi) : nb_ref(1) { - const_iterator it = pbi->begin(), ite = pbi->end(); - size_type i = 0; - for ( ; it != ite; ++it) i = std::max(i, *it); - resize(i+1); std::fill(begin(), end(), size_type(-1)); - for (it = pbi->begin(), i = 0; it != ite; ++it, ++i) - std::vector::operator[](*it) = i; - } - void swap(size_type i, size_type j) { - std::swap(std::vector::operator[](i), - std::vector::operator[](j)); - } - - }; - - typedef basic_index *pbasic_index; - - struct index_generator { - - template static pbasic_index create_index(IT begin, IT end) - { return new basic_index(begin, end); } - static pbasic_index create_rindex(pbasic_index pbi) - { return new basic_index(pbi); } - static void attach(pbasic_index pbi) { if (pbi) pbi->nb_ref++; } - static void unattach(pbasic_index pbi) - { if (pbi && --(pbi->nb_ref) == 0) delete pbi; } - - }; - - struct sub_index { - - size_type first_, last_; - typedef basic_index base_type; - typedef base_type::const_iterator const_iterator; - - mutable pbasic_index ind; - mutable pbasic_index rind; - - void comp_extr(void) { - std::vector::const_iterator it = ind->begin(), ite = ind->end(); - if (it != ite) { first_=last_= *it; ++it; } else { first_=last_= 0; } - for (; it != ite; ++it) - { first_ = std::min(first_, *it); last_ = std::max(last_, *it); } - } - - // inline void test_rind(void) const - // { if (!rind) rind = index_generator::create_rindex(ind); } - size_type size(void) const { return ind->size(); } - size_type first(void) const { return first_; } - size_type last(void) const { return last_; } - size_type index(size_type i) const { return (*ind)[i]; } - size_type rindex(size_type i) const { - // test_rind(); - if (i < rind->size()) return (*rind)[i]; else return size_type(-1); - } - - const_iterator begin(void) const { return ind->begin(); } - const_iterator end(void) const { return ind->end(); } - const_iterator rbegin(void) const {/*test_rind();*/ return rind->begin(); } - const_iterator rend(void) const {/*test_rind();*/ return rind->end(); } - - sub_index() : ind(0), rind(0) {} - template sub_index(IT it, IT ite) - : ind(index_generator::create_index(it, ite)), - rind(index_generator::create_rindex(ind)) { comp_extr(); } - template sub_index(const CONT &c) - : ind(index_generator::create_index(c.begin(), c.end())), - rind(index_generator::create_rindex(ind)) - { comp_extr(); } - ~sub_index() - { index_generator::unattach(rind); index_generator::unattach(ind); } - sub_index(const sub_index &si) : first_(si.first_), last_(si.last_), - ind(si.ind), rind(si.rind) - { index_generator::attach(rind); index_generator::attach(ind); } - sub_index &operator =(const sub_index &si) { - index_generator::unattach(rind); index_generator::unattach(ind); - ind = si.ind; rind = si.rind; index_generator::attach(rind); - index_generator::attach(ind); - first_ = si.first_; last_ = si.last_; - return *this; - } - }; - - struct unsorted_sub_index : public sub_index { - template unsorted_sub_index(IT it, IT ite) - : sub_index(it, ite) {} - template unsorted_sub_index(const CONT &c) - : sub_index(c) {} - unsorted_sub_index() {} - unsorted_sub_index(const unsorted_sub_index &si) : sub_index(si) {} - unsorted_sub_index &operator =(const unsorted_sub_index &si) - { sub_index::operator =(si); return *this; } - void swap(size_type i, size_type j) { - GMM_ASSERT2(ind->nb_ref <= 1, "Operation not allowed on this index"); - if (rind) rind->swap((*ind)[i], (*ind)[j]); - ind->swap(i, j); - } - }; - - inline std::ostream &operator << (std::ostream &o, const sub_index &si) { - o << "sub_index("; - if (si.size() != 0) o << si.index(0); - for (size_type i = 1; i < si.size(); ++i) o << ", " << si.index(i); - o << ")"; - return o; - } - - struct sub_interval { - size_type min, max; - - size_type size(void) const { return max - min; } - size_type first(void) const { return min; } - size_type last(void) const { return max; } - size_type index(size_type i) const { return min + i; } - size_type step(void) const { return 1; } - size_type rindex(size_type i) const - { if (i >= min && i < max) return i - min; return size_type(-1); } - sub_interval(size_type mi, size_type l) : min(mi), max(mi+l) {} - sub_interval() {} - }; - - inline std::ostream &operator << (std::ostream &o, const sub_interval &si) - { o << "sub_interval(" << si.min << ", " << si.size() << ")"; return o; } - - struct sub_slice { - size_type min, max, N; - - size_type size(void) const { return (max - min) / N; } - size_type first(void) const { return min; } - size_type last(void) const { return (min == max) ? max : max+1-N; } - size_type step(void) const { return N; } - size_type index(size_type i) const { return min + N * i; } - size_type rindex(size_type i) const { - if (i >= min && i < max) - { size_type j = (i - min); if (j % N == 0) return j / N; } - return size_type(-1); - } - sub_slice(size_type mi, size_type l, size_type n) - : min(mi), max(mi+l*n), N(n) {} - sub_slice(void) {} - }; - - inline std::ostream &operator << (std::ostream &o, const sub_slice &si) { - o << "sub_slice(" << si.min << ", " << si.size() << ", " << si.step() - << ")"; return o; - } - - template struct index_is_sorted - { typedef linalg_true bool_type; }; - template<> struct index_is_sorted - { typedef linalg_false bool_type; }; - -} - -#endif // GMM_SUB_INDEX_H__ diff --git a/include/gmm/gmm_sub_matrix.h b/include/gmm/gmm_sub_matrix.h deleted file mode 100644 index 54daf5f85d5..00000000000 --- a/include/gmm/gmm_sub_matrix.h +++ /dev/null @@ -1,409 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_sub_matrix.h - @author Yves Renard - @date October 13, 2002. - @brief Generic sub-matrices. -*/ - -#ifndef GMM_SUB_MATRIX_H__ -#define GMM_SUB_MATRIX_H__ - -#include "gmm_sub_vector.h" - -namespace gmm { - - /* ********************************************************************* */ - /* sub row matrices type */ - /* ********************************************************************* */ - - template - struct gen_sub_row_matrix { - typedef gen_sub_row_matrix this_type; - typedef typename std::iterator_traits::value_type M; - typedef M * CPT; - typedef typename std::iterator_traits::reference ref_M; - typedef typename select_ref - ::const_row_iterator, typename linalg_traits::row_iterator, - PT>::ref_type iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - SUBI1 si1; - SUBI2 si2; - iterator begin_; - porigin_type origin; - - reference operator()(size_type i, size_type j) const - { return linalg_traits::access(begin_ + si1.index(i), si2.index(j)); } - - size_type nrows(void) const { return si1.size(); } - size_type ncols(void) const { return si2.size(); } - - gen_sub_row_matrix(ref_M m, const SUBI1 &s1, const SUBI2 &s2) - : si1(s1), si2(s2), begin_(mat_row_begin(m)), - origin(linalg_origin(m)) {} - gen_sub_row_matrix() {} - gen_sub_row_matrix(const gen_sub_row_matrix &cr) : - si1(cr.si1), si2(cr.si2), begin_(cr.begin_),origin(cr.origin) {} - }; - - template - struct gen_sub_row_matrix_iterator { - typedef gen_sub_row_matrix this_type; - typedef typename modifiable_pointer::pointer MPT; - typedef typename std::iterator_traits::value_type M; - typedef typename select_ref - ::const_row_iterator, typename linalg_traits::row_iterator, - PT>::ref_type ITER; - typedef ITER value_type; - typedef ITER *pointer; - typedef ITER &reference; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - typedef std::random_access_iterator_tag iterator_category; - typedef gen_sub_row_matrix_iterator iterator; - - ITER it; - SUBI1 si1; - SUBI2 si2; - size_type ii; - - iterator operator ++(int) { iterator tmp = *this; ii++; return tmp; } - iterator operator --(int) { iterator tmp = *this; ii--; return tmp; } - iterator &operator ++() { ii++; return *this; } - iterator &operator --() { ii--; return *this; } - iterator &operator +=(difference_type i) { ii += i; return *this; } - iterator &operator -=(difference_type i) { ii -= i; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const { return ii - i.ii; } - - ITER operator *() const { return it + si1.index(ii); } - ITER operator [](int i) { return it + si1.index(ii+i); } - - bool operator ==(const iterator &i) const { return (ii == i.ii); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (ii < i.ii); } - - gen_sub_row_matrix_iterator(void) {} - gen_sub_row_matrix_iterator(const - gen_sub_row_matrix_iterator &itm) - : it(itm.it), si1(itm.si1), si2(itm.si2), ii(itm.ii) {} - gen_sub_row_matrix_iterator(const ITER &iter, const SUBI1 &s1, - const SUBI2 &s2, size_type i) - : it(iter), si1(s1), si2(s2), ii(i) { } - - }; - - template - struct linalg_traits > { - typedef gen_sub_row_matrix this_type; - typedef typename std::iterator_traits::value_type M; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type const_col_iterator; - typedef typename sub_vector_type::const_sub_row_type *, SUBI2>::vector_type - const_sub_row_type; - typedef typename select_ref::sub_row_type *, - SUBI2>::vector_type, PT>::ref_type sub_row_type; - typedef gen_sub_row_matrix_iterator::pointer, - SUBI1, SUBI2> const_row_iterator; - typedef typename select_ref, PT>::ref_type - row_iterator; - typedef typename linalg_traits::storage_type - storage_type; - typedef row_major sub_orientation; - typedef linalg_true index_sorted; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_sub_row_type row(const const_row_iterator &it) - { return const_sub_row_type(linalg_traits::row(*it), it.si2); } - static sub_row_type row(const row_iterator &it) - { return sub_row_type(linalg_traits::row(*it), it.si2); } - static const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m.begin_, m.si1, m.si2, 0); } - static row_iterator row_begin(this_type &m) - { return row_iterator(m.begin_, m.si1, m.si2, 0); } - static const_row_iterator row_end(const this_type &m) - { return const_row_iterator(m.begin_, m.si1, m.si2, m.nrows()); } - static row_iterator row_end(this_type &m) - { return row_iterator(m.begin_, m.si1, m.si2, m.nrows()); } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void do_clear(this_type &m) { - row_iterator it = mat_row_begin(m), ite = mat_row_end(m); - for (; it != ite; ++it) clear(row(it)); - } - static value_type access(const const_row_iterator &itrow, size_type i) - { return linalg_traits::access(*itrow, itrow.si2.index(i)); } - static reference access(const row_iterator &itrow, size_type i) - { return linalg_traits::access(*itrow, itrow.si2.index(i)); } - }; - - template - std::ostream &operator <<(std::ostream &o, - const gen_sub_row_matrix& m) - { gmm::write(o,m); return o; } - - - /* ********************************************************************* */ - /* sub column matrices type */ - /* ********************************************************************* */ - - template - struct gen_sub_col_matrix { - typedef gen_sub_col_matrix this_type; - typedef typename std::iterator_traits::value_type M; - typedef M * CPT; - typedef typename std::iterator_traits::reference ref_M; - typedef typename select_ref - ::const_col_iterator, typename linalg_traits::col_iterator, - PT>::ref_type iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - SUBI1 si1; - SUBI2 si2; - iterator begin_; - porigin_type origin; - - reference operator()(size_type i, size_type j) const - { return linalg_traits::access(begin_ + si2.index(j), si1.index(i)); } - - size_type nrows(void) const { return si1.size(); } - size_type ncols(void) const { return si2.size(); } - - gen_sub_col_matrix(ref_M m, const SUBI1 &s1, const SUBI2 &s2) - : si1(s1), si2(s2), begin_(mat_col_begin(m)), - origin(linalg_origin(m)) {} - gen_sub_col_matrix() {} - gen_sub_col_matrix(const gen_sub_col_matrix &cr) : - si1(cr.si1), si2(cr.si2), begin_(cr.begin_),origin(cr.origin) {} - }; - - template - struct gen_sub_col_matrix_iterator { - typedef gen_sub_col_matrix this_type; - typedef typename modifiable_pointer::pointer MPT; - typedef typename std::iterator_traits::value_type M; - typedef typename select_ref::const_col_iterator, - typename linalg_traits::col_iterator, - PT>::ref_type ITER; - typedef ITER value_type; - typedef ITER *pointer; - typedef ITER &reference; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - typedef std::random_access_iterator_tag iterator_category; - typedef gen_sub_col_matrix_iterator iterator; - - ITER it; - SUBI1 si1; - SUBI2 si2; - size_type ii; - - iterator operator ++(int) { iterator tmp = *this; ii++; return tmp; } - iterator operator --(int) { iterator tmp = *this; ii--; return tmp; } - iterator &operator ++() { ii++; return *this; } - iterator &operator --() { ii--; return *this; } - iterator &operator +=(difference_type i) { ii += i; return *this; } - iterator &operator -=(difference_type i) { ii -= i; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const { return ii - i.ii; } - - ITER operator *() const { return it + si2.index(ii); } - ITER operator [](int i) { return it + si2.index(ii+i); } - - bool operator ==(const iterator &i) const { return (ii == i.ii); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (ii < i.ii); } - - gen_sub_col_matrix_iterator(void) {} - gen_sub_col_matrix_iterator(const - gen_sub_col_matrix_iterator &itm) - : it(itm.it), si1(itm.si1), si2(itm.si2), ii(itm.ii) {} - gen_sub_col_matrix_iterator(const ITER &iter, const SUBI1 &s1, - const SUBI2 &s2, size_type i) - : it(iter), si1(s1), si2(s2), ii(i) { } - }; - - template - struct linalg_traits > { - typedef gen_sub_col_matrix this_type; - typedef typename std::iterator_traits::value_type M; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type const_row_iterator; - typedef typename sub_vector_type::const_sub_col_type *, SUBI1>::vector_type - const_sub_col_type; - typedef typename select_ref::sub_col_type *, - SUBI1>::vector_type, PT>::ref_type sub_col_type; - typedef gen_sub_col_matrix_iterator::pointer, - SUBI1, SUBI2> const_col_iterator; - typedef typename select_ref, PT>::ref_type - col_iterator; - typedef col_major sub_orientation; - typedef linalg_true index_sorted; - typedef typename linalg_traits::storage_type - storage_type; - static size_type nrows(const this_type &m) { return m.nrows(); } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_sub_col_type col(const const_col_iterator &it) - { return const_sub_col_type(linalg_traits::col(*it), it.si1); } - static sub_col_type col(const col_iterator &it) - { return sub_col_type(linalg_traits::col(*it), it.si1); } - static const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m.begin_, m.si1, m.si2, 0); } - static col_iterator col_begin(this_type &m) - { return col_iterator(m.begin_, m.si1, m.si2, 0); } - static const_col_iterator col_end(const this_type &m) - { return const_col_iterator(m.begin_, m.si1, m.si2, m.ncols()); } - static col_iterator col_end(this_type &m) - { return col_iterator(m.begin_, m.si1, m.si2, m.ncols()); } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void do_clear(this_type &m) { - col_iterator it = mat_col_begin(m), ite = mat_col_end(m); - for (; it != ite; ++it) clear(col(it)); - } - static value_type access(const const_col_iterator &itcol, size_type i) - { return linalg_traits::access(*itcol, itcol.si1.index(i)); } - static reference access(const col_iterator &itcol, size_type i) - { return linalg_traits::access(*itcol, itcol.si1.index(i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const gen_sub_col_matrix& m) - { gmm::write(o,m); return o; } - - /* ******************************************************************** */ - /* sub matrices */ - /* ******************************************************************** */ - - template - struct sub_matrix_type_ { - typedef abstract_null_type return_type; - }; - template - struct sub_matrix_type_ - { typedef gen_sub_col_matrix matrix_type; }; - template - struct sub_matrix_type_ - { typedef gen_sub_row_matrix matrix_type; }; - template - struct sub_matrix_type { - typedef typename std::iterator_traits::value_type M; - typedef typename sub_matrix_type_::sub_orientation>::potype>::matrix_type matrix_type; - }; - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - M *>::return_type - sub_matrix(M &m, const SUBI1 &si1, const SUBI2 &si2) { - GMM_ASSERT2(si1.last() <= mat_nrows(m) && si2.last() <= mat_ncols(m), - "sub matrix too large"); - return typename select_return::matrix_type, typename sub_matrix_type - ::matrix_type, M *>::return_type(linalg_cast(m), si1, si2); - } - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - const M *>::return_type - sub_matrix(const M &m, const SUBI1 &si1, const SUBI2 &si2) { - GMM_ASSERT2(si1.last() <= mat_nrows(m) && si2.last() <= mat_ncols(m), - "sub matrix too large"); - return typename select_return::matrix_type, typename sub_matrix_type - ::matrix_type, const M *>::return_type(linalg_cast(m), si1, si2); - } - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - M *>::return_type - sub_matrix(M &m, const SUBI1 &si1) { - GMM_ASSERT2(si1.last() <= mat_nrows(m) && si1.last() <= mat_ncols(m), - "sub matrix too large"); - return typename select_return::matrix_type, typename sub_matrix_type - ::matrix_type, M *>::return_type(linalg_cast(m), si1, si1); - } - - template inline - typename select_return - ::matrix_type, typename sub_matrix_type::matrix_type, - const M *>::return_type - sub_matrix(const M &m, const SUBI1 &si1) { - GMM_ASSERT2(si1.last() <= mat_nrows(m) && si1.last() <= mat_ncols(m), - "sub matrix too large"); - return typename select_return::matrix_type, typename sub_matrix_type - ::matrix_type, const M *>::return_type(linalg_cast(m), si1, si1); - } - -} - -#endif // GMM_SUB_MATRIX_H__ diff --git a/include/gmm/gmm_sub_vector.h b/include/gmm/gmm_sub_vector.h deleted file mode 100644 index c9f60e898bf..00000000000 --- a/include/gmm/gmm_sub_vector.h +++ /dev/null @@ -1,557 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_sub_vector.h - @author Yves Renard - @date October 13, 2002. - @brief Generic sub-vectors. -*/ - -#ifndef GMM_SUB_VECTOR_H__ -#define GMM_SUB_VECTOR_H__ - -#include "gmm_interface.h" -#include "gmm_sub_index.h" - -namespace gmm { - - /* ********************************************************************* */ - /* sparse sub-vectors */ - /* ********************************************************************* */ - - template - struct sparse_sub_vector_iterator { - - IT itb, itbe; - SUBI si; - - typedef std::iterator_traits traits_type; - typedef typename traits_type::value_type value_type; - typedef typename traits_type::pointer pointer; - typedef typename traits_type::reference reference; - typedef typename traits_type::difference_type difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - typedef size_t size_type; - typedef sparse_sub_vector_iterator iterator; - - size_type index(void) const { return si.rindex(itb.index()); } - void forward(void); - void backward(void); - iterator &operator ++() - { ++itb; forward(); return *this; } - iterator operator ++(int) { iterator tmp = *this; ++(*this); return tmp; } - iterator &operator --() - { --itb; backward(); return *this; } - iterator operator --(int) { iterator tmp = *this; --(*this); return tmp; } - reference operator *() const { return *itb; } - - bool operator ==(const iterator &i) const { return itb == i.itb; } - bool operator !=(const iterator &i) const { return !(i == *this); } - - sparse_sub_vector_iterator(void) {} - sparse_sub_vector_iterator(const IT &it, const IT &ite, const SUBI &s) - : itb(it), itbe(ite), si(s) { forward(); } - sparse_sub_vector_iterator(const sparse_sub_vector_iterator &it) : itb(it.itb), itbe(it.itbe), si(it.si) {} - }; - - template - void sparse_sub_vector_iterator::forward(void) - { while(itb!=itbe && index()==size_type(-1)) { ++itb; } } - - template - void sparse_sub_vector_iterator::backward(void) - { while(itb!=itbe && index()==size_type(-1)) --itb; } - - template struct sparse_sub_vector { - typedef sparse_sub_vector this_type; - typedef typename std::iterator_traits::value_type V; - typedef V * CPT; - typedef typename select_ref::const_iterator, - typename linalg_traits::iterator, PT>::ref_type iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - SUBI si; - - size_type size(void) const { return si.size(); } - - reference operator[](size_type i) const - { return linalg_traits::access(origin, begin_, end_, si.index(i)); } - - sparse_sub_vector(V &v, const SUBI &s) : begin_(vect_begin(v)), - end_(vect_end(v)), origin(linalg_origin(v)), si(s) {} - sparse_sub_vector(const V &v, const SUBI &s) - : begin_(vect_begin(const_cast(v))), - end_(vect_end(const_cast(v))), - origin(linalg_origin(const_cast(v))), si(s) {} - sparse_sub_vector() {} - sparse_sub_vector(const sparse_sub_vector &cr) - : begin_(cr.begin_),end_(cr.end_),origin(cr.origin), si(cr.si) {} - }; - - template inline - void set_to_begin(sparse_sub_vector_iterator &it, - ORG o, sparse_sub_vector *, - linalg_modifiable) { - typedef sparse_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_begin(it.itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(it.itbe, o, typename linalg_traits::pV(), ref_t()); - it.forward(); - } - template inline - void set_to_begin(sparse_sub_vector_iterator &it, - ORG o, const sparse_sub_vector *, - linalg_modifiable) { - typedef sparse_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_begin(it.itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(it.itbe, o, typename linalg_traits::pV(), ref_t()); - it.forward(); - } - - template inline - void set_to_end(sparse_sub_vector_iterator &it, - ORG o, sparse_sub_vector *, linalg_modifiable) { - typedef sparse_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_end(it.itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(it.itbe, o, typename linalg_traits::pV(), ref_t()); - it.forward(); - } - template inline - void set_to_end(sparse_sub_vector_iterator &it, - ORG o, const sparse_sub_vector *, - linalg_modifiable) { - typedef sparse_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - set_to_end(it.itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(it.itbe, o, typename linalg_traits::pV(), ref_t()); - it.forward(); - } - - template - struct linalg_traits > { - typedef sparse_sub_vector this_type; - typedef this_type * pthis_type; - typedef PT pV; - typedef typename std::iterator_traits::value_type V; - typedef typename linalg_and::bool_type, - typename linalg_traits::index_sorted>::bool_type index_sorted; - typedef typename linalg_traits::is_reference V_reference; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef typename select_ref::const_iterator, - typename linalg_traits::iterator, PT>::ref_type pre_iterator; - typedef typename select_ref, - PT>::ref_type iterator; - typedef sparse_sub_vector_iterator - ::const_iterator, pre_iterator, SUBI> const_iterator; - typedef abstract_sparse storage_type; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { - iterator it; - it.itb = v.begin_; it.itbe = v.end_; it.si = v.si; - if (!is_const_reference(is_reference())) - set_to_begin(it, v.origin, pthis_type(), is_reference()); - else it.forward(); - return it; - } - static const_iterator begin(const this_type &v) { - const_iterator it; it.itb = v.begin_; it.itbe = v.end_; it.si = v.si; - if (!is_const_reference(is_reference())) - { set_to_begin(it, v.origin, pthis_type(), is_reference()); } - else it.forward(); - return it; - } - static iterator end(this_type &v) { - iterator it; - it.itb = v.end_; it.itbe = v.end_; it.si = v.si; - if (!is_const_reference(is_reference())) - set_to_end(it, v.origin, pthis_type(), is_reference()); - else it.forward(); - return it; - } - static const_iterator end(const this_type &v) { - const_iterator it; it.itb = v.end_; it.itbe = v.end_; it.si = v.si; - if (!is_const_reference(is_reference())) - set_to_end(it, v.origin, pthis_type(), is_reference()); - else it.forward(); - return it; - } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void clear(origin_type* o, const iterator &begin_, - const iterator &end_) { - std::deque ind; - iterator it = begin_; - for (; it != end_; ++it) ind.push_front(it.index()); - for (; !(ind.empty()); ind.pop_back()) - access(o, begin_, end_, ind.back()) = value_type(0); - } - static void do_clear(this_type &v) { clear(v.origin, begin(v), end(v)); } - static value_type access(const origin_type *o, const const_iterator &it, - const const_iterator &ite, size_type i) - { return linalg_traits::access(o, it.itb, ite.itb, it.si.index(i)); } - static reference access(origin_type *o, const iterator &it, - const iterator &ite, size_type i) - { return linalg_traits::access(o, it.itb, ite.itb, it.si.index(i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const sparse_sub_vector& m) - { gmm::write(o,m); return o; } - - /* ********************************************************************* */ - /* skyline sub-vectors */ - /* ********************************************************************* */ - - template - struct skyline_sub_vector_iterator { - - IT itb; - SUBI si; - - typedef std::iterator_traits traits_type; - typedef typename traits_type::value_type value_type; - typedef typename traits_type::pointer pointer; - typedef typename traits_type::reference reference; - typedef typename traits_type::difference_type difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - typedef size_t size_type; - typedef skyline_sub_vector_iterator iterator; - - size_type index(void) const - { return (itb.index() - si.min + si.step() - 1) / si.step(); } - void backward(void); - iterator &operator ++() - { itb += si.step(); return *this; } - iterator operator ++(int) { iterator tmp = *this; ++(*this); return tmp; } - iterator &operator --() - { itb -= si.step(); return *this; } - iterator operator --(int) { iterator tmp = *this; --(*this); return tmp; } - - iterator &operator +=(difference_type i) - { itb += si.step() * i; return *this; } - iterator &operator -=(difference_type i) - { itb -= si.step() * i; return *this; } - iterator operator +(difference_type i) const - { iterator ii = *this; return (ii += i); } - iterator operator -(difference_type i) const - { iterator ii = *this; return (ii -= i); } - difference_type operator -(const iterator &i) const - { return (itb - i.itb) / si.step(); } - - reference operator *() const { return *itb; } - reference operator [](int ii) { return *(itb + ii * si.step()); } - - bool operator ==(const iterator &i) const { return index() == i.index();} - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return index() < i.index();} - - skyline_sub_vector_iterator(void) {} - skyline_sub_vector_iterator(const IT &it, const SUBI &s) - : itb(it), si(s) {} - skyline_sub_vector_iterator(const skyline_sub_vector_iterator &it) : itb(it.itb), si(it.si) {} - }; - - template - void update_for_sub_skyline(IT &it, IT &ite, const SUBI &si) { - if (it.index() >= si.max || ite.index() <= si.min) { it = ite; return; } - ptrdiff_t dec1 = si.min - it.index(), dec2 = ite.index() - si.max; - it += (dec1 < 0) ? ((si.step()-((-dec1) % si.step())) % si.step()) : dec1; - ite -= (dec2 < 0) ? -((-dec2) % si.step()) : dec2; - } - - template struct skyline_sub_vector { - typedef skyline_sub_vector this_type; - typedef typename std::iterator_traits::value_type V; - typedef V * pV; - typedef typename select_ref::const_iterator, - typename linalg_traits::iterator, PT>::ref_type iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - SUBI si; - - size_type size(void) const { return si.size(); } - - reference operator[](size_type i) const - { return linalg_traits::access(origin, begin_, end_, si.index(i)); } - - skyline_sub_vector(V &v, const SUBI &s) : begin_(vect_begin(v)), - end_(vect_end(v)), origin(linalg_origin(v)), si(s) { - update_for_sub_skyline(begin_, end_, si); - } - skyline_sub_vector(const V &v, const SUBI &s) - : begin_(vect_begin(const_cast(v))), - end_(vect_end(const_cast(v))), - origin(linalg_origin(const_cast(v))), si(s) { - update_for_sub_skyline(begin_, end_, si); - } - skyline_sub_vector() {} - skyline_sub_vector(const skyline_sub_vector &cr) - : begin_(cr.begin_),end_(cr.end_),origin(cr.origin), si(cr.si) {} - }; - - template inline - void set_to_begin(skyline_sub_vector_iterator &it, - ORG o, skyline_sub_vector *, - linalg_modifiable) { - typedef skyline_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - IT itbe = it.itb; - set_to_begin(it.itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(itbe, o, typename linalg_traits::pV(), ref_t()); - update_for_sub_skyline(it.itb, itbe, it.si); - } - template inline - void set_to_begin(skyline_sub_vector_iterator &it, - ORG o, const skyline_sub_vector *, - linalg_modifiable) { - typedef skyline_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - IT itbe = it.itb; - set_to_begin(it.itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(itbe, o, typename linalg_traits::pV(), ref_t()); - update_for_sub_skyline(it.itb, itbe, it.si); - } - - template inline - void set_to_end(skyline_sub_vector_iterator &it, - ORG o, skyline_sub_vector *, - linalg_modifiable) { - typedef skyline_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - IT itb = it.itb; - set_to_begin(itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(it.itb, o, typename linalg_traits::pV(), ref_t()); - update_for_sub_skyline(itb, it.itb, it.si); - } - template inline - void set_to_end(skyline_sub_vector_iterator &it, - ORG o, const skyline_sub_vector *, - linalg_modifiable) { - typedef skyline_sub_vector VECT; - typedef typename linalg_traits::V_reference ref_t; - IT itb = it.itb; - set_to_begin(itb, o, typename linalg_traits::pV(), ref_t()); - set_to_end(it.itb, o, typename linalg_traits::pV(), ref_t()); - update_for_sub_skyline(itb, it.itb, it.si); - } - - - template - struct linalg_traits > { - typedef skyline_sub_vector this_type; - typedef this_type *pthis_type; - typedef typename std::iterator_traits::value_type V; - typedef typename linalg_traits::is_reference V_reference; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef V * pV; - typedef typename which_reference::is_reference is_reference; - typedef abstract_vector linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef typename linalg_traits::const_iterator const_V_iterator; - typedef typename linalg_traits::iterator V_iterator; - typedef typename select_ref::ref_type pre_iterator; - typedef typename select_ref, - PT>::ref_type iterator; - typedef skyline_sub_vector_iterator - const_iterator; - typedef abstract_skyline storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { - iterator it; - it.itb = v.begin_; it.si = v.si; - if (!is_const_reference(is_reference())) - set_to_begin(it, v.origin, pthis_type(), is_reference()); - return it; - } - static const_iterator begin(const this_type &v) { - const_iterator it; it.itb = v.begin_; it.si = v.si; - if (!is_const_reference(is_reference())) - { set_to_begin(it, v.origin, pthis_type(), is_reference()); } - return it; - } - static iterator end(this_type &v) { - iterator it; - it.itb = v.end_; it.si = v.si; - if (!is_const_reference(is_reference())) - set_to_end(it, v.origin, pthis_type(), is_reference()); - return it; - } - static const_iterator end(const this_type &v) { - const_iterator it; it.itb = v.end_; it.si = v.si; - if (!is_const_reference(is_reference())) - set_to_end(it, v.origin, pthis_type(), is_reference()); - return it; - } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void clear(origin_type*, const iterator &it, const iterator &ite) - { std::fill(it, ite, value_type(0)); } - static void do_clear(this_type &v) { clear(v.origin, begin(v), end(v)); } - static value_type access(const origin_type *o, const const_iterator &it, - const const_iterator &ite, size_type i) - { return linalg_traits::access(o, it.itb, ite.itb, it.si.index(i)); } - static reference access(origin_type *o, const iterator &it, - const iterator &ite, size_type i) - { return linalg_traits::access(o, it.itb, ite.itb, it.si.index(i)); } - }; - - template std::ostream &operator << - (std::ostream &o, const skyline_sub_vector& m) - { gmm::write(o,m); return o; } - - /* ******************************************************************** */ - /* sub vector. */ - /* ******************************************************************** */ - /* sub_vector_type::vector_type is the sub vector type */ - /* returned by sub_vector(v, sub_index) */ - /************************************************************************/ - - template struct svrt_ir { - typedef abstract_null_type vector_type; - }; - - template - struct svrt_ir { - typedef typename std::iterator_traits::value_type V; - typedef typename vect_ref_type::iterator iterator; - typedef tab_ref_index_ref_with_origin vector_type; - }; - - template - struct svrt_ir { - typedef typename std::iterator_traits::value_type V; - typedef typename vect_ref_type::iterator iterator; - typedef tab_ref_index_ref_with_origin vector_type; - }; - - template - struct svrt_ir { - typedef typename std::iterator_traits::value_type V; - typedef typename vect_ref_type::iterator iterator; - typedef tab_ref_with_origin vector_type; - }; - - template - struct svrt_ir { - typedef typename std::iterator_traits::value_type V; - typedef typename vect_ref_type::iterator iterator; - typedef tab_ref_reg_spaced_with_origin vector_type; - }; - - template - struct svrt_ir { - typedef skyline_sub_vector vector_type; - }; - - template - struct svrt_ir { - typedef sparse_sub_vector vector_type; - }; - - template - struct svrt_ir { - typedef sparse_sub_vector vector_type; - }; - - - template - struct svrt_ir { - typedef sparse_sub_vector vector_type; - }; - - template - struct sub_vector_type { - typedef typename std::iterator_traits::value_type V; - typedef typename svrt_ir::storage_type>::vector_type vector_type; - }; - - template - typename select_return< - typename sub_vector_type::vector_type, - typename sub_vector_type::vector_type, const V *>::return_type - sub_vector(const V &v, const SUBI &si) { - GMM_ASSERT2(si.last() <= vect_size(v), "sub vector too large"); - return typename select_return< - typename sub_vector_type::vector_type, - typename sub_vector_type::vector_type, const V *>::return_type - (linalg_cast(v), si); - } - - template - typename select_return< - typename sub_vector_type::vector_type, - typename sub_vector_type::vector_type, V *>::return_type - sub_vector(V &v, const SUBI &si) { - GMM_ASSERT2(si.last() <= vect_size(v), "sub vector too large"); - return typename select_return< - typename sub_vector_type::vector_type, - typename sub_vector_type::vector_type, V *>::return_type - (linalg_cast(v), si); - } - -} - -#endif // GMM_SUB_VECTOR_H__ diff --git a/include/gmm/gmm_superlu_interface.h b/include/gmm/gmm_superlu_interface.h deleted file mode 100644 index fdff16e53e7..00000000000 --- a/include/gmm/gmm_superlu_interface.h +++ /dev/null @@ -1,406 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_superlu_interface.h - @author Yves Renard - @date October 17, 2003. - @brief Interface with SuperLU (LU direct solver for sparse matrices). -*/ -#if defined(GMM_USES_SUPERLU) && !defined(GETFEM_VERSION) - -#ifndef GMM_SUPERLU_INTERFACE_H -#define GMM_SUPERLU_INTERFACE_H - -#include "gmm_kernel.h" - -typedef int int_t; - -/* because SRC/util.h defines TRUE and FALSE ... */ -#ifdef TRUE -# undef TRUE -#endif -#ifdef FALSE -# undef FALSE -#endif - -#include "SRC/slu_Cnames.h" -#include "SRC/supermatrix.h" -#include "SRC/slu_util.h" - -namespace SuperLU_S { -#include "SRC/slu_sdefs.h" -} -namespace SuperLU_D { -#include "SRC/slu_ddefs.h" -} -namespace SuperLU_C { -#include "SRC/slu_cdefs.h" -} -namespace SuperLU_Z { -#include "SRC/slu_zdefs.h" -} - - - -namespace gmm { - - /* interface for Create_CompCol_Matrix */ - - inline void Create_CompCol_Matrix(SuperMatrix *A, int m, int n, int nnz, - float *a, int *ir, int *jc) { - SuperLU_S::sCreate_CompCol_Matrix(A, m, n, nnz, a, ir, jc, - SLU_NC, SLU_S, SLU_GE); - } - - inline void Create_CompCol_Matrix(SuperMatrix *A, int m, int n, int nnz, - double *a, int *ir, int *jc) { - SuperLU_D::dCreate_CompCol_Matrix(A, m, n, nnz, a, ir, jc, - SLU_NC, SLU_D, SLU_GE); - } - - inline void Create_CompCol_Matrix(SuperMatrix *A, int m, int n, int nnz, - std::complex *a, int *ir, int *jc) { - SuperLU_C::cCreate_CompCol_Matrix(A, m, n, nnz, (SuperLU_C::complex *)(a), - ir, jc, SLU_NC, SLU_C, SLU_GE); - } - - inline void Create_CompCol_Matrix(SuperMatrix *A, int m, int n, int nnz, - std::complex *a, int *ir, int *jc) { - SuperLU_Z::zCreate_CompCol_Matrix(A, m, n, nnz, - (SuperLU_Z::doublecomplex *)(a), ir, jc, - SLU_NC, SLU_Z, SLU_GE); - } - - /* interface for Create_Dense_Matrix */ - - inline void Create_Dense_Matrix(SuperMatrix *A, int m, int n, float *a, int k) - { SuperLU_S::sCreate_Dense_Matrix(A, m, n, a, k, SLU_DN, SLU_S, SLU_GE); } - inline void Create_Dense_Matrix(SuperMatrix *A, int m, int n, double *a, int k) - { SuperLU_D::dCreate_Dense_Matrix(A, m, n, a, k, SLU_DN, SLU_D, SLU_GE); } - inline void Create_Dense_Matrix(SuperMatrix *A, int m, int n, - std::complex *a, int k) { - SuperLU_C::cCreate_Dense_Matrix(A, m, n, (SuperLU_C::complex *)(a), - k, SLU_DN, SLU_C, SLU_GE); - } - inline void Create_Dense_Matrix(SuperMatrix *A, int m, int n, - std::complex *a, int k) { - SuperLU_Z::zCreate_Dense_Matrix(A, m, n, (SuperLU_Z::doublecomplex *)(a), - k, SLU_DN, SLU_Z, SLU_GE); - } - - /* interface for gssv */ - -#define DECL_GSSV(NAMESPACE,FNAME,FLOATTYPE,KEYTYPE) \ - inline void SuperLU_gssv(superlu_options_t *options, SuperMatrix *A, int *p, \ - int *q, SuperMatrix *L, SuperMatrix *U, SuperMatrix *B, \ - SuperLUStat_t *stats, int *info, KEYTYPE) { \ - NAMESPACE::FNAME(options, A, p, q, L, U, B, stats, info); \ - } - - DECL_GSSV(SuperLU_S,sgssv,float,float) - DECL_GSSV(SuperLU_C,cgssv,float,std::complex) - DECL_GSSV(SuperLU_D,dgssv,double,double) - DECL_GSSV(SuperLU_Z,zgssv,double,std::complex) - - /* interface for gssvx */ - -#define DECL_GSSVX(NAMESPACE,FNAME,FLOATTYPE,KEYTYPE) \ - inline float SuperLU_gssvx(superlu_options_t *options, SuperMatrix *A, \ - int *perm_c, int *perm_r, int *etree, char *equed, \ - FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \ - SuperMatrix *U, void *work, int lwork, \ - SuperMatrix *B, SuperMatrix *X, \ - FLOATTYPE *recip_pivot_growth, \ - FLOATTYPE *rcond, FLOATTYPE *ferr, FLOATTYPE *berr, \ - SuperLUStat_t *stats, int *info, KEYTYPE) { \ - NAMESPACE::mem_usage_t mem_usage; \ - NAMESPACE::FNAME(options, A, perm_c, perm_r, etree, equed, R, C, L, \ - U, work, lwork, B, X, recip_pivot_growth, rcond, \ - ferr, berr, &mem_usage, stats, info); \ - return mem_usage.for_lu; /* bytes used by the factor storage */ \ - } - - DECL_GSSVX(SuperLU_S,sgssvx,float,float) - DECL_GSSVX(SuperLU_C,cgssvx,float,std::complex) - DECL_GSSVX(SuperLU_D,dgssvx,double,double) - DECL_GSSVX(SuperLU_Z,zgssvx,double,std::complex) - - /* ********************************************************************* */ - /* SuperLU solve interface */ - /* ********************************************************************* */ - - template - void SuperLU_solve(const MAT &A, const VECTX &X_, const VECTB &B, - double& rcond_, int permc_spec = 3) { - VECTX &X = const_cast(X_); - /* - * Get column permutation vector perm_c[], according to permc_spec: - * permc_spec = 0: use the natural ordering - * permc_spec = 1: use minimum degree ordering on structure of A'*A - * permc_spec = 2: use minimum degree ordering on structure of A'+A - * permc_spec = 3: use approximate minimum degree column ordering - */ - typedef typename linalg_traits::value_type T; - typedef typename number_traits::magnitude_type R; - - int m = mat_nrows(A), n = mat_ncols(A), nrhs = 1, info = 0; - - csc_matrix csc_A(m, n); gmm::copy(A, csc_A); - std::vector rhs(m), sol(m); - gmm::copy(B, rhs); - - int nz = nnz(csc_A); - if ((2 * nz / n) >= m) - GMM_WARNING2("CAUTION : it seems that SuperLU has a problem" - " for nearly dense sparse matrices"); - - superlu_options_t options; - set_default_options(&options); - options.ColPerm = NATURAL; - options.PrintStat = NO; - options.ConditionNumber = YES; - switch (permc_spec) { - case 1 : options.ColPerm = MMD_ATA; break; - case 2 : options.ColPerm = MMD_AT_PLUS_A; break; - case 3 : options.ColPerm = COLAMD; break; - } - SuperLUStat_t stat; - StatInit(&stat); - - SuperMatrix SA, SL, SU, SB, SX; // SuperLU format. - Create_CompCol_Matrix(&SA, m, n, nz, csc_A.pr, - (int *)(csc_A.ir), (int *)(csc_A.jc)); - Create_Dense_Matrix(&SB, m, nrhs, &rhs[0], m); - Create_Dense_Matrix(&SX, m, nrhs, &sol[0], m); - memset(&SL,0,sizeof SL); - memset(&SU,0,sizeof SU); - - std::vector etree(n); - char equed[] = "B"; - std::vector Rscale(m),Cscale(n); // row scale factors - std::vector ferr(nrhs), berr(nrhs); - R recip_pivot_gross, rcond; - std::vector perm_r(m), perm_c(n); - - SuperLU_gssvx(&options, &SA, &perm_c[0], &perm_r[0], - &etree[0] /* output */, equed /* output */, - &Rscale[0] /* row scale factors (output) */, - &Cscale[0] /* col scale factors (output) */, - &SL /* fact L (output)*/, &SU /* fact U (output)*/, - NULL /* work */, - 0 /* lwork: superlu auto allocates (input) */, - &SB /* rhs */, &SX /* solution */, - &recip_pivot_gross /* reciprocal pivot growth */ - /* factor max_j( norm(A_j)/norm(U_j) ). */, - &rcond /*estimate of the reciprocal condition */ - /* number of the matrix A after equilibration */, - &ferr[0] /* estimated forward error */, - &berr[0] /* relative backward error */, - &stat, &info, T()); - rcond_ = rcond; - Destroy_SuperMatrix_Store(&SB); - Destroy_SuperMatrix_Store(&SX); - Destroy_SuperMatrix_Store(&SA); - Destroy_SuperNode_Matrix(&SL); - Destroy_CompCol_Matrix(&SU); - StatFree(&stat); - GMM_ASSERT1(info == 0, "SuperLU solve failed: info=" << info); - gmm::copy(sol, X); - } - - template class SuperLU_factor { - typedef typename number_traits::magnitude_type R; - - csc_matrix csc_A; - mutable SuperMatrix SA, SL, SB, SU, SX; - mutable SuperLUStat_t stat; - mutable superlu_options_t options; - float memory_used; - mutable std::vector etree, perm_r, perm_c; - mutable std::vector Rscale, Cscale; - mutable std::vector ferr, berr; - mutable std::vector rhs; - mutable std::vector sol; - mutable bool is_init; - mutable char equed; - - public : - enum { LU_NOTRANSP, LU_TRANSP, LU_CONJUGATED }; - void free_supermatrix(void); - template void build_with(const MAT &A, int permc_spec = 3); - template - /* transp = LU_NOTRANSP -> solves Ax = B - transp = LU_TRANSP -> solves A'x = B - transp = LU_CONJUGATED -> solves conj(A)X = B */ - void solve(const VECTX &X_, const VECTB &B, int transp=LU_NOTRANSP) const; - SuperLU_factor(void) { is_init = false; } - SuperLU_factor(const SuperLU_factor& other) { - GMM_ASSERT2(!(other.is_init), - "copy of initialized SuperLU_factor is forbidden"); - is_init = false; - } - SuperLU_factor& operator=(const SuperLU_factor& other) { - GMM_ASSERT2(!(other.is_init) && !is_init, - "assignment of initialized SuperLU_factor is forbidden"); - return *this; - } - ~SuperLU_factor() { free_supermatrix(); } - float memsize() { return memory_used; } - }; - - - template void SuperLU_factor::free_supermatrix(void) { - if (is_init) { - if (SB.Store) Destroy_SuperMatrix_Store(&SB); - if (SX.Store) Destroy_SuperMatrix_Store(&SX); - if (SA.Store) Destroy_SuperMatrix_Store(&SA); - if (SL.Store) Destroy_SuperNode_Matrix(&SL); - if (SU.Store) Destroy_CompCol_Matrix(&SU); - } - } - - - template template - void SuperLU_factor::build_with(const MAT &A, int permc_spec) { - /* - * Get column permutation vector perm_c[], according to permc_spec: - * permc_spec = 0: use the natural ordering - * permc_spec = 1: use minimum degree ordering on structure of A'*A - * permc_spec = 2: use minimum degree ordering on structure of A'+A - * permc_spec = 3: use approximate minimum degree column ordering - */ - free_supermatrix(); - int n = mat_nrows(A), m = mat_ncols(A), info = 0; - csc_A.init_with(A); - - rhs.resize(m); sol.resize(m); - gmm::clear(rhs); - int nz = nnz(csc_A); - - set_default_options(&options); - options.ColPerm = NATURAL; - options.PrintStat = NO; - options.ConditionNumber = NO; - switch (permc_spec) { - case 1 : options.ColPerm = MMD_ATA; break; - case 2 : options.ColPerm = MMD_AT_PLUS_A; break; - case 3 : options.ColPerm = COLAMD; break; - } - StatInit(&stat); - - Create_CompCol_Matrix(&SA, m, n, nz, csc_A.pr, - (int *)(csc_A.ir), (int *)(csc_A.jc)); - Create_Dense_Matrix(&SB, m, 0, &rhs[0], m); - Create_Dense_Matrix(&SX, m, 0, &sol[0], m); - memset(&SL,0,sizeof SL); - memset(&SU,0,sizeof SU); - equed = 'B'; - Rscale.resize(m); Cscale.resize(n); etree.resize(n); - ferr.resize(1); berr.resize(1); - R recip_pivot_gross, rcond; - perm_r.resize(m); perm_c.resize(n); - memory_used = SuperLU_gssvx(&options, &SA, &perm_c[0], &perm_r[0], - &etree[0] /* output */, &equed /* output */, - &Rscale[0] /* row scale factors (output) */, - &Cscale[0] /* col scale factors (output) */, - &SL /* fact L (output)*/, &SU /* fact U (output)*/, - NULL /* work */, - 0 /* lwork: superlu auto allocates (input) */, - &SB /* rhs */, &SX /* solution */, - &recip_pivot_gross /* reciprocal pivot growth */ - /* factor max_j( norm(A_j)/norm(U_j) ). */, - &rcond /*estimate of the reciprocal condition */ - /* number of the matrix A after equilibration */, - &ferr[0] /* estimated forward error */, - &berr[0] /* relative backward error */, - &stat, &info, T()); - - Destroy_SuperMatrix_Store(&SB); - Destroy_SuperMatrix_Store(&SX); - Create_Dense_Matrix(&SB, m, 1, &rhs[0], m); - Create_Dense_Matrix(&SX, m, 1, &sol[0], m); - StatFree(&stat); - - GMM_ASSERT1(info == 0, "SuperLU solve failed: info=" << info); - is_init = true; - } - - template template - void SuperLU_factor::solve(const VECTX &X_, const VECTB &B, - int transp) const { - VECTX &X = const_cast(X_); - gmm::copy(B, rhs); - options.Fact = FACTORED; - options.IterRefine = NOREFINE; - switch (transp) { - case LU_NOTRANSP: options.Trans = NOTRANS; break; - case LU_TRANSP: options.Trans = TRANS; break; - case LU_CONJUGATED: options.Trans = CONJ; break; - default: GMM_ASSERT1(false, "invalid value for transposition option"); - } - StatInit(&stat); - int info = 0; - R recip_pivot_gross, rcond; - SuperLU_gssvx(&options, &SA, &perm_c[0], &perm_r[0], - &etree[0] /* output */, &equed /* output */, - &Rscale[0] /* row scale factors (output) */, - &Cscale[0] /* col scale factors (output) */, - &SL /* fact L (output)*/, &SU /* fact U (output)*/, - NULL /* work */, - 0 /* lwork: superlu auto allocates (input) */, - &SB /* rhs */, &SX /* solution */, - &recip_pivot_gross /* reciprocal pivot growth */ - /* factor max_j( norm(A_j)/norm(U_j) ). */, - &rcond /*estimate of the reciprocal condition */ - /* number of the matrix A after equilibration */, - &ferr[0] /* estimated forward error */, - &berr[0] /* relative backward error */, - &stat, &info, T()); - StatFree(&stat); - GMM_ASSERT1(info == 0, "SuperLU solve failed: info=" << info); - gmm::copy(sol, X); - } - - template inline - void mult(const SuperLU_factor& P, const V1 &v1, const V2 &v2) { - P.solve(v2,v1); - } - - template inline - void transposed_mult(const SuperLU_factor& P,const V1 &v1,const V2 &v2) { - P.solve(v2, v1, SuperLU_factor::LU_TRANSP); - } - -} - - -#endif // GMM_SUPERLU_INTERFACE_H - -#endif // GMM_USES_SUPERLU diff --git a/include/gmm/gmm_transposed.h b/include/gmm/gmm_transposed.h deleted file mode 100644 index 4fcf57169d7..00000000000 --- a/include/gmm/gmm_transposed.h +++ /dev/null @@ -1,243 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_transposed.h - @author Yves Renard - @date November 10, 2002. - @brief Generic transposed matrices -*/ -#ifndef GMM_TRANSPOSED_H__ -#define GMM_TRANSPOSED_H__ - -#include "gmm_def.h" - -namespace gmm { - - /* ********************************************************************* */ - /* transposed reference */ - /* ********************************************************************* */ - - template struct transposed_row_ref { - - typedef transposed_row_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef M * CPT; - typedef typename std::iterator_traits::reference ref_M; - typedef typename select_ref - ::const_col_iterator, typename linalg_traits - ::col_iterator, PT>::ref_type iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - size_type nr, nc; - - transposed_row_ref(ref_M m) - : begin_(mat_row_begin(m)), end_(mat_row_end(m)), - origin(linalg_origin(m)), nr(mat_ncols(m)), nc(mat_nrows(m)) {} - - transposed_row_ref(const transposed_row_ref &cr) : - begin_(cr.begin_),end_(cr.end_), origin(cr.origin),nr(cr.nr),nc(cr.nc) {} - - reference operator()(size_type i, size_type j) const - { return linalg_traits::access(begin_+j, i); } - }; - - template struct linalg_traits > { - typedef transposed_row_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef typename linalg_traits::storage_type storage_type; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_row_iterator; - typedef typename linalg_traits::const_sub_row_type const_sub_col_type; - typedef typename select_ref::sub_row_type, PT>::ref_type sub_col_type; - typedef typename linalg_traits::const_row_iterator const_col_iterator; - typedef typename select_ref::row_iterator, PT>::ref_type col_iterator; - typedef col_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type ncols(const this_type &v) { return v.nc; } - static size_type nrows(const this_type &v) { return v.nr; } - static const_sub_col_type col(const const_col_iterator &it) - { return linalg_traits::row(it); } - static sub_col_type col(const col_iterator &it) - { return linalg_traits::row(it); } - static col_iterator col_begin(this_type &m) { return m.begin_; } - static col_iterator col_end(this_type &m) { return m.end_; } - static const_col_iterator col_begin(const this_type &m) - { return m.begin_; } - static const_col_iterator col_end(const this_type &m) { return m.end_; } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void do_clear(this_type &v); - static value_type access(const const_col_iterator &itcol, size_type i) - { return linalg_traits::access(itcol, i); } - static reference access(const col_iterator &itcol, size_type i) - { return linalg_traits::access(itcol, i); } - }; - - template - void linalg_traits >::do_clear(this_type &v) { - col_iterator it = mat_col_begin(v), ite = mat_col_end(v); - for (; it != ite; ++it) clear(col(it)); - } - - template std::ostream &operator << - (std::ostream &o, const transposed_row_ref& m) - { gmm::write(o,m); return o; } - - template struct transposed_col_ref { - - typedef transposed_col_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef M * CPT; - typedef typename std::iterator_traits::reference ref_M; - typedef typename select_ref - ::const_row_iterator, typename linalg_traits - ::row_iterator, PT>::ref_type iterator; - typedef typename linalg_traits::reference reference; - typedef typename linalg_traits::porigin_type porigin_type; - - iterator begin_, end_; - porigin_type origin; - size_type nr, nc; - - transposed_col_ref(ref_M m) - : begin_(mat_col_begin(m)), end_(mat_col_end(m)), - origin(linalg_origin(m)), nr(mat_ncols(m)), nc(mat_nrows(m)) {} - - transposed_col_ref(const transposed_col_ref &cr) : - begin_(cr.begin_),end_(cr.end_), origin(cr.origin),nr(cr.nr),nc(cr.nc) {} - - reference operator()(size_type i, size_type j) const - { return linalg_traits::access(begin_+i, j); } - }; - - template struct linalg_traits > { - typedef transposed_col_ref this_type; - typedef typename std::iterator_traits::value_type M; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef typename linalg_traits::storage_type storage_type; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_col_iterator; - typedef typename linalg_traits::const_sub_col_type const_sub_row_type; - typedef typename select_ref::sub_col_type, PT>::ref_type sub_row_type; - typedef typename linalg_traits::const_col_iterator const_row_iterator; - typedef typename select_ref::col_iterator, PT>::ref_type row_iterator; - typedef row_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type nrows(const this_type &v) - { return v.nr; } - static size_type ncols(const this_type &v) - { return v.nc; } - static const_sub_row_type row(const const_row_iterator &it) - { return linalg_traits::col(it); } - static sub_row_type row(const row_iterator &it) - { return linalg_traits::col(it); } - static row_iterator row_begin(this_type &m) { return m.begin_; } - static row_iterator row_end(this_type &m) { return m.end_; } - static const_row_iterator row_begin(const this_type &m) - { return m.begin_; } - static const_row_iterator row_end(const this_type &m) { return m.end_; } - static origin_type* origin(this_type &v) { return v.origin; } - static const origin_type* origin(const this_type &v) { return v.origin; } - static void do_clear(this_type &m); - static value_type access(const const_row_iterator &itrow, size_type i) - { return linalg_traits::access(itrow, i); } - static reference access(const row_iterator &itrow, size_type i) - { return linalg_traits::access(itrow, i); } - }; - - template - void linalg_traits >::do_clear(this_type &v) { - row_iterator it = mat_row_begin(v), ite = mat_row_end(v); - for (; it != ite; ++it) clear(row(it)); - } - - template std::ostream &operator << - (std::ostream &o, const transposed_col_ref& m) - { gmm::write(o,m); return o; } - - template struct transposed_return_ { - typedef abstract_null_type return_type; - }; - template struct transposed_return_ { - typedef typename std::iterator_traits::value_type L; - typedef typename select_return, - transposed_row_ref< L *>, PT>::return_type return_type; - }; - template struct transposed_return_ { - typedef typename std::iterator_traits::value_type L; - typedef typename select_return, - transposed_col_ref< L *>, PT>::return_type return_type; - }; - template struct transposed_return { - typedef typename std::iterator_traits::value_type L; - typedef typename transposed_return_::sub_orientation>::potype, - PT>::return_type return_type; - }; - - template inline - typename transposed_return::return_type transposed(const L &l) { - return typename transposed_return::return_type - (linalg_cast(const_cast(l))); - } - - template inline - typename transposed_return::return_type transposed(L &l) - { return typename transposed_return::return_type(linalg_cast(l)); } - -} - -#endif // GMM_TRANSPOSED_H__ diff --git a/include/gmm/gmm_tri_solve.h b/include/gmm/gmm_tri_solve.h deleted file mode 100644 index b110ac86f45..00000000000 --- a/include/gmm/gmm_tri_solve.h +++ /dev/null @@ -1,221 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_tri_solve.h - @author Yves Renard - @date October 13, 2002. - @brief Solve triangular linear system for dense matrices. -*/ - -#ifndef GMM_TRI_SOLVE_H__ -#define GMM_TRI_SOLVE_H__ - -#include "gmm_interface.h" - -namespace gmm { - - template - void upper_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - col_major, abstract_sparse, bool is_unit) { - typename linalg_traits::value_type x_j; - for (int j = int(k) - 1; j >= 0; --j) { - typedef typename linalg_traits::const_sub_col_type COL; - COL c = mat_const_col(T, j); - typename linalg_traits::const_iterator - it = vect_const_begin(c), ite = vect_const_end(c); - if (!is_unit) x[j] /= c[j]; - for (x_j = x[j]; it != ite ; ++it) - if (int(it.index()) < j) x[it.index()] -= x_j * (*it); - } - } - - template - void upper_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - col_major, abstract_dense, bool is_unit) { - typename linalg_traits::value_type x_j; - for (int j = int(k) - 1; j >= 0; --j) { - typedef typename linalg_traits::const_sub_col_type COL; - COL c = mat_const_col(T, j); - typename linalg_traits::const_iterator - it = vect_const_begin(c), ite = it + j; - typename linalg_traits::iterator itx = vect_begin(x); - if (!is_unit) x[j] /= c[j]; - for (x_j = x[j]; it != ite ; ++it, ++itx) *itx -= x_j * (*it); - } - } - - template - void lower_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - col_major, abstract_sparse, bool is_unit) { - typename linalg_traits::value_type x_j; - // cout << "(lower col)The Tri Matrix = " << T << endl; - // cout << "k = " << endl; - for (int j = 0; j < int(k); ++j) { - typedef typename linalg_traits::const_sub_col_type COL; - COL c = mat_const_col(T, j); - typename linalg_traits::const_iterator - it = vect_const_begin(c), ite = vect_const_end(c); - if (!is_unit) x[j] /= c[j]; - for (x_j = x[j]; it != ite ; ++it) - if (int(it.index()) > j && it.index() < k) x[it.index()] -= x_j*(*it); - } - } - - template - void lower_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - col_major, abstract_dense, bool is_unit) { - typename linalg_traits::value_type x_j; - for (int j = 0; j < int(k); ++j) { - typedef typename linalg_traits::const_sub_col_type COL; - COL c = mat_const_col(T, j); - typename linalg_traits::const_iterator - it = vect_const_begin(c) + (j+1), ite = vect_const_begin(c) + k; - typename linalg_traits::iterator itx = vect_begin(x) + (j+1); - if (!is_unit) x[j] /= c[j]; - for (x_j = x[j]; it != ite ; ++it, ++itx) *itx -= x_j * (*it); - } - } - - - template - void upper_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - row_major, abstract_sparse, bool is_unit) { - typedef typename linalg_traits::const_sub_row_type ROW; - typename linalg_traits::value_type t; - typename linalg_traits::const_row_iterator - itr = mat_row_const_end(T); - for (int i = int(k) - 1; i >= 0; --i) { - --itr; - ROW c = linalg_traits::row(itr); - typename linalg_traits::const_iterator - it = vect_const_begin(c), ite = vect_const_end(c); - for (t = x[i]; it != ite; ++it) - if (int(it.index()) > i && it.index() < k) t -= (*it) * x[it.index()]; - if (!is_unit) x[i] = t / c[i]; else x[i] = t; - } - } - - template - void upper_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - row_major, abstract_dense, bool is_unit) { - typename linalg_traits::value_type t; - - for (int i = int(k) - 1; i >= 0; --i) { - typedef typename linalg_traits::const_sub_row_type ROW; - ROW c = mat_const_row(T, i); - typename linalg_traits::const_iterator - it = vect_const_begin(c) + (i + 1), ite = vect_const_begin(c) + k; - typename linalg_traits::iterator itx = vect_begin(x) + (i+1); - - for (t = x[i]; it != ite; ++it, ++itx) t -= (*it) * (*itx); - if (!is_unit) x[i] = t / c[i]; else x[i] = t; - } - } - - template - void lower_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - row_major, abstract_sparse, bool is_unit) { - typename linalg_traits::value_type t; - - for (int i = 0; i < int(k); ++i) { - typedef typename linalg_traits::const_sub_row_type ROW; - ROW c = mat_const_row(T, i); - typename linalg_traits::const_iterator - it = vect_const_begin(c), ite = vect_const_end(c); - - for (t = x[i]; it != ite; ++it) - if (int(it.index()) < i) t -= (*it) * x[it.index()]; - if (!is_unit) x[i] = t / c[i]; else x[i] = t; - } - } - - template - void lower_tri_solve__(const TriMatrix& T, VecX& x, size_t k, - row_major, abstract_dense, bool is_unit) { - typename linalg_traits::value_type t; - - for (int i = 0; i < int(k); ++i) { - typedef typename linalg_traits::const_sub_row_type ROW; - ROW c = mat_const_row(T, i); - typename linalg_traits::const_iterator - it = vect_const_begin(c), ite = it + i; - typename linalg_traits::iterator itx = vect_begin(x); - - for (t = x[i]; it != ite; ++it, ++itx) t -= (*it) * (*itx); - if (!is_unit) x[i] = t / c[i]; else x[i] = t; - } - } - - -// Triangular Solve: x <-- T^{-1} * x - - template inline - void upper_tri_solve(const TriMatrix& T, VecX &x_, bool is_unit = false) - { upper_tri_solve(T, x_, mat_nrows(T), is_unit); } - - template inline - void lower_tri_solve(const TriMatrix& T, VecX &x_, bool is_unit = false) - { lower_tri_solve(T, x_, mat_nrows(T), is_unit); } - - template inline - void upper_tri_solve(const TriMatrix& T, VecX &x_, size_t k, - bool is_unit) { - VecX& x = const_cast(x_); - GMM_ASSERT2(mat_nrows(T) >= k && vect_size(x) >= k - && mat_ncols(T) >= k && !is_sparse(x_), "dimensions mismatch"); - upper_tri_solve__(T, x, k, - typename principal_orientation_type::sub_orientation>::potype(), - typename linalg_traits::storage_type(), - is_unit); - } - - template inline - void lower_tri_solve(const TriMatrix& T, VecX &x_, size_t k, - bool is_unit) { - VecX& x = const_cast(x_); - GMM_ASSERT2(mat_nrows(T) >= k && vect_size(x) >= k - && mat_ncols(T) >= k && !is_sparse(x_), "dimensions mismatch"); - lower_tri_solve__(T, x, k, - typename principal_orientation_type::sub_orientation>::potype(), - typename linalg_traits::storage_type(), - is_unit); - } - - - - - - -} - - -#endif // GMM_TRI_SOLVE_H__ diff --git a/include/gmm/gmm_vector.h b/include/gmm/gmm_vector.h deleted file mode 100644 index c87c1d23c7e..00000000000 --- a/include/gmm/gmm_vector.h +++ /dev/null @@ -1,968 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2002-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== -/**@file gmm_vector.h - @author Yves Renard - @date October 13, 2002. - @brief Declaration of the vector types (gmm::rsvector, gmm::wsvector, - gmm::slvector ,..) -*/ -#ifndef GMM_VECTOR_H__ -#define GMM_VECTOR_H__ - -#include -#include "gmm_interface.h" - -namespace gmm { - - /*************************************************************************/ - /* */ - /* Class ref_elt_vector: reference on a vector component. */ - /* */ - /*************************************************************************/ - - - template class ref_elt_vector { - - V *pm; - size_type l; - - public : - - operator T() const { return pm->r(l); } - ref_elt_vector(V *p, size_type ll) : pm(p), l(ll) {} - inline ref_elt_vector &operator =(T v) - { (*pm).w(l,v); return *this; } - inline bool operator ==(T v) const { return ((*pm).r(l) == v); } - inline bool operator !=(T v) const { return ((*pm).r(l) != v); } - inline ref_elt_vector &operator +=(T v) - { (*pm).w(l,(*pm).r(l) + v); return *this; } - inline ref_elt_vector &operator -=(T v) - { (*pm).w(l,(*pm).r(l) - v); return *this; } - inline ref_elt_vector &operator /=(T v) - { (*pm).w(l,(*pm).r(l) / v); return *this; } - inline ref_elt_vector &operator *=(T v) - { (*pm).w(l,(*pm).r(l) * v); return *this; } - inline ref_elt_vector &operator =(const ref_elt_vector &re) - { *this = T(re); return *this; } - T operator +() { return T(*this); } // necessary for unknow reason - T operator -() { return -T(*this); } // necessary for unknow reason - T operator +(T v) { return T(*this)+ v; } // necessary for unknow reason - T operator -(T v) { return T(*this)- v; } // necessary for unknow reason - T operator *(T v) { return T(*this)* v; } // necessary for unknow reason - T operator /(T v) { return T(*this)/ v; } // necessary for unknow reason - }; - - - template inline - bool operator ==(T v, const ref_elt_vector &re) { return (v==T(re)); } - template inline - bool operator !=(T v, const ref_elt_vector &re) { return (v!=T(re)); } - template inline - T &operator +=(T &v, const ref_elt_vector &re) - { v += T(re); return v; } - template inline - T &operator -=(T &v, const ref_elt_vector &re) - { v -= T(re); return v; } - template inline - T &operator *=(T &v, const ref_elt_vector &re) - { v *= T(re); return v; } - template inline - T &operator /=(T &v, const ref_elt_vector &re) - { v /= T(re); return v; } - template inline - T operator +(const ref_elt_vector &re) { return T(re); } - template inline - T operator -(const ref_elt_vector &re) { return -T(re); } - template inline - T operator +(const ref_elt_vector &re, T v) { return T(re)+ v; } - template inline - T operator +(T v, const ref_elt_vector &re) { return v+ T(re); } - template inline - T operator -(const ref_elt_vector &re, T v) { return T(re)- v; } - template inline - T operator -(T v, const ref_elt_vector &re) { return v- T(re); } - template inline - T operator *(const ref_elt_vector &re, T v) { return T(re)* v; } - template inline - T operator *(T v, const ref_elt_vector &re) { return v* T(re); } - template inline - T operator /(const ref_elt_vector &re, T v) { return T(re)/ v; } - template inline - T operator /(T v, const ref_elt_vector &re) { return v/ T(re); } - template inline - typename number_traits::magnitude_type - abs(const ref_elt_vector &re) { return gmm::abs(T(re)); } - template inline - T sqr(const ref_elt_vector &re) { return gmm::sqr(T(re)); } - template inline - typename number_traits::magnitude_type - abs_sqr(const ref_elt_vector &re) { return gmm::abs_sqr(T(re)); } - template inline - T conj(const ref_elt_vector &re) { return gmm::conj(T(re)); } - template std::ostream &operator << - (std::ostream &o, const ref_elt_vector &re) { o << T(re); return o; } - template inline - typename number_traits::magnitude_type - real(const ref_elt_vector &re) { return gmm::real(T(re)); } - template inline - typename number_traits::magnitude_type - imag(const ref_elt_vector &re) { return gmm::imag(T(re)); } - - - - /*************************************************************************/ - /* */ - /* Class wsvector: sparse vector optimized for random write operations. */ - /* */ - /*************************************************************************/ - - template struct wsvector_iterator - : public std::map::iterator { - typedef typename std::map::iterator base_it_type; - typedef T value_type; - typedef value_type* pointer; - typedef value_type& reference; - // typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - - reference operator *() const { return (base_it_type::operator*()).second; } - pointer operator->() const { return &(operator*()); } - size_type index(void) const { return (base_it_type::operator*()).first; } - - wsvector_iterator(void) {} - wsvector_iterator(const base_it_type &it) : base_it_type(it) {} - }; - - template struct wsvector_const_iterator - : public std::map::const_iterator { - typedef typename std::map::const_iterator base_it_type; - typedef T value_type; - typedef const value_type* pointer; - typedef const value_type& reference; - // typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - - reference operator *() const { return (base_it_type::operator*()).second; } - pointer operator->() const { return &(operator*()); } - size_type index(void) const { return (base_it_type::operator*()).first; } - - wsvector_const_iterator(void) {} - wsvector_const_iterator(const wsvector_iterator &it) - : base_it_type(it) {} - wsvector_const_iterator(const base_it_type &it) : base_it_type(it) {} - }; - - - /** - sparse vector built upon std::map. - Read and write access are quite fast (log n) - */ - template class wsvector : public std::map { - public: - - typedef typename std::map::size_type size_type; - typedef std::map base_type; - typedef typename base_type::iterator iterator; - typedef typename base_type::const_iterator const_iterator; - - protected: - size_type nbl; - - public: - void clean(double eps); - void resize(size_type); - - inline ref_elt_vector > operator [](size_type c) - { return ref_elt_vector >(this, c); } - - inline void w(size_type c, const T &e) { - GMM_ASSERT2(c < nbl, "out of range"); - if (e == T(0)) { base_type::erase(c); } - else base_type::operator [](c) = e; - } - - inline T r(size_type c) const { - GMM_ASSERT2(c < nbl, "out of range"); - const_iterator it = this->lower_bound(c); - if (it != this->end() && c == it->first) return it->second; - else return T(0); - } - - inline T operator [](size_type c) const { return r(c); } - - size_type nb_stored(void) const { return base_type::size(); } - size_type size(void) const { return nbl; } - - void swap(wsvector &v) - { std::swap(nbl, v.nbl); std::map::swap(v); } - - - /* Constructeurs */ - void init(size_type l) { nbl = l; this->clear(); } - explicit wsvector(size_type l){ init(l); } - wsvector(void) { init(0); } - }; - - template void wsvector::clean(double eps) { - iterator it = this->begin(), itf = it, ite = this->end(); - while (it != ite) { - ++itf; if (gmm::abs(it->second) <= eps) erase(it); it = itf; - } - } - - template void wsvector::resize(size_type n) { - if (n < nbl) { - iterator it = this->begin(), itf = it, ite = this->end(); - while (it != ite) { ++itf; if (it->first >= n) this->erase(it); it = itf; } - } - nbl = n; - } - - template struct linalg_traits > { - typedef wsvector this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_vector linalg_type; - typedef T value_type; - typedef ref_elt_vector > reference; - typedef wsvector_iterator iterator; - typedef wsvector_const_iterator const_iterator; - typedef abstract_sparse storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return v.begin(); } - static const_iterator begin(const this_type &v) { return v.begin(); } - static iterator end(this_type &v) { return v.end(); } - static const_iterator end(const this_type &v) { return v.end(); } - static origin_type* origin(this_type &v) { return &v; } - static const origin_type* origin(const this_type &v) { return &v; } - static void clear(origin_type* o, const iterator &, const iterator &) - { o->clear(); } - static void do_clear(this_type &v) { v.clear(); } - static value_type access(const origin_type *o, const const_iterator &, - const const_iterator &, size_type i) - { return (*o)[i]; } - static reference access(origin_type *o, const iterator &, const iterator &, - size_type i) - { return (*o)[i]; } - static void resize(this_type &v, size_type n) { v.resize(n); } - }; - - template std::ostream &operator << - (std::ostream &o, const wsvector& v) { gmm::write(o,v); return o; } - - /******* Optimized BLAS for wsvector **********************************/ - - template inline void copy(const wsvector &v1, - wsvector &v2) { - GMM_ASSERT2(vect_size(v1) == vect_size(v2), "dimensions mismatch"); - v2 = v1; - } - template inline - void copy(const wsvector &v1, const simple_vector_ref *> &v2){ - simple_vector_ref *> - *svr = const_cast *> *>(&v2); - wsvector - *pv = const_cast *>(v2.origin); - GMM_ASSERT2(vect_size(v1) == vect_size(v2), "dimensions mismatch"); - *pv = v1; svr->begin_ = vect_begin(*pv); svr->end_ = vect_end(*pv); - } - template inline - void copy(const simple_vector_ref *> &v1, - wsvector &v2) - { copy(*(v1.origin), v2); } - template inline - void copy(const simple_vector_ref *> &v1, wsvector &v2) - { copy(*(v1.origin), v2); } - - template inline void clean(wsvector &v, double eps) { - typedef typename number_traits::magnitude_type R; - typename wsvector::iterator it = v.begin(), ite = v.end(), itc; - while (it != ite) - if (gmm::abs((*it).second) <= R(eps)) - { itc=it; ++it; v.erase(itc); } else ++it; - } - - template - inline void clean(const simple_vector_ref *> &l, double eps) { - simple_vector_ref *> - *svr = const_cast *> *>(&l); - wsvector - *pv = const_cast *>((l.origin)); - clean(*pv, eps); - svr->begin_ = vect_begin(*pv); svr->end_ = vect_end(*pv); - } - - template - inline size_type nnz(const wsvector& l) { return l.nb_stored(); } - - /*************************************************************************/ - /* */ - /* rsvector: sparse vector optimized for linear algebra operations. */ - /* */ - /*************************************************************************/ - - template struct elt_rsvector_ { - size_type c; T e; - /* e is initialized by default to avoid some false warnings of valgrind.. - (from http://valgrind.org/docs/manual/mc-manual.html: - - When memory is read into the CPU's floating point registers, the - relevant V bits are read from memory and they are immediately - checked. If any are invalid, an uninitialised value error is - emitted. This precludes using the floating-point registers to copy - possibly-uninitialised memory, but simplifies Valgrind in that it - does not have to track the validity status of the floating-point - registers. - */ - elt_rsvector_(void) : e(0) {} - elt_rsvector_(size_type cc) : c(cc), e(0) {} - elt_rsvector_(size_type cc, const T &ee) : c(cc), e(ee) {} - bool operator < (const elt_rsvector_ &a) const { return c < a.c; } - bool operator == (const elt_rsvector_ &a) const { return c == a.c; } - bool operator != (const elt_rsvector_ &a) const { return c != a.c; } - }; - - template struct rsvector_iterator { - typedef typename std::vector >::iterator IT; - typedef T value_type; - typedef value_type* pointer; - typedef value_type& reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - typedef rsvector_iterator iterator; - - IT it; - - reference operator *() const { return it->e; } - pointer operator->() const { return &(operator*()); } - - iterator &operator ++() { ++it; return *this; } - iterator operator ++(int) { iterator tmp = *this; ++(*this); return tmp; } - iterator &operator --() { --it; return *this; } - iterator operator --(int) { iterator tmp = *this; --(*this); return tmp; } - - bool operator ==(const iterator &i) const { return it == i.it; } - bool operator !=(const iterator &i) const { return !(i == *this); } - - size_type index(void) const { return it->c; } - rsvector_iterator(void) {} - rsvector_iterator(const IT &i) : it(i) {} - }; - - template struct rsvector_const_iterator { - typedef typename std::vector >::const_iterator IT; - typedef T value_type; - typedef const value_type* pointer; - typedef const value_type& reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef std::forward_iterator_tag iterator_category; - typedef rsvector_const_iterator iterator; - - IT it; - - reference operator *() const { return it->e; } - pointer operator->() const { return &(operator*()); } - size_type index(void) const { return it->c; } - - iterator &operator ++() { ++it; return *this; } - iterator operator ++(int) { iterator tmp = *this; ++(*this); return tmp; } - iterator &operator --() { --it; return *this; } - iterator operator --(int) { iterator tmp = *this; --(*this); return tmp; } - - bool operator ==(const iterator &i) const { return it == i.it; } - bool operator !=(const iterator &i) const { return !(i == *this); } - - rsvector_const_iterator(void) {} - rsvector_const_iterator(const rsvector_iterator &i) : it(i.it) {} - rsvector_const_iterator(const IT &i) : it(i) {} - }; - - /** - sparse vector built upon std::vector. Read access is fast, - but insertion is O(n) - */ - template class rsvector : public std::vector > { - public: - - typedef std::vector > base_type_; - typedef typename base_type_::iterator iterator; - typedef typename base_type_::const_iterator const_iterator; - typedef typename base_type_::size_type size_type; - typedef T value_type; - - protected: - size_type nbl; /* size of the vector. */ - - public: - - void sup(size_type j); - void base_resize(size_type n) { base_type_::resize(n); } - void resize(size_type); - - ref_elt_vector > operator [](size_type c) - { return ref_elt_vector >(this, c); } - - void w(size_type c, const T &e); - T r(size_type c) const; - void swap_indices(size_type i, size_type j); - - inline T operator [](size_type c) const { return r(c); } - - size_type nb_stored(void) const { return base_type_::size(); } - size_type size(void) const { return nbl; } - void clear(void) { base_type_::resize(0); } - void swap(rsvector &v) - { std::swap(nbl, v.nbl); std::vector >::swap(v); } - - /* Constructeurs */ - explicit rsvector(size_type l) : nbl(l) { } - rsvector(void) : nbl(0) { } - }; - - template - void rsvector::swap_indices(size_type i, size_type j) { - if (i > j) std::swap(i, j); - if (i != j) { - int situation = 0; - elt_rsvector_ ei(i), ej(j), a; - iterator it, ite, iti, itj; - iti = std::lower_bound(this->begin(), this->end(), ei); - if (iti != this->end() && iti->c == i) situation += 1; - itj = std::lower_bound(this->begin(), this->end(), ej); - if (itj != this->end() && itj->c == j) situation += 2; - - switch (situation) { - case 1 : a = *iti; a.c = j; it = iti; ++it; ite = this->end(); - for (; it != ite && it->c <= j; ++it, ++iti) *iti = *it; - *iti = a; - break; - case 2 : a = *itj; a.c = i; it = itj; ite = this->begin(); - if (it != ite) { - --it; - while (it->c >= i) { *itj = *it; --itj; if (it==ite) break; --it; } - } - *itj = a; - break; - case 3 : std::swap(iti->e, itj->e); - break; - } - } - } - - template void rsvector::sup(size_type j) { - if (nb_stored() != 0) { - elt_rsvector_ ev(j); - iterator it = std::lower_bound(this->begin(), this->end(), ev); - if (it != this->end() && it->c == j) { - for (iterator ite = this->end() - 1; it != ite; ++it) *it = *(it+1); - base_type_::resize(nb_stored()-1); - } - } - } - - template void rsvector::resize(size_type n) { - if (n < nbl) { - for (size_type i = 0; i < nb_stored(); ++i) - if (base_type_::operator[](i).c >= n) { base_resize(i); break; } - } - nbl = n; - } - - template void rsvector::w(size_type c, const T &e) { - GMM_ASSERT2(c < nbl, "out of range"); - if (e == T(0)) sup(c); - else { - elt_rsvector_ ev(c, e); - if (nb_stored() == 0) { - base_type_::resize(1,ev); - } - else { - iterator it = std::lower_bound(this->begin(), this->end(), ev); - if (it != this->end() && it->c == c) it->e = e; - else { - size_type ind = it - this->begin(); - base_type_::resize(nb_stored()+1, ev); - if (ind != nb_stored() - 1) { - it = this->begin() + ind; - for (iterator ite = this->end() - 1; ite != it; --ite) - *ite = *(ite-1); - *it = ev; - } - } - } - } - } - - template T rsvector::r(size_type c) const { - GMM_ASSERT2(c < nbl, "out of range"); - if (nb_stored() != 0) { - elt_rsvector_ ev(c); - const_iterator it = std::lower_bound(this->begin(), this->end(), ev); - if (it != this->end() && it->c == c) return it->e; - } - return T(0); - } - - template struct linalg_traits > { - typedef rsvector this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_vector linalg_type; - typedef T value_type; - typedef ref_elt_vector > reference; - typedef rsvector_iterator iterator; - typedef rsvector_const_iterator const_iterator; - typedef abstract_sparse storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) { return iterator(v.begin()); } - static const_iterator begin(const this_type &v) - { return const_iterator(v.begin()); } - static iterator end(this_type &v) { return iterator(v.end()); } - static const_iterator end(const this_type &v) - { return const_iterator(v.end()); } - static origin_type* origin(this_type &v) { return &v; } - static const origin_type* origin(const this_type &v) { return &v; } - static void clear(origin_type* o, const iterator &, const iterator &) - { o->clear(); } - static void do_clear(this_type &v) { v.clear(); } - static value_type access(const origin_type *o, const const_iterator &, - const const_iterator &, size_type i) - { return (*o)[i]; } - static reference access(origin_type *o, const iterator &, const iterator &, - size_type i) - { return (*o)[i]; } - static void resize(this_type &v, size_type n) { v.resize(n); } - }; - - template std::ostream &operator << - (std::ostream &o, const rsvector& v) { gmm::write(o,v); return o; } - - /******* Optimized operations for rsvector ****************************/ - - template inline void copy(const rsvector &v1, - rsvector &v2) { - GMM_ASSERT2(vect_size(v1) == vect_size(v2), "dimensions mismatch"); - v2 = v1; - } - template inline - void copy(const rsvector &v1, const simple_vector_ref *> &v2){ - simple_vector_ref *> - *svr = const_cast *> *>(&v2); - rsvector - *pv = const_cast *>((v2.origin)); - GMM_ASSERT2(vect_size(v1) == vect_size(v2), "dimensions mismatch"); - *pv = v1; svr->begin_ = vect_begin(*pv); svr->end_ = vect_end(*pv); - } - template inline - void copy(const simple_vector_ref *> &v1, - rsvector &v2) - { copy(*(v1.origin), v2); } - template inline - void copy(const simple_vector_ref *> &v1, rsvector &v2) - { copy(*(v1.origin), v2); } - - template inline void add(const V &v1, - rsvector &v2) { - if ((const void *)(&v1) != (const void *)(&v2)) { - GMM_ASSERT2(vect_size(v1) == vect_size(v2), "dimensions mismatch"); - add_rsvector(v1, v2, typename linalg_traits::storage_type()); - } - } - - template - inline void add_rsvector(const V &v1, rsvector &v2, abstract_dense) - { add(v1, v2, abstract_dense(), abstract_sparse()); } - - template - inline void add_rsvector(const V &v1, rsvector &v2, abstract_skyline) - { add(v1, v2, abstract_skyline(), abstract_sparse()); } - - template - void add_rsvector(const V &v1, rsvector &v2, abstract_sparse) { - add_rsvector(v1, v2, typename linalg_traits::index_sorted()); - } - - template - void add_rsvector(const V &v1, rsvector &v2, linalg_false) { - add(v1, v2, abstract_sparse(), abstract_sparse()); - } - - template - void add_rsvector(const V &v1, rsvector &v2, linalg_true) { - typename linalg_traits::const_iterator it1 = vect_const_begin(v1), - ite1 = vect_const_end(v1); - typename rsvector::iterator it2 = v2.begin(), ite2 = v2.end(), it3; - size_type nbc = 0, old_nbc = v2.nb_stored(); - for (; it1 != ite1 && it2 != ite2 ; ++nbc) - if (it1.index() == it2->c) { ++it1; ++it2; } - else if (it1.index() < it2->c) ++it1; else ++it2; - for (; it1 != ite1; ++it1) ++nbc; - for (; it2 != ite2; ++it2) ++nbc; - - v2.base_resize(nbc); - it3 = v2.begin() + old_nbc; - it2 = v2.end(); ite2 = v2.begin(); - it1 = vect_end(v1); ite1 = vect_const_begin(v1); - while (it1 != ite1 && it3 != ite2) { - --it3; --it1; --it2; - if (it3->c > it1.index()) { *it2 = *it3; ++it1; } - else if (it3->c == it1.index()) { *it2=*it3; it2->e+=*it1; } - else { it2->c = it1.index(); it2->e = *it1; ++it3; } - } - while (it1 != ite1) { --it1; --it2; it2->c = it1.index(); it2->e = *it1; } - } - - template void copy(const V &v1, rsvector &v2) { - if ((const void *)(&v1) != (const void *)(&v2)) { - GMM_ASSERT2(vect_size(v1) == vect_size(v2), "dimensions mismatch"); - if (same_origin(v1, v2)) - GMM_WARNING2("a conflict is possible in vector copy\n"); - copy_rsvector(v1, v2, typename linalg_traits::storage_type()); - } - } - - template - void copy_rsvector(const V &v1, rsvector &v2, abstract_dense) - { copy_vect(v1, v2, abstract_dense(), abstract_sparse()); } - - template - void copy_rsvector(const V &v1, rsvector &v2, abstract_skyline) - { copy_vect(v1, v2, abstract_skyline(), abstract_sparse()); } - - template - void copy_rsvector(const V &v1, rsvector &v2, abstract_sparse) { - copy_rsvector(v1, v2, typename linalg_traits::index_sorted()); - } - - template - void copy_rsvector(const V &v1, rsvector &v2, linalg_true) { - typedef typename linalg_traits::value_type T1; - typename linalg_traits::const_iterator it = vect_const_begin(v1), - ite = vect_const_end(v1); - v2.base_resize(nnz(v1)); - typename rsvector::iterator it2 = v2.begin(); - size_type nn = 0; - for (; it != ite; ++it) - if ((*it) != T1(0)) { it2->c = it.index(); it2->e = *it; ++it2; ++nn; } - v2.base_resize(nn); - } - - template - void copy_rsvector(const V &v1, rsvector &v2, linalg_false) { - typedef typename linalg_traits::value_type T1; - typename linalg_traits::const_iterator it = vect_const_begin(v1), - ite = vect_const_end(v1); - v2.base_resize(nnz(v1)); - typename rsvector::iterator it2 = v2.begin(); - size_type nn = 0; - for (; it != ite; ++it) - if ((*it) != T1(0)) { it2->c = it.index(); it2->e = *it; ++it2; ++nn; } - v2.base_resize(nn); - std::sort(v2.begin(), v2.end()); - } - - template inline void clean(rsvector &v, double eps) { - typedef typename number_traits::magnitude_type R; - typename rsvector::iterator it = v.begin(), ite = v.end(); - for (; it != ite; ++it) if (gmm::abs((*it).e) <= eps) break; - if (it != ite) { - typename rsvector::iterator itc = it; - size_type erased = 1; - for (++it; it != ite; ++it) - { *itc = *it; if (gmm::abs((*it).e) <= R(eps)) ++erased; else ++itc; } - v.base_resize(v.nb_stored() - erased); - } - } - - template - inline void clean(const simple_vector_ref *> &l, double eps) { - simple_vector_ref *> - *svr = const_cast *> *>(&l); - rsvector - *pv = const_cast *>((l.origin)); - clean(*pv, eps); - svr->begin_ = vect_begin(*pv); svr->end_ = vect_end(*pv); - } - - template - inline size_type nnz(const rsvector& l) { return l.nb_stored(); } - - /*************************************************************************/ - /* */ - /* Class slvector: 'sky-line' vector. */ - /* */ - /*************************************************************************/ - - template struct slvector_iterator { - typedef T value_type; - typedef T *pointer; - typedef T &reference; - typedef ptrdiff_t difference_type; - typedef std::random_access_iterator_tag iterator_category; - typedef size_t size_type; - typedef slvector_iterator iterator; - typedef typename std::vector::iterator base_iterator; - - base_iterator it; - size_type shift; - - - iterator &operator ++() - { ++it; ++shift; return *this; } - iterator &operator --() - { --it; --shift; return *this; } - iterator operator ++(int) - { iterator tmp = *this; ++(*(this)); return tmp; } - iterator operator --(int) - { iterator tmp = *this; --(*(this)); return tmp; } - iterator &operator +=(difference_type i) - { it += i; shift += i; return *this; } - iterator &operator -=(difference_type i) - { it -= i; shift -= i; return *this; } - iterator operator +(difference_type i) const - { iterator tmp = *this; return (tmp += i); } - iterator operator -(difference_type i) const - { iterator tmp = *this; return (tmp -= i); } - difference_type operator -(const iterator &i) const - { return it - i.it; } - - reference operator *() const - { return *it; } - reference operator [](int ii) - { return *(it + ii); } - - bool operator ==(const iterator &i) const - { return it == i.it; } - bool operator !=(const iterator &i) const - { return !(i == *this); } - bool operator < (const iterator &i) const - { return it < i.it; } - size_type index(void) const { return shift; } - - slvector_iterator(void) {} - slvector_iterator(const base_iterator &iter, size_type s) - : it(iter), shift(s) {} - }; - - template struct slvector_const_iterator { - typedef T value_type; - typedef const T *pointer; - typedef value_type reference; - typedef ptrdiff_t difference_type; - typedef std::random_access_iterator_tag iterator_category; - typedef size_t size_type; - typedef slvector_const_iterator iterator; - typedef typename std::vector::const_iterator base_iterator; - - base_iterator it; - size_type shift; - - - iterator &operator ++() - { ++it; ++shift; return *this; } - iterator &operator --() - { --it; --shift; return *this; } - iterator operator ++(int) - { iterator tmp = *this; ++(*(this)); return tmp; } - iterator operator --(int) - { iterator tmp = *this; --(*(this)); return tmp; } - iterator &operator +=(difference_type i) - { it += i; shift += i; return *this; } - iterator &operator -=(difference_type i) - { it -= i; shift -= i; return *this; } - iterator operator +(difference_type i) const - { iterator tmp = *this; return (tmp += i); } - iterator operator -(difference_type i) const - { iterator tmp = *this; return (tmp -= i); } - difference_type operator -(const iterator &i) const - { return it - i.it; } - - value_type operator *() const - { return *it; } - value_type operator [](int ii) - { return *(it + ii); } - - bool operator ==(const iterator &i) const - { return it == i.it; } - bool operator !=(const iterator &i) const - { return !(i == *this); } - bool operator < (const iterator &i) const - { return it < i.it; } - size_type index(void) const { return shift; } - - slvector_const_iterator(void) {} - slvector_const_iterator(const slvector_iterator& iter) - : it(iter.it), shift(iter.shift) {} - slvector_const_iterator(const base_iterator &iter, size_type s) - : it(iter), shift(s) {} - }; - - - /** skyline vector. - */ - template class slvector { - - public : - typedef slvector_iterator iterators; - typedef slvector_const_iterator const_iterators; - typedef typename std::vector::size_type size_type; - typedef T value_type; - - protected : - std::vector data; - size_type shift; - size_type size_; - - - public : - - size_type size(void) const { return size_; } - size_type first(void) const { return shift; } - size_type last(void) const { return shift + data.size(); } - ref_elt_vector > operator [](size_type c) - { return ref_elt_vector >(this, c); } - - typename std::vector::iterator data_begin(void) { return data.begin(); } - typename std::vector::iterator data_end(void) { return data.end(); } - typename std::vector::const_iterator data_begin(void) const - { return data.begin(); } - typename std::vector::const_iterator data_end(void) const - { return data.end(); } - - void w(size_type c, const T &e); - T r(size_type c) const { - GMM_ASSERT2(c < size_, "out of range"); - if (c < shift || c >= shift + data.size()) return T(0); - return data[c - shift]; - } - - inline T operator [](size_type c) const { return r(c); } - void resize(size_type); - void clear(void) { data.resize(0); shift = 0; } - void swap(slvector &v) { - std::swap(data, v.data); - std::swap(shift, v.shift); - std::swap(size_, v.size_); - } - - - slvector(void) : data(0), shift(0), size_(0) {} - explicit slvector(size_type l) : data(0), shift(0), size_(l) {} - slvector(size_type l, size_type d, size_type s) - : data(d), shift(s), size_(l) {} - - }; - - template void slvector::resize(size_type n) { - if (n < last()) { - if (shift >= n) clear(); else { data.resize(n-shift); } - } - size_ = n; - } - - template void slvector::w(size_type c, const T &e) { - GMM_ASSERT2(c < size_, "out of range"); - size_type s = data.size(); - if (!s) { data.resize(1); shift = c; } - else if (c < shift) { - data.resize(s + shift - c); - typename std::vector::iterator it = data.begin(),it2=data.end()-1; - typename std::vector::iterator it3 = it2 - shift + c; - for (; it3 >= it; --it3, --it2) *it2 = *it3; - std::fill(it, it + shift - c, T(0)); - shift = c; - } - else if (c >= shift + s) { - data.resize(c - shift + 1); - std::fill(data.begin() + s, data.end(), T(0)); - } - data[c - shift] = e; - } - - template struct linalg_traits > { - typedef slvector this_type; - typedef this_type origin_type; - typedef linalg_false is_reference; - typedef abstract_vector linalg_type; - typedef T value_type; - typedef ref_elt_vector > reference; - typedef slvector_iterator iterator; - typedef slvector_const_iterator const_iterator; - typedef abstract_skyline storage_type; - typedef linalg_true index_sorted; - static size_type size(const this_type &v) { return v.size(); } - static iterator begin(this_type &v) - { return iterator(v.data_begin(), v.first()); } - static const_iterator begin(const this_type &v) - { return const_iterator(v.data_begin(), v.first()); } - static iterator end(this_type &v) - { return iterator(v.data_end(), v.last()); } - static const_iterator end(const this_type &v) - { return const_iterator(v.data_end(), v.last()); } - static origin_type* origin(this_type &v) { return &v; } - static const origin_type* origin(const this_type &v) { return &v; } - static void clear(origin_type* o, const iterator &, const iterator &) - { o->clear(); } - static void do_clear(this_type &v) { v.clear(); } - static value_type access(const origin_type *o, const const_iterator &, - const const_iterator &, size_type i) - { return (*o)[i]; } - static reference access(origin_type *o, const iterator &, const iterator &, - size_type i) - { return (*o)[i]; } - static void resize(this_type &v, size_type n) { v.resize(n); } - }; - - template std::ostream &operator << - (std::ostream &o, const slvector& v) { gmm::write(o,v); return o; } - - template - inline size_type nnz(const slvector& l) { return l.last() - l.first(); } - -} - -namespace std { - template void swap(gmm::wsvector &v, gmm::wsvector &w) - { v.swap(w);} - template void swap(gmm::rsvector &v, gmm::rsvector &w) - { v.swap(w);} - template void swap(gmm::slvector &v, gmm::slvector &w) - { v.swap(w);} -} - - - -#endif /* GMM_VECTOR_H__ */ diff --git a/include/gmm/gmm_vector_to_matrix.h b/include/gmm/gmm_vector_to_matrix.h deleted file mode 100644 index 81217fce067..00000000000 --- a/include/gmm/gmm_vector_to_matrix.h +++ /dev/null @@ -1,339 +0,0 @@ -// -*- c++ -*- (enables emacs c++ mode) -//=========================================================================== -// -// Copyright (C) 2003-2008 Yves Renard -// -// This file is a part of GETFEM++ -// -// Getfem++ is free software; you can redistribute it and/or modify it -// under the terms of the GNU Lesser General Public License as published -// by the Free Software Foundation; either version 2.1 of the License, or -// (at your option) any later version. -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -// License for more details. -// You should have received a copy of the GNU Lesser General Public License -// along with this program; if not, write to the Free Software Foundation, -// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. -// -// As a special exception, you may use this file as it is a part of a free -// software library without restriction. Specifically, if other files -// instantiate templates or use macros or inline functions from this file, -// or you compile this file and link it with other files to produce an -// executable, this file does not by itself cause the resulting executable -// to be covered by the GNU Lesser General Public License. This exception -// does not however invalidate any other reasons why the executable file -// might be covered by the GNU Lesser General Public License. -// -//=========================================================================== - -/**@file gmm_vector_to_matrix.h - @author Yves Renard - @date December 6, 2003. - @brief View vectors as row or column matrices. */ -#ifndef GMM_VECTOR_TO_MATRIX_H__ -#define GMM_VECTOR_TO_MATRIX_H__ - -#include "gmm_interface.h" - -namespace gmm { - - /* ********************************************************************* */ - /* row vector -> transform a vector in a (1, n) matrix. */ - /* ********************************************************************* */ - - template struct gen_row_vector { - typedef gen_row_vector this_type; - typedef typename std::iterator_traits::value_type V; - typedef V * CPT; - typedef typename std::iterator_traits::reference ref_V; - typedef typename linalg_traits::reference reference; - - simple_vector_ref vec; - - reference operator()(size_type, size_type j) const { return vec[j]; } - - size_type nrows(void) const { return 1; } - size_type ncols(void) const { return vect_size(vec); } - - gen_row_vector(ref_V v) : vec(v) {} - gen_row_vector() {} - gen_row_vector(const gen_row_vector &cr) : vec(cr.vec) {} - }; - - template - struct gen_row_vector_iterator { - typedef gen_row_vector this_type; - typedef typename modifiable_pointer::pointer MPT; - typedef typename std::iterator_traits::value_type V; - typedef simple_vector_ref value_type; - typedef const simple_vector_ref *pointer; - typedef const simple_vector_ref &reference; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - typedef std::random_access_iterator_tag iterator_category; - typedef gen_row_vector_iterator iterator; - - simple_vector_ref vec; - bool isend; - - iterator &operator ++() { isend = true; return *this; } - iterator &operator --() { isend = false; return *this; } - iterator operator ++(int) { iterator tmp = *this; ++(*this); return tmp; } - iterator operator --(int) { iterator tmp = *this; --(*this); return tmp; } - iterator &operator +=(difference_type i) - { if (i) isend = false; return *this; } - iterator &operator -=(difference_type i) - { if (i) isend = true; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const { - return (isend == true) ? ((i.isend == true) ? 0 : 1) - : ((i.isend == true) ? -1 : 0); - } - - const simple_vector_ref& operator *() const { return vec; } - const simple_vector_ref& operator [](int i) { return vec; } - - bool operator ==(const iterator &i) const { return (isend == i.isend); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (*this - i < 0); } - - gen_row_vector_iterator(void) {} - gen_row_vector_iterator(const gen_row_vector_iterator &itm) - : vec(itm.vec), isend(itm.isend) {} - gen_row_vector_iterator(const gen_row_vector &m, bool iis_end) - : vec(m.vec), isend(iis_end) { } - - }; - - template - struct linalg_traits > { - typedef gen_row_vector this_type; - typedef typename std::iterator_traits::value_type V; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef abstract_null_type sub_col_type; - typedef abstract_null_type col_iterator; - typedef abstract_null_type const_sub_col_type; - typedef abstract_null_type const_col_iterator; - typedef simple_vector_ref const_sub_row_type; - typedef typename select_ref, PT>::ref_type sub_row_type; - typedef gen_row_vector_iterator::pointer> - const_row_iterator; - typedef typename select_ref, PT>::ref_type row_iterator; - typedef typename linalg_traits::storage_type storage_type; - typedef row_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type nrows(const this_type &) { return 1; } - static size_type ncols(const this_type &m) { return m.ncols(); } - static const_sub_row_type row(const const_row_iterator &it) { return *it; } - static sub_row_type row(const row_iterator &it) { return *it; } - static const_row_iterator row_begin(const this_type &m) - { return const_row_iterator(m, false); } - static row_iterator row_begin(this_type &m) - { return row_iterator(m, false); } - static const_row_iterator row_end(const this_type &m) - { return const_row_iterator(m, true); } - static row_iterator row_end(this_type &m) - { return row_iterator(m, true); } - static origin_type* origin(this_type &m) { return m.vec.origin; } - static const origin_type* origin(const this_type &m) - { return m.vec.origin; } - static void do_clear(this_type &m) - { clear(row(mat_row_begin(m))); } - static value_type access(const const_row_iterator &itrow, size_type i) - { return itrow.vec[i]; } - static reference access(const row_iterator &itrow, size_type i) - { return itrow.vec[i]; } - }; - - template - std::ostream &operator <<(std::ostream &o, const gen_row_vector& m) - { gmm::write(o,m); return o; } - - /* ********************************************************************* */ - /* col vector -> transform a vector in a (n, 1) matrix. */ - /* ********************************************************************* */ - - template struct gen_col_vector { - typedef gen_col_vector this_type; - typedef typename std::iterator_traits::value_type V; - typedef V * CPT; - typedef typename std::iterator_traits::reference ref_V; - typedef typename linalg_traits::reference reference; - - simple_vector_ref vec; - - reference operator()(size_type i, size_type) const { return vec[i]; } - - size_type ncols(void) const { return 1; } - size_type nrows(void) const { return vect_size(vec); } - - gen_col_vector(ref_V v) : vec(v) {} - gen_col_vector() {} - gen_col_vector(const gen_col_vector &cr) : vec(cr.vec) {} - }; - - template - struct gen_col_vector_iterator { - typedef gen_col_vector this_type; - typedef typename modifiable_pointer::pointer MPT; - typedef typename std::iterator_traits::value_type V; - typedef simple_vector_ref value_type; - typedef const simple_vector_ref *pointer; - typedef const simple_vector_ref &reference; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - typedef std::random_access_iterator_tag iterator_category; - typedef gen_col_vector_iterator iterator; - - simple_vector_ref vec; - bool isend; - - iterator &operator ++() { isend = true; return *this; } - iterator &operator --() { isend = false; return *this; } - iterator operator ++(int) { iterator tmp = *this; ++(*this); return tmp; } - iterator operator --(int) { iterator tmp = *this; --(*this); return tmp; } - iterator &operator +=(difference_type i) - { if (i) isend = false; return *this; } - iterator &operator -=(difference_type i) - { if (i) isend = true; return *this; } - iterator operator +(difference_type i) const - { iterator itt = *this; return (itt += i); } - iterator operator -(difference_type i) const - { iterator itt = *this; return (itt -= i); } - difference_type operator -(const iterator &i) const { - return (isend == true) ? ((i.isend == true) ? 0 : 1) - : ((i.isend == true) ? -1 : 0); - } - - const simple_vector_ref& operator *() const { return vec; } - const simple_vector_ref& operator [](int i) { return vec; } - - bool operator ==(const iterator &i) const { return (isend == i.isend); } - bool operator !=(const iterator &i) const { return !(i == *this); } - bool operator < (const iterator &i) const { return (*this - i < 0); } - - gen_col_vector_iterator(void) {} - gen_col_vector_iterator(const gen_col_vector_iterator &itm) - : vec(itm.vec), isend(itm.isend) {} - gen_col_vector_iterator(const gen_col_vector &m, bool iis_end) - : vec(m.vec), isend(iis_end) { } - - }; - - template - struct linalg_traits > { - typedef gen_col_vector this_type; - typedef typename std::iterator_traits::value_type V; - typedef typename which_reference::is_reference is_reference; - typedef abstract_matrix linalg_type; - typedef typename linalg_traits::origin_type origin_type; - typedef typename select_ref::ref_type porigin_type; - typedef typename linalg_traits::value_type value_type; - typedef typename select_ref::reference, PT>::ref_type reference; - typedef abstract_null_type sub_row_type; - typedef abstract_null_type row_iterator; - typedef abstract_null_type const_sub_row_type; - typedef abstract_null_type const_row_iterator; - typedef simple_vector_ref const_sub_col_type; - typedef typename select_ref, PT>::ref_type sub_col_type; - typedef gen_col_vector_iterator::pointer> - const_col_iterator; - typedef typename select_ref, PT>::ref_type col_iterator; - typedef typename linalg_traits::storage_type storage_type; - typedef col_major sub_orientation; - typedef typename linalg_traits::index_sorted index_sorted; - static size_type ncols(const this_type &) { return 1; } - static size_type nrows(const this_type &m) { return m.nrows(); } - static const_sub_col_type col(const const_col_iterator &it) { return *it; } - static sub_col_type col(const col_iterator &it) { return *it; } - static const_col_iterator col_begin(const this_type &m) - { return const_col_iterator(m, false); } - static col_iterator col_begin(this_type &m) - { return col_iterator(m, false); } - static const_col_iterator col_end(const this_type &m) - { return const_col_iterator(m, true); } - static col_iterator col_end(this_type &m) - { return col_iterator(m, true); } - static origin_type* origin(this_type &m) { return m.vec.origin; } - static const origin_type* origin(const this_type &m) - { return m.vec.origin; } - static void do_clear(this_type &m) - { clear(col(mat_col_begin(m))); } - static value_type access(const const_col_iterator &itcol, size_type i) - { return itcol.vec[i]; } - static reference access(const col_iterator &itcol, size_type i) - { return itcol.vec[i]; } - }; - - template - std::ostream &operator <<(std::ostream &o, const gen_col_vector& m) - { gmm::write(o,m); return o; } - - /* ******************************************************************** */ - /* col and row vectors */ - /* ******************************************************************** */ - - - template inline - typename select_return< gen_row_vector, gen_row_vector, - const V *>::return_type - row_vector(const V& v) { - return typename select_return< gen_row_vector, - gen_row_vector, const V *>::return_type(linalg_cast(v)); - } - - template inline - typename select_return< gen_row_vector, gen_row_vector, - V *>::return_type - row_vector(V& v) { - return typename select_return< gen_row_vector, - gen_row_vector, V *>::return_type(linalg_cast(v)); - } - - template inline gen_row_vector - const_row_vector(V& v) - { return gen_row_vector(v); } - - - template inline - typename select_return< gen_col_vector, gen_col_vector, - const V *>::return_type - col_vector(const V& v) { - return typename select_return< gen_col_vector, - gen_col_vector, const V *>::return_type(linalg_cast(v)); - } - - template inline - typename select_return< gen_col_vector, gen_col_vector, - V *>::return_type - col_vector(V& v) { - return typename select_return< gen_col_vector, - gen_col_vector, V *>::return_type(linalg_cast(v)); - } - - template inline gen_col_vector - const_col_vector(V& v) - { return gen_col_vector(v); } - - -} - -#endif // GMM_VECTOR_TO_MATRIX_H__ diff --git a/include/gw_utils.h b/include/gw_utils.h index c9638d29871..75cf6bdf115 100644 --- a/include/gw_utils.h +++ b/include/gw_utils.h @@ -69,7 +69,7 @@ extern int gw_log_init(char * AProgname, char * ALogfilepath, int newfile); extern void gw_log_message(char * msg); -extern void gw_log_timestamp(char * label); +extern void gw_log_timestamp(const char * label); extern void gw_log_begin(void); extern void gw_log_end(void); //============================================================================= diff --git a/include/h_logz.h b/include/h_logz.h deleted file mode 100644 index b06c48716cb..00000000000 --- a/include/h_logz.h +++ /dev/null @@ -1,280 +0,0 @@ -/** - * @file h_logz.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.24 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)logmap.h 1.18 - 8/10/95 -*/ -/*------------------------------------------------------------------------ - File Name: logmap.h - - Author: Bruce Fischl - - Created: Jan. 1993 - - Description: - -------------------------------------------------------------------------*/ - - -#ifndef MAPINFO_H -#define MAPINFO_H - -#include "macros.h" -#include "image.h" - -typedef struct _neighbor_list -{ - struct _LOGPIX *logpix ; - struct _neighbor_list *next ; -} -NEIGHBOR ; - -/* - constants for eight neighbors and self. Note that these must match - the positions in a 3x3 matrix (row major order), where south and west - correspond to lower indices (down and to the left). -*/ -#define N_SW 0 -#define N_S 1 -#define N_SE 2 -#define N_W 3 -#define N_SELF 4 -#define N_E 5 -#define N_NW 6 -#define N_N 7 -#define N_NE 8 -#define NBD_SIZE 9 - -typedef struct _LOGPIX -{ - int area ; /* # of Cartesian pixels that map to this log pix */ - int row_cent ; /* centroid of logmap pixel in Cartesian space */ - int col_cent ; /* centroid of logmap pixel in Cartesian space */ - float xcent ; /* centroid of logmap pixel in Cartesian space */ - float ycent ; /* centroid of logmap pixel in Cartesian space */ - int spoke ; /* the spoke # of this pixel */ - int ring ; /* the ring # of this pixel */ - int n_neighbors ; /* # of neighbors of this logpix */ - NEIGHBOR *neighbors ; /* a link-list */ - void *user ; /* misc. pointer for whoever */ - double weight ; /* for gradient calculation */ - struct _LOGPIX *nbd[9] ; /* 8-connected neighbors and self */ - float rho ; /* radial log coordinate */ - float phi ; /* angular log coordinate */ - int ncpix ; /* # of cart. pix that map to this logpix */ -} -LOGPIX ; - -#define MAX_PIX 10 -typedef struct -{ - int npix ; /* # of log pix that this cart. pixel contributes to */ - /* array of log pixels that this pixel contributes to */ - LOGPIX *logpix[MAX_PIX] ; -} -CARTESIAN_PIXEL, CP ; - -typedef struct -{ - int rows ; - int cols ; - CP *pix ; /* array of LUTs for doing mapping */ -} -CARTESIAN_MAP_INFO, CMI ; - -typedef struct -{ - int nrings ; /* # of rings in logmap */ - int nspokes ; /* # of spokes in logmap */ - int ncols ; /* # of cols in Cartesian image */ - int nrows ; /* # of rows in Cartesian image */ - int nruns ; /* # of runs in runlength lookup tables */ - double alpha ; /* alpha used in complex log mapping */ - LOGPIX *logPix ; /* info about each logmap pixel (nrings x nspokes) */ - int *runNoToRing ; /* maps a run # to the ring it resides in. */ - int *runNoToSpoke; /* maps a run # to the ring it resides in. */ - char *runNoToLen ; /* contains a list of all run lengths. */ - UCHAR *tvToRing ; /* maps Cartesian (x, y) to a ring # */ - UCHAR *tvToSpoke ; /* maps Cartesian (x, y) to a spoke # */ - NEIGHBOR *neighbors ; /* total # of nbrs needed for connectivity graph */ - int max_neighbors ; /* size of neighbors allocation */ - int n_neighbors ; /* # of neighbors allocated so far */ - int ring_fovea ; - double maxr ; /* max radius in domain */ - float min_rho ; - float max_rho ; - float *rhos ; - int *start_spoke ; /* first spoke with real data in each ring */ - int *end_spoke ; /* last spoke with real data in each ring */ - CMI cmi ; /* for overlapping logmap construction */ -} -LOGMAP_INFO ; - -/* - These macros give access to the mapping from Cartesian coordinates to log - space coordinates. In the macros r = row (y), c = col (x) -*/ -#define TV_TO_SPOKE(m, c, r) (*((m)->tvToSpoke + ((r) * m->ncols) + c)) -#define TV_TO_RING(m, c, r) (*((m)->tvToRing + ((r) * m->ncols) + c)) - -/* - these macros deal with obtaining information about a log space pixel. - In the macros r = ring (x), s = spoke (y) -*/ -#define LOG_PIX(m, r, s) ((m)->logPix + ((s) * m->nrings) + r) -#define LOG_PIX_AREA(m, r, s) LOG_PIX(m, r, s)->area -#define LOG_PIX_ROW_CENT(m,r,s) LOG_PIX(m, r, s)->row_cent -#define LOG_PIX_COL_CENT(m,r,s) LOG_PIX(m, r, s)->col_cent -#define LOG_PIX_ROW_FCENT(m,r,s) LOG_PIX(m, r, s)->ycent -#define LOG_PIX_COL_FCENT(m,r,s) LOG_PIX(m, r, s)->xcent -#define LOG_PIX_SPOKE(m,r,s) LOG_PIX(m, r, s)->spoke -#define LOG_PIX_RING(m,r,s) LOG_PIX(m, r, s)->ring -#define LOG_PIX_WEIGHT(m,r,s) LOG_PIX(m, r, s)->weight -#define LOG_PIX_NEIGHBORS(m,r,s) LOG_PIX(m, r, s)->neighbors -#define LOG_PIX_N_NEIGHBORS(m,r,s) LOG_PIX(m, r, s)->n_neighbors -#define LOG_PIX_NBD(m,r,s,d) LOG_PIX(m,r,s)->nbd[d] -#define LOG_PIX_RHO(m,r,s) LOG_PIX(m, r, s)->rho -#define LOG_PIX_PHI(m,r,s) LOG_PIX(m, r, s)->phi - - -/* - These macros allow access to information about run lengths used in - doing a fast construction of the logmap image. -*/ -#define RUN_NO_TO_LEN(m, no) ((m)->runNoToLen[no]) -#define RUN_NO_TO_RING(m, no) ((m)->runNoToRing[no]) -#define RUN_NO_TO_SPOKE(m, no) ((m)->runNoToSpoke[no]) - -/* constants for LogMapInitForwardFilter */ -#define LMI_FORWARD_FILTER_CIRCLE 0 -#define LMI_FORWARD_FILTER_GAUSSIAN 1 - -void LogMapFree(LOGMAP_INFO **plmi) ; -LOGMAP_INFO *LogMapInit(double alpha,int cols,int rows,int nrings, - int nspokes); -int LogMapForward(LOGMAP_INFO *mi, IMAGE *inImage, IMAGE *outImage); -IMAGE *LogMapSample(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst) ; -IMAGE *LogMapInverseSample(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst) ; -IMAGE *LogMapNonlocal(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Ismooth, - IMAGE *Idst) ; -int LogMapInverse(LOGMAP_INFO *mi, IMAGE *inImage, IMAGE *outImage); -int LogMapGradient(LOGMAP_INFO *mi, IMAGE *inImage, - IMAGE *gradImage, int doweight, - int start_ring, int end_ring) ; -int LogMapSobel(LOGMAP_INFO *lmi, IMAGE *inImage, IMAGE *gradImage, - IMAGE *Ix, IMAGE *Iy, int doweight, int start_ring, - int end_ring) ; -IMAGE *LogMapFilter(LOGMAP_INFO *lmi, int which, int window_size, - IMAGE *Isrc, IMAGE *Idst) ; -IMAGE *LogMapMeanFilter(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst) ; -double LogMapDiffuse(LOGMAP_INFO *mi, IMAGE *inImage, IMAGE *outImage, - double k, int niter, int doweight, int which, - int time_type) ; -double LogMapDiffusePerona(LOGMAP_INFO *lmi, IMAGE *inImage, - IMAGE *outImage, double k, int niterations, - int doweight, int time_type) ; -double LogMapDiffuseCurvature(LOGMAP_INFO *lmi, IMAGE *inImage, - IMAGE *outImage, double A, int niterations, - int doweight, int time_type) ; - -int LogMapCurvature(LOGMAP_INFO *lmi, IMAGE *inImage, IMAGE *gradImage, - float A, int doweight, int start_ring, int end_ring) ; - -void LogMapPatchHoles(LOGMAP_INFO *lmi, IMAGE *Itv, IMAGE *Ilog) ; -IMAGE *LogMapNormalize(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst, - float low, float hi) ; -int LogMapInitForwardFilter(LOGMAP_INFO *lmi, int which) ; -IMAGE *LogMapForwardFilter(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst) ; -IMAGE *LogMapInverseFilter(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst); -IMAGE *LogMapInverseBilinear(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst); -IMAGE *LogMapInverseFilterGaussian(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst); - - -IMAGE *LogMapMedianFilter(LOGMAP_INFO *lmi, IMAGE *Isrc, int wsize, - IMAGE *Ioffset, IMAGE *Idst) ; - -/* offset filtering in the log plane */ -IMAGE *LogMapOffsetOrientation(LOGMAP_INFO *lmi, int wsize, IMAGE *Isrc, - IMAGE *Iorient) ; -IMAGE *LogMapOffsetDirection(LOGMAP_INFO *lmi, IMAGE *Iorient, IMAGE *Ioffset); -IMAGE *LogMapOffsetMagnitude(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Idst, - int maxsteps) ; -IMAGE *LogMapApplyOffset(LOGMAP_INFO *lmi, IMAGE *Isrc, IMAGE *Ioffset, - IMAGE *Idst) ; -IMAGE *LogMapGaussianFilter(LOGMAP_INFO *lmi, IMAGE *Isrc, - IMAGE *Igaussian, IMAGE *Idst) ; -IMAGE *LogMapOffset(LOGMAP_INFO *lmi, IMAGE *Isrc, int wsize, IMAGE *Ioffset) ; -IMAGE *LogMapAddSaltNoise(LOGMAP_INFO *lmi, IMAGE *Isrc,IMAGE *Idst, - float density); - -#if 0 -#define for_each_neighbor(lmi, ptr, i, j, r, s) \ - for (ptr = LOG_PIX_NEIGHBORS(lmi, i, j) ; ptr ; ptr = ptr->next) \ - if (((s = ptr->logpix->spoke)|1) && ((r = ptr->logpix->ring)|1)) -#else -#define for_each_neighbor(lmi, ptr, i, j) \ - for (ptr = LOG_PIX_NEIGHBORS(lmi, i, j) ; ptr ; ptr = ptr->next) -#endif - -#define for_each_log_pixel(lmi, r, s) \ - for (r = 0; r < lmi->nrings; r++) \ - for (s = 0; s < lmi->nspokes; s++) \ - if (LOG_PIX_AREA(lmi,r,s) > 0) - -/* this macro will go through a specified set of rings */ -#define for_each_ring(lmi, r, s, start_ring, end_ring) \ - for (r = start_ring; r <= end_ring ; r++) \ - for (s = lmi->start_spoke[r]; s <= lmi->end_spoke[r]; s++) - -/* this macro will go through all log pixels, even those with no area */ -#define for_all_log_pixels(lmi, r, s) \ - for (s = 0; s < lmi->nspokes; s++) \ - for (r = 0; r < lmi->nrings; r++) - -#define for_each_tv_pixel(lmi, i, j) \ - for (j = 0; j < lmi->nrows ; j++) \ - for (i = 0; i < lmi->ncols ; i++) - - -#define UNDEFINED 255 -#define DEFINED(r, s) ((r != UNDEFINED) && (s != UNDEFINED)) - -#define DIFFUSION_TIME_LOG 0 /* just straight diffusion */ -#define DIFFUSION_TIME_PERIPHERAL 1 /* base time on peripheral it. */ -#define DIFFUSION_TIME_FOVEAL 2 /* || foveal || */ -#define DIFFUSION_TIME_CARTESIAN 3 /* run for equivalent cart. it. */ - - -int log_median(LOGMAP_INFO *lmi, IMAGE *hdi, IMAGE *hdo, int size) ; - -#define LOGMAP_RLE 0 -#define LOGMAP_SAMPLE 1 -#define LOGMAP_NONLOCAL 2 -#define LOGMAP_FILTER 3 - - -#endif diff --git a/include/handle.h b/include/handle.h deleted file mode 100644 index 48d32819853..00000000000 --- a/include/handle.h +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @file handle.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef HANDLE_H -#define HANDLE_H - -typedef unsigned long PTR_HANDLE ; - -PTR_HANDLE HandleAlloc(void *ptr) ; -void HandleFree(PTR_HANDLE handle) ; -void *HandleToPtr(PTR_HANDLE handle) ; -int HandleOk(PTR_HANDLE handle) ; - - -#endif diff --git a/include/heap.h b/include/heap.h deleted file mode 100644 index 3bc3b75fdac..00000000000 --- a/include/heap.h +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @file heap.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/*---------------------------------------------------------------------------- -// -// File: heap.h -// Data Structure: list and heap -// -//--------------------------------------------------------------------------*/ - -/*============================================================================ -// Summary -//============================================================================ -// -// DATA STRUCTURE: -// PGlist ---> {elementSize, size, data, capacity, capacityIncrement} -// -// NOTE: the type of PGlist is a pointer. -// -// Assume the following variable declarations: -// PGlist list, list1, list2; -// ListElement element; -// ListElement *data; -// int capacity, capacityIncrement, size, -// elementSize, index, returnFlag; -// -// LIST MANIPULATIONS: -// -// pgList ........................ default constructor -// list = pgList(sizeof(ListElement)); -// -// pgList1 ....................... default constructor with capacity -// list1 = pgList(sizeof(ListElement), capacity); -// -// pgList2 ....................... default constructor with capacity -// and capacity increment -// list2 = pgList(sizeof(ListElement), capacity, capacityIncrement); -// -// pgListOfSize .................. default constructor with a specified size -// list = pgListOfSize(size, sizeof(ListElement)); -// -// pgListDelete .................. delete the list -// pgListDelete(list); -// -// pgListAddElement .............. add an element to this list -// pgListAddElement(list, &element); -// -// pgListInsertElementAt ......... insert an element in the list at the given -// index. Each list element's index greater -// or equal to the specified index is -// shifted upward than its previous value. -// returnFlag = pgListInsertElementAt(list, index, &element); -// -// pgListElementAt ............... retrieve an element at index -// returnFlag = pgListElementAt(list, index, &element); -// -// pgListSetElementAt ............ set the element at the specified index of -// this list by copying the value of -// given element. -// returnFlag = pgListSetElementAt(list, index, &element); -// -// pgListRemoveElementAt ......... Delete the element at the specified index. -// The index of each element after the -// specified index is decreased by 1. -// returnFlag = pgListRemoveElementAt(list, index); -// -// pgListRemoveAllElements ....... removes all elements from this list -// and sets its size to zero -// pgListRemoveAllElements(list); -// -// pgListTrim .................... trim this list to its current size -// pgListTrim(list); -// -// pgListIsEmpty ................. PG_TRUE if this list has no elements -// returnFlag = pgListIsEmpty(list); -// -// pgListElementSize ............. the element size of each component -// elementSize = pgListElementSize(list); -// -// pgListSize .................... the current size of this list -// size = pgListSize(list); -// -// pgListData .................... the data of this list -// data = pgListData(list); -// -//==========================================================================*/ - -#ifndef HEAP_TOOLS -#define HEAP_TOOLS -#include - -typedef struct -{ - int elementSize; - int size; - void *data; - int capacity; - int capacityIncrement; -} -PGlistStruct; - -typedef PGlistStruct *PGlist; - -#define pgListIsEmpty(list) (list->size == 0 ? 1 : 0) -#define pgListSize(list) (list->size) -#define pgListData(list) (list->data) -#define pgListElementSize(list) (list->elementSize) - -PGlist pgList(int elementSize); -PGlist pgList1(int elementSize, int capacity); -PGlist pgList2(int elementSize, int capacity, int capacityIncrement); -PGlist pgListOfSize(int size, int elementSize); -void pgListDelete(PGlist list); -void pgListAddElement(PGlist list, void *element); -int pgListInsertElementAt(PGlist list, int index, void *element); -int pgListSetElementAt(PGlist list, int index, void *element); -int pgListElementAt(PGlist list, int index, - /* stores the result at */ void *element); -int pgListRemoveElementAt(PGlist list, int index); -void pgListRemoveAllElements(PGlist list); -void pgListTrim(PGlist list); - -/*============================================================================ -// PGutil private functions -// USER PLEASE DO NOT USE -// NOTE: these numbers should not be changed once the list is created -//============================================================================ -// pgListCapacity ................ the current capacity of this list -// pgListCapacityIncrement ....... the current capacityIncrement of this list -// pgListSetElementSize .......... set the element size of this list -// pgListSetSize ................. set the size of this list -// pgListSetData ................. set the data of this list -// pgListSetCapacity ............. set the capacity of this list -// pgListSetCapacityIncrement .... set the capacityIncrement of this list -// pgListInfo .................... print the information about the list -//==========================================================================*/ - -/*-------------------------------------------------------------------------- -// Private functions -//------------------------------------------------------------------------*/ -#define pgListCapacity(list) (list->capacity) -#define pgListCapacityIncrement(list) (list->capacityIncrement) -#define pgListSetElementSize(list, val) list->elementSize = val -#define pgListSetSize(list, val) list->size = val -#define pgListSetData(list, val) list->data = (void *)val -#define pgListSetCapacity(list, val) list->capacity = val -#define pgListSetCapacityIncrement(list, val) list->capacityIncrement = val - -/* The following is the definition of HEAP data structure, - which is built upon pgList above. It implements a Min_heap that stores - floating point value with an associated attribute of id */ -typedef struct -{ - double value; - int id; - int* p; /* backpointer */ -} -XheapElement; - -typedef PGlist Xheap; - -int xhSize(Xheap H); /* get size of heap */ -Xheap xhInitEmpty(); /* an empty heap */ -Xheap xhInit(XheapElement *array, int N); /* init from an array (0,N-1) */ -void xhDestroy(Xheap H); /* destroy the heap and free the memory */ -int xhUpHeap(int k, Xheap H); -int xhDownHeap(int k, Xheap H); -int xhInsert(double value, int id, int *p, Xheap H); -XheapElement xhRemove(Xheap H); -XheapElement xhReplace(double value, int id, int *p, Xheap H); -XheapElement xhDelete(int k, Xheap H); -XheapElement xhChange(int k, double value, int id, int *p, Xheap H); -XheapElement xhChangeValue(int k, double value, Xheap H); -XheapElement xhGet(int k, Xheap H); /* k must be 1, 2, ... N */ -#define xhIsEmpty(H) (xhSize(H) == 0) - -#endif diff --git a/include/hip_brf.h b/include/hip_brf.h deleted file mode 100644 index 8097fcdfdec..00000000000 --- a/include/hip_brf.h +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file hip_brf.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - * FILE NAME: hips.h - * - * DESCRIPTION: hips2 prototypes - * - * AUTHOR: Bruce Fischl - * DATE: 2/5/96 - * -*/ - -#ifndef HIPS_H -#define HIPS_H - -/*----------------------------------------------------- - TYPEDEFS & STRUCTURES --------------------------------------------------------*/ -#define MaxDisks 8 -typedef struct -{ - /* - indices (i,j) refer to which logmap point the current image point - belongs (MAX number of logmap points is MaxDisks) - */ - int xi_i[MaxDisks]; - int eta_j[MaxDisks]; - float weight[MaxDisks]; /* differs with the type of nonuniform filetring */ -} -LMtable; - - - - -/*----------------------------------------------------- - INCLUDE FILES --------------------------------------------------------*/ -#include -#include "hipsh.h" -#include "hipsu.h" - -#if 0 -int h_mulscale(struct header *hdi, struct header *hdo, Pixelval *b) ; -int h_divscale(struct header *hdi, struct header *hdo, Pixelval *b) ; -int h_add(struct header *hdi1, struct header *hdi2, struct header *hdo) ; -int h_linscale(struct header *hdi, struct header * hdo, float b, float c) ; -int h_div(struct header *hdi1, struct header * hdi2, struct header *hdo) ; -int h_tof(struct header *hdi, struct header *hdo) ; -int h_toc(struct header *hdi, struct header *hdo) ; -int h_reduce(struct header *hdi, struct header *hdo, int xf, int yf) ; -int h_flipquad(struct header *hdi, struct header *hdo) ; -int h_rot180(struct header *hdi, struct header *hdo) ; -int h_minmax(struct header *hd, Pixelval *minval, Pixelval *maxval,int nzflag); -int h_discedge(struct header *hdi, struct header *hdo,int size, float varcrit); -int h_canny(struct header *Isrc, struct header *Idst, double sigma, - int mask_size,double lfrac,double hfrac,int dothin); -int h_morphdil(struct header *hdi, struct header *hde, struct header *hdo, - int centerr, int centerc,int gray) ; -int h_logmap(struct header *phd,struct header *phd_LM,float a, - int R,int rows,int cols,int Fx,int Fy,float disk_size) ; -int h_logmap_f(struct header *phd,struct header *phd_LM,float a, - int R,int rows,int cols,int Fx,int Fy,float disk_size) ; -int h_LMtable_uniform(LMtable *ptable,struct header *phd_w,int Irows,int Icols, - float a,int R,int Fx,int Fy,float disk_size) ; -#endif - -#endif diff --git a/include/hipl_for.h b/include/hipl_for.h deleted file mode 100644 index 3c76cf327f2..00000000000 --- a/include/hipl_for.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file hipl_for.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - * Copyright (c) 1991 Michael Landy - * - * Disclaimer: No guarantees of performance accompany this software, - * nor is any responsibility assumed on the part of the authors. All the - * software has been tested extensively and every effort has been made to - * insure its reliability. - */ - -/* - * hipl_format.h - standard definitions for HIPS images - * - * Michael Landy - 12/28/90 - */ - -#ifndef HIPL_FORMAT_H -#define HIPL_FORMAT_H - -#ifndef FILE -#include -#endif -#include -#include -#include -#include - -/* include local additions */ -#ifdef GRLE -#include -#endif - -#endif diff --git a/include/hipl_format.h b/include/hipl_format.h deleted file mode 100644 index e441066299c..00000000000 --- a/include/hipl_format.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file hipl_format.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - * Copyright (c) 1991 Michael Landy - * - * Disclaimer: No guarantees of performance accompany this software, - * nor is any responsibility assumed on the part of the authors. All the - * software has been tested extensively and every effort has been made to - * insure its reliability. - */ - -/* - * hipl_format.h - standard definitions for HIPS images - * - * Michael Landy - 12/28/90 - */ - -#ifndef HIPL_FORMAT_H -#define HIPL_FORMAT_H - -#ifndef FILE -#include -#endif -#include -#include -#include -#include - -/* include local additions */ -#ifdef GRLE -#include -#endif - -#endif diff --git a/include/hips.h b/include/hips.h index e19822bdd42..0d459aeb7c6 100644 --- a/include/hips.h +++ b/include/hips.h @@ -1,91 +1,263 @@ -/** - * @file hips.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.9 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - * FILE NAME: hips.h - * - * DESCRIPTION: hips2 prototypes - * - * AUTHOR: Bruce Fischl - * DATE: 2/5/96 - * -*/ - #ifndef HIPS_H #define HIPS_H -/*----------------------------------------------------- - TYPEDEFS & STRUCTURES --------------------------------------------------------*/ -#define MaxDisks 8 -typedef struct -{ - /* - indices (i,j) refer to which logmap point the current image point - belongs (MAX number of logmap points is MaxDisks) - */ - int xi_i[MaxDisks]; - int eta_j[MaxDisks]; - float weight[MaxDisks]; /* differs with the type of nonuniform filetring */ -} -LMtable; - - - - -/*----------------------------------------------------- - INCLUDE FILES --------------------------------------------------------*/ -#include -#include "hipsh.h" -#include "hipsu.h" - -#if 0 -int h_mulscale(struct header *hdi, struct header *hdo, Pixelval *b) ; -int h_divscale(struct header *hdi, struct header *hdo, Pixelval *b) ; -int h_add(struct header *hdi1, struct header *hdi2, struct header *hdo) ; -int h_linscale(struct header *hdi, struct header * hdo, float b, float c) ; -int h_div(struct header *hdi1, struct header * hdi2, struct header *hdo) ; -int h_tof(struct header *hdi, struct header *hdo) ; -int h_toc(struct header *hdi, struct header *hdo) ; -int h_reduce(struct header *hdi, struct header *hdo, int xf, int yf) ; -int h_flipquad(struct header *hdi, struct header *hdo) ; -int h_rot180(struct header *hdi, struct header *hdo) ; -int h_minmax(struct header *hd, Pixelval *minval, Pixelval *maxval,int nzflag); -int h_discedge(struct header *hdi, struct header *hdo,int size, float varcrit); -int h_canny(struct header *Isrc, struct header *Idst, double sigma, - int mask_size,double lfrac,double hfrac,int dothin); -int h_morphdil(struct header *hdi, struct header *hde, struct header *hdo, - int centerr, int centerc,int gray) ; -int h_logmap(struct header *phd,struct header *phd_LM,float a, - int R,int rows,int cols,int Fx,int Fy,float disk_size) ; -int h_logmap_f(struct header *phd,struct header *phd_LM,float a, - int R,int rows,int cols,int Fx,int Fy,float disk_size) ; -int h_LMtable_uniform(LMtable *ptable,struct header *phd_w,int Irows,int Icols, - float a,int R,int Fx,int Fy,float disk_size) ; +// ------ typedefs ------ + +typedef unsigned char byte; +typedef char sbyte; +typedef unsigned short h_ushort; +typedef unsigned int h_uint; +typedef float h_complex[2]; +typedef double h_dblcom[2]; +typedef unsigned long fs_hsize_t; +typedef const char * Filename; +typedef int h_boolean; + +// ------ macros ------ + +#define MSBF_PACKING 1 /* use most significant bit first packing */ +#define LSBF_PACKING 2 /* use least significant bit first packing */ + +#define CPLX_MAG 1 /* complex magnitude */ +#define CPLX_PHASE 2 /* complex phase */ +#define CPLX_REAL 3 /* complex - real part only */ +#define CPLX_IMAG 4 /* complex - imaginary part only */ + +#define CPLX_RVI0 1 /* real part = value, imaginary = 0 */ +#define CPLX_R0IV 2 /* real part = 0, imaginary = value */ + +#define PFBYTE 0 /* Bytes interpreted as unsigned integers */ +#define PFSHORT 1 /* Short integers (2 bytes) */ +#define PFINT 2 /* Integers (4 bytes) */ +#define PFFLOAT 3 /* Float's (4 bytes)*/ +#define PFCOMPLEX 4 /* 2 Float's interpreted as (real,imaginary) */ +#define PFASCII 5 /* ASCII rep, with linefeeds after each row */ +#define PFDOUBLE 6 /* Double's (8 byte floats) */ +#define PFDBLCOM 7 /* Double complex's (2 Double's) */ +#define PFQUAD 10 /* quad-tree encoding (Mimaging) */ +#define PFQUAD1 11 /* quad-tree encoding */ +#define PFHIST 12 /* histogram of an image (using ints) */ +#define PFSPAN 13 /* spanning tree format */ +#define PLOT3D 24 /* plot-3d format */ +#define PFMSBF 30 /* packed, most-significant-bit first */ +#define PFLSBF 31 /* packed, least-significant-bit first */ +#define PFSBYTE 32 /* signed bytes */ +#define PFUSHORT 33 /* unsigned shorts */ +#define PFUINT 34 /* unsigned ints */ +#define PFRGB 35 /* RGB RGB RGB bytes */ +#define PFRGBZ 36 /* RGB0 RGB0 RGB0 bytes */ +#define PFZRGB 37 /* 0RGB 0RGB 0RGB bytes */ +#define PFMIXED 40 /* multiple frames in different pixel formats */ +#define PFBGR 41 /* BGR BGR BGR bytes */ +#define PFBGRZ 42 /* BGR0 BGR0 BGR0 bytes */ +#define PFZBGR 43 /* 0BGR 0BGR 0BGR bytes */ +#define PFINTPYR 50 /* integer pyramid */ +#define PFFLOATPYR 51 /* float pyramid */ +#define PFPOLYLINE 100 /* 2D points */ +#define PFCOLVEC 101 /* Set of RGB triplets defining colours */ +#define PFUKOOA 102 /* Data in standard UKOOA format */ +#define PFTRAINING 104 /* Set of colour vector training examples */ +#define PFTOSPACE 105 /* TOspace world model data structure */ +#define PFSTEREO 106 /* Stereo sequence (l, r, l, r, ...) */ +#define PFRGPLINE 107 /* 2D points with regions */ +#define PFRGISPLINE 108 /* 2D points with regions and interfaces */ +#define PFCHAIN 200 /* Chain code encoding (Mimaging) */ +#define PFLUT 300 /* LUT format (uses Ints) (Mimaging) */ +#define PFAHC 400 /* adaptive hierarchical encoding */ +#define PFOCT 401 /* oct-tree encoding */ +#define PFBT 402 /* binary tree encoding */ +#define PFAHC3 403 /* 3-d adaptive hierarchical encoding */ +#define PFBQ 404 /* binquad encoding */ +#define PFRLED 500 /* run-length encoding */ +#define PFRLEB 501 /* run-length encoding, line begins black */ +#define PFRLEW 502 /* run-length encoding, line begins white */ +#define PFPOLAR 600 /* rho-theta format (Mimaging) */ +#define PFGRLE 601 /* gray scale run-length encoding */ +#define PFSRLE 602 /* monochrome run-scale encoding */ +#define PFVFFT3D 701 /* float complex 3D virtual-very fast FT */ +#define PFVFFT2D 702 /* float complex 2D virtual-very fast FT */ +#define PFDVFFT3D 703 /* double complex 3D VFFT */ +#define PFDVFFT2D 704 /* double complex 2D VFFT */ +#define PFVVFFT3D 705 /* float 3D VFFT in separated planes */ +#define PFDVVFFT3D 706 /* double 3D VVFFT in separated planes */ + +#define HIPS_ERROR -1 /* error-return from hips routines */ +#define HIPS_OK 0 /* one possible nonerror-return value */ + +#define FBUFLIMIT 30000 /* increase this if you use large PLOT3D files */ +#define LINELENGTH 200 /* max characters per line in header vars */ +#define NULLPAR ((struct extpar *) 0) + +// ------ math macros ------ + +#ifndef MAX +# define MAX(A,B) ((A) > (B) ? (A) : (B)) +#endif +#ifndef MIN +# define MIN(A,B) ((A) < (B) ? (A) : (B)) +#endif +#ifndef ABS +# define ABS(A) ((A) > 0 ? (A) : (-(A))) +#endif +#ifndef BETWEEN +# define BETWEEN(A,B,C) (((A) < (B)) ? (B) : (((A) > (C)) ? (C) : (A))) +#endif +#ifndef SIGN +# define SIGN(A,B) (((B) > 0) ? (A) : (-(A))) #endif +#ifndef TOascii +# define TOascii(c) ((c) & 0x7f) +#endif + +// ------ structs ------ + +union pixelval { + byte v_byte; + sbyte v_sbyte; + short v_short; + h_ushort v_ushort; + int v_int; + h_uint v_uint; + float v_float; + double v_double; + h_complex v_complex; + h_dblcom v_dblcom; +}; + +typedef union pixelval Pixelval; + +struct header { + char *orig_name; /* The originator of this sequence */ + h_boolean ondealloc; /* If nonzero, free orig_name when requested */ + char *seq_name; /* The name of this sequence */ + h_boolean sndealloc; /* If nonzero, free seq_name when requested */ + int num_frame; /* The number of frames in this sequence */ + char *orig_date; /* The date the sequence was originated */ + h_boolean oddealloc; /* If nonzero, free orig_date when requested */ + int orows; /* The number of rows in each stored image */ + int ocols; /* The number of columns in each stored image */ + int rows; /* The number of rows in each image (ROI) */ + int cols; /* The number of columns in each image (ROI) */ + int frow; /* The first ROI row */ + int fcol; /* The first ROI col */ + int pixel_format; /* The format of each pixel */ + int numcolor; /* The number of color frames per image */ + int numpix; /* The number of pixels per stored frame */ + fs_hsize_t sizepix; /* The number of bytes per pixel */ + fs_hsize_t sizeimage; /* The number of bytes per stored frame */ + byte *image; /* The image itself */ + h_boolean imdealloc; /* if nonzero, free image when requested */ + byte *firstpix; /* Pointer to first pixel (for ROI) */ + int sizehist; /* Number of bytes in history (excluding null, including ) */ + char *seq_history; /* The sequence's history of transformations */ + h_boolean histdealloc; /* If nonzero, free history when requested */ + int sizedesc; /* Number of bytes in description (excluding null, including ) */ + char *seq_desc; /* Descriptive information */ + h_boolean seqddealloc; /* If nonzero, free desc when requested */ + int numparam; /* Count of additional parameters */ + h_boolean paramdealloc; /* If nonzero, free param structures and/or param values when requested */ + struct extpar *params; /* Additional parameters */ + float xsize ; + float ysize ; +}; + +struct hips_roi { + int rows; /* The number of rows in the ROI */ + int cols; /* The number of columns in the ROI */ + int frow; /* The first ROI row */ + int fcol; /* The first ROI col */ +}; + +struct extpar { + char *name; /* name of this variable */ + int format; /* format of values (PFBYTE, PFINT, etc.) */ + int count; /* number of values */ + union { + byte v_b; /* PFBYTE/PFASCII, count = 1 */ + int v_i; /* PFINT, count = 1 */ + short v_s; /* PFSHORT, count = 1 */ + float v_f; /* PFFLOAT, count = 1 */ + byte *v_pb; /* PFBYT/PFASCIIE, count > 1 */ + int *v_pi; /* PFINT, count > 1 */ + short *v_ps; /* PFSHORT, count > 1 */ + float *v_pf; /* PFFLOAT, count > 1 */ + } val; + h_boolean dealloc; /* if nonzero, free memory for val */ + struct extpar *nextp; /* next parameter in list */ +}; + +struct hips_histo { + int nbins; + int *histo; + fs_hsize_t sizehist; + h_boolean histodealloc; + int pixel_format; + Pixelval minbin; + Pixelval binwidth; +}; + +// ------ functions ------ + +double h_entropy(int *table,int count,int pairflag); +int alloc_histo(struct hips_histo *histo,union pixelval *min,union pixelval *max,int nbins,int format); +int alloc_histobins(struct hips_histo *histo); +int clearparam(struct header *hd, const char *name); +int fread_header(FILE *fp,struct header *hd,const char *fname); +int fread_image(FILE *fp,struct header *hd,int fr,const char *fname); +int free_hdrcon(struct header *hd); +// int free_header(struct header *hd); +int fwrite_header(FILE *fp,struct header *hd,const char *fname); +int fwrite_image(FILE *fp,struct header *hd,int fr,const char *fname); +int getparam(struct header *hda,...); +int h_add(struct header *hdi1,struct header *hdi2,struct header *hdo); +int h_clearhisto(struct hips_histo *histogram); +// int h_copy(struct header *hdi,struct header *hdo); +int h_diff(struct header *hdi1,struct header *hdi2,struct header *hdo); +int h_div(struct header *hdi1,struct header *hdi2,struct header *hdo); +int h_divscale(struct header *hdi,struct header *hdo,union pixelval *b); +int h_enlarge(struct header *hdi,struct header *hdo,int xf,int yf); +int h_entropycnt(struct header *hd,int *table,int pairflag); +int h_flipquad(struct header *hdi,struct header *hdo); +int h_fourtr(struct header *hd); +int h_histo(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); +int h_histoeq(struct hips_histo *histogram,int count,unsigned char *map); +int h_invert(struct header *hdi,struct header *hdo); +int h_invfourtr(struct header *hd); +int h_linscale(struct header *hdi,struct header *hdo,float b,float c); +int h_median(struct header *hdi,struct header *hdo,int size); +int h_minmax(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); +int h_morphdil(struct header *hdi,struct header *hde,struct header *hdo,int centerr,int centerc,int gray); +int h_mul(struct header *hdi1,struct header *hdi2,struct header *hdo); +int h_mulscale(struct header *hdi,struct header *hdo,union pixelval *b); +int h_pixmap(struct header *hdi,struct header *hdo,unsigned char *map); +int h_reduce(struct header *hdi,struct header *hdo,int xf,int yf); +int h_softthresh(struct header *hdi,struct header *hdo,union pixelval *thresh); +int h_tob(struct header *hdi,struct header *hdo); +int h_toc(struct header *hdi,struct header *hdo); +int h_tod(struct header *hdi,struct header *hdo); +int h_todc(struct header *hdi,struct header *hdo); +int h_tof(struct header *hdi,struct header *hdo); +int h_toi(struct header *hdi,struct header *hdo); +int setparam(struct header *hda,...); +int update_header(struct header *hd,int argc,char **argv ); +struct extpar *findparam(struct header *hd, const char *name); + +// ------ externs ------ + +extern int hips_rtocplx; +extern int hips_cplxtor; + +// ------ canny ----- + +void canny(int *magmax, int *hthresh, int *lthresh, int *image, int *xsize, int *ysize, short *shortim, int *windowsize, double *sigma, int *bordermode, double *hfrac, double *lfrac, int *pflag, + short *gx, short *gy, short *mag, int *hist, int *histsize, unsigned char *nms, unsigned char *edgemap, float *gm, float *gmp,short *temp) ; +void cleanup(unsigned char *map, int xsize, int ysize) ; +void find_edges(unsigned char *map, short *mag, int xsize, int ysize, int maxmag, float hpixel_fraction, float lpixel_fraction, int *hgram, int hsize, int *actual_hthresh, int *actual_lthresh); +void follow_edges(unsigned char *edgemapptr, short *edgemagptr) ; +void clear_borders(unsigned char *charimage, int xsize, int ysize) ; +void gauss_filter(short *inimage, int inx, int iny, int direction, int boundary, int masksize, float sigma, short *grad, int *outx, int *outy, float *gmask, float *gprimemask, short *tempimage) ; +void copyimage(int *charimage, int ncols, int nrows, short *shortimage) ; +void thin(unsigned char *edges, int height, int width) ; +int h_canny(struct header *Isrc, struct header *Idst, double sigma, int mask_size,double lfrac,double hfrac,int dothin); #endif diff --git a/include/hips_basic.h b/include/hips_basic.h deleted file mode 100644 index 49aaa45984f..00000000000 --- a/include/hips_basic.h +++ /dev/null @@ -1,424 +0,0 @@ -/** - * @file hips_basic.h - * @brief basic definitions for HIPS - * - */ -/* - * Original Author: Michael Landy - 12/28/90 - * CVS Revision Info: - * $Author: zkaufman $ - * $Date: 2016/02/24 16:23:27 $ - * $Revision: 1.6 $ - * - * Copyright (c) 1991 Michael Landy - * - * Disclaimer: No guarantees of performance accompany this software, - * nor is any responsibility assumed on the part of the authors. All the - * software has been tested extensively and every effort has been made to - * insure its reliability. - * - */ - - -#ifndef HIPS_BASIC_H -#define HIPS_BASIC_H - -/* - * Machine-dependent portion - * - * The next lines are the only portion of the file which should be tailored - * to an individual installation. - */ - -typedef unsigned long fs_hsize_t; /* variable which can hold the size of an - image in bytes */ -#ifdef AIX -#define HPUXORAIX -#endif - -#ifdef HPUX -#define HPUXORAIX -#endif - -#ifdef HPUXORAIX - -#define H__RANDOM lrand48 /* routine to call for random numbers */ -#define H__RANDTYPE long /* type of H__RANDOM() */ -#define H__SRANDOM srand48 /* routine to call to set the seed */ -#define H__MAXRAND (0x7fffffff) /* maximum random number */ -#define H__RANDBITS (31) /* number of random bits returned */ - -#else - -#define H__RANDOM random /* routine to call for random numbers */ -#define H__RANDTYPE long /* type of H__RANDOM() */ -#define H__SRANDOM srandom /* routine to call to set the seed */ -#define H__MAXRAND (0x7fffffff) /* maximum random number */ -#define H__RANDBITS (31) /* number of random bits returned */ - -#endif - -/* *******************END OF MACHINE-DEPENDENT PORTION*********************/ - -typedef unsigned char byte; -typedef char sbyte; -typedef unsigned short h_ushort; -typedef unsigned int h_uint; -typedef float h_complex[2]; -typedef double h_dblcom[2]; -typedef const char * Filename; - -union pixelval { - byte v_byte; - sbyte v_sbyte; - short v_short; - h_ushort v_ushort; - int v_int; - h_uint v_uint; - float v_float; - double v_double; - h_complex v_complex; - h_dblcom v_dblcom; -}; - -typedef union pixelval Pixelval; - -/* - * For general readability - */ - -#ifndef TRUE -# define TRUE 1 -# define FALSE 0 -#endif - -typedef int h_boolean; - -/* - * Histogram structure - * - * The zero-th bin is underflows. The last bin is overflows. So there are - * nbins+2 slots. The n'th bin counts pixels such that: - * - * min + ((n-1)*binwidth) <= value < min + n*binwidth - * - * For complex and double complex images, the complex magnitude is - * histogrammed, and min/binwidth are either floats (for complex images) or - * doubles (for double complex images). - */ - -struct hips_histo -{ - int nbins; - int *histo; - fs_hsize_t sizehist; - h_boolean histodealloc; - int pixel_format; - Pixelval minbin; - Pixelval binwidth; -}; - -/* - * Statistics structure - * - * The variable nelem counts the number of pixels that contributed to these - * image statistics (which might be less than the number of pixels in the - * region-of-interest if zero-valued pixels aren't included. - */ - -struct hips_stats -{ - int nelem; - int pixel_format; - Pixelval statmin; - Pixelval statmax; - double sum,ssq,mean,var,stdev; -}; - -/* - * Convolution mask set structure - */ - -struct hips_mask -{ - char *name; /* name of this mask set */ - int nmasks; /* number of masks */ - int func_num; /* function applied to mask outputs */ - int pixel_format; /* format of mask elements */ - union { - float **f_values; /* float mask pointers */ - int **i_values; /* int mask pointers */ - } vals; - int *mask_rows; /* number of rows in each mask */ - int *mask_cols; /* number of columns in each mask */ - int *row_offset; /* row number of mask value overlying image - pixel */ - int *col_offset; /* column number of mask value overlying image - pixel */ -}; - -/* - * Mask function numbers - */ - -#define MASKFUN_MAXABS 1 -#define MASKFUN_MEANSQ 2 -#define MASKFUN_SUMABS 3 -#define MASKFUN_MAX 4 -#define MASKFUN_MAXFLR 5 -#define MASKFUN_MXASFLR 6 -#define MASKFUN_MUL 7 -#define MASKFUN_NORM 8 -#define MASKFUN_DIFF 9 -#define MASKFUN_ORIENT 10 -#define MASKFUN_IDENT 11 -#define MASKFUN_MAXMASKS 11 - -/* - * Filter types and structure - * - * A bandpass filter is a concatenation (i.e., product) of a lowpass (using - * highcut/highorder) and a highpass (using lowcut/loworder) filter. A band - * reject filter is one minus the corresponding bandpass filter. - */ - -#define FILTMETHOD_IDEAL 1 -#define FILTMETHOD_BUTTERWORTH 2 -#define FILTMETHOD_EXPONENTIAL 3 - -#define FILTDIST_ROW 1 -#define FILTDIST_COL 2 -#define FILTDIST_BOTH 3 - -#define FILTTYPE_LOWPASS 1 -#define FILTTYPE_HIGHPASS 2 -#define FILTTYPE_BANDPASS 3 -#define FILTTYPE_BANDREJ 4 - -struct hips_filter -{ - int method; /* Ideal/Butterworth/Exponential */ - int disttype; /* scale by number of rows, columns or both */ - int ftype; /* lowpass/highpass/bandpass/bandreject */ - double dmetric; /* Minkowdki metric */ - double lowcut; - int loworder; - double highcut; - int highorder; -}; - -char *strsave(),*memalloc(),*formatheader(),*formatheadera(); -char *formatheaderc(),*hformatname(),*hformatname_f(),*hformatname_t(); -byte *halloc(),*hmalloc(); -fs_hsize_t hsizepix(); -struct extpar *findparam(),*grepparam(); -FILE *hfopenr(),*ffopen(),*ffreopen(); -/* h_boolean getline(),swallownl(),hfgets(); */ - -/* - * avoid hassles of including string.h or strings.h - */ - -#if 0 -extern char *strcat(),*strncat(),*strcpy(),*strncpy(),*index(),*rindex(); -extern char *strchr(),*strdup(),*strstr(); -extern int strcmp(),strncmp(); -#else -#include -#endif - -/* omit strlen so that it defaults to int, but can also be size_t as in gcc */ - -/* - * image and pyramid type declarations for the pyramid routines. - * - * The pyramid utilities are derived from code originally written by - * Raj Hingorani at SRI/David Sarnoff Research Institute. The original - * Gaussian and Laplacian pyramid algorithms were designed by Peter Burt (also - * currently at SRI/DSRC). See: Computer Graphics and Image Processing, - * Volume 16, pp. 20-51, 1981, and IEEE Transactions on Communications, - * Volume COM-31, pp. 532-540, 1983. - */ - -#define MAXLEV 12 - -typedef struct -{ - float **ptr; - int nr; - int nc; -} -FIMAGE; - -typedef struct -{ - int **ptr; - int nr; - int nc; -} -IIMAGE; - -typedef FIMAGE FPYR[MAXLEV]; -typedef IIMAGE IPYR[MAXLEV]; - -typedef struct -{ - float *k; - int taps2; /* the number of taps from the center rightward, - total number is 2*taps2-1 */ -} -FILTER; - -/* function definitions */ - -float **_read_fimgstr(); -int **_read_iimgstr(); -float **_alloc_fimage(); -int **_alloc_iimage(); - -/* externals */ - -extern int Image_border; - -/* image macros */ - -#ifndef MAX -# define MAX(A,B) ((A) > (B) ? (A) : (B)) -#endif -#ifndef MIN -# define MIN(A,B) ((A) < (B) ? (A) : (B)) -#endif -#ifndef ABS -# define ABS(A) ((A) > 0 ? (A) : (-(A))) -#endif -#ifndef BETWEEN -# define BETWEEN(A,B,C) (((A) < (B)) ? (B) : (((A) > (C)) ? (C) : (A))) -#endif -#ifndef SIGN -# define SIGN(A,B) (((B) > 0) ? (A) : (-(A))) -#endif -#ifndef TOascii -# define TOascii(c) ((c) & 0x7f) -#endif - -/* compatibilities, type lists, etc. */ - -#define LASTTYPE -1 /* the last type in a type list */ - -#define CM_ROWS 01 /* check compatibility: ROI rows */ -#define CM_COLS 02 /* check compatibility: ROI cols */ -#define CM_FRAMES 04 /* check compatibility: frames & depths */ -#define CM_FORMAT 010 /* check compatibility: pixel format */ -#define CM_NUMCOLOR 020 /* check compatibility: numcolor */ -#define CM_NUMLEV 040 /* check compatibility: pyramid levels */ -#define CM_OROWS 0100 /* check compatibility: total # rows */ -#define CM_OCOLS 0200 /* check compatibility: total # cols */ -#define CM_FRAMESC 0400 /* check compatibility: check frames & depths -if numcolor != 1 or numdepth != 1 */ -#define CM_NUMCOLOR3 01000 /* check compatibility: numcolor (treat -RGB, etc. as if numcolor=3) */ -#define CM_DEPTH 02000 /* check compatibility: numdepth */ - - /* converting to packed formats */ - -#define MSBF_PACKING 1 /* use most significant bit first packing */ -#define LSBF_PACKING 2 /* use least significant bit first packing */ - - /* converting complex numbers to single-valued numbers */ - -#define CPLX_MAG 1 /* complex magnitude */ -#define CPLX_PHASE 2 /* complex phase */ -#define CPLX_REAL 3 /* complex - real part only */ -#define CPLX_IMAG 4 /* complex - imaginary part only */ - - /* converting single-valued numbers to complex numbers */ - -#define CPLX_RVI0 1 /* real part = value, imaginary = 0 */ -#define CPLX_R0IV 2 /* real part = 0, imaginary = value */ -#define CPLX_RVIV 3 /* real part = value, imaginary = same value */ - - /* - * type conversion methods - * - * Note: because find_method returns a method identifier, or METH_IDENT, - * or the negative of a method identifier (for conversion via PFINT), it is - * essential that none of these possible values be identical to HIPS_ERROR so - * that it also can give a normal hips error return. - */ - -#define METH_IDENT 2 -#define METH_BYTE 3 -#define METH_COMPLEX 4 -#define METH_DOUBLE 5 -#define METH_DBLCOM 6 -#define METH_FLOAT 7 -#define METH_INT 8 -#define METH_LSBF 9 -#define METH_MSBF 10 -#define METH_SHORT 11 -#define METH_SBYTE 12 -#define METH_UINT 13 -#define METH_USHORT 14 -#define METH_RGB 15 -#define METH_RGBZ 16 -#define METH_ZRGB 17 -#define METH_BGR 18 -#define METH_BGRZ 19 -#define METH_ZBGR 20 - - /* conversion-related variables */ - - extern int hips_packing; - extern byte hips_lchar; - extern byte hips_hchar; - extern int hips_cplxtor; - extern int hips_rtocplx; - extern int hips_convback; - extern int hips_lclip,hips_hclip; - extern int hips_zdiv; - extern h_boolean hips_oldhdr; - - /* header handling */ - - extern int hips_fullhist; - extern int hips_fulldesc; - extern int hips_fullxpar; - - struct h_types - { /* the type names structure defined in htypes.c */ - int h_pfmt; /* pixel format */ -char *h_fmtname; /* sprintf string for error code */ -}; - -struct h_convs -{ /* the conversion names structure defined in htype.c */ - int h_cnvtype; /* pixel format */ -char *h_cnvname; /* sprintf string for error code */ -}; - -/* useful constants and functions */ - -#define RND01 ((double)H__RANDOM()/(double)H__MAXRAND) -#define RNDPM (RND01 > 0.5 ? 1.0 : -1.0) -#ifndef SQR -#define SQR(x) ((x)*(x)) -#endif -#define H_E 2.7182818284590452354 -#define H_LOG2E 1.4426950408889634074 -#define H_LOG10E 0.43429448190325182765 -#define H_LN2 0.69314718055994530942 -#define H_LN10 2.30258509299404568402 -#define H_PI 3.14159265358979323846 -#define H_2PI 6.28318530717958647692 -#define H_PI_2 1.57079632679489661923 -#define H_PI_4 0.78539816339744830962 -#define H_3PI_2 4.71238898038468985769 -#define H_ONE_PI 0.31830988618379067154 -#define H_TWO_PI 0.63661977236758134308 -#define H_TWO_SQRTPI 1.12837916709551257390 -#define H_180_PI 57.2957795130823208768 /* degrees to radians */ -#define H_SQRT2 1.41421356237309504880 -#define H_SQRT1_2 0.70710678118654752440 -#define H_SQRT3OVER2 0.86602540378443864676 - -#endif diff --git a/include/hips_error.h b/include/hips_error.h deleted file mode 100644 index 18697b6151a..00000000000 --- a/include/hips_error.h +++ /dev/null @@ -1,198 +0,0 @@ -/** - * @file hips_error.h - * @brief definitions related to the HIPS error handler - * - */ -/* - * Original Author: Michael Landy - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2007/11/18 03:03:32 $ - * $Revision: 1.3 $ - * - * General inquiries: freesurfer@nmr.mgh.harvard.edu - * Bug reports: analysis-bugs@nmr.mgh.harvard.edu - * - */ - - -#ifndef HIPS_ERROR_H -#define HIPS_ERROR_H - -/* - * Copyright (c) 1991 Michael Landy - * - * Disclaimer: No guarantees of performance accompany this software, - * nor is any responsibility assumed on the part of the authors. All the - * software has been tested extensively and every effort has been made to - * insure its reliability. - */ - -/* - * hips_error.h - definitions related to the HIPS error handler - * - * Michael Landy - 12/28/90 - */ - -/* error-related variables */ - -extern int hipserrno; -extern int hipserrlev; /* if errlev <= errno - then print&die */ -extern int hipserrprt; /* if errprt <= errno < errlev - then print&return */ -extern char hipserr[]; - -struct h_errstruct -{ /* the error structure defined in herrs.c */ - char *h_errstr; /* sprintf string for error code */ - int h_errfmt; /* list of variables for sprintf */ - int h_errsev; /* error severity */ -}; - -#define HIPS_ERROR -1 /* error-return from hips routines */ -#define HIPS_OK 0 /* one possible nonerror-return value */ - -/* Error code severities */ -#define HEL_INFORM 1 /* informational */ -#define HEL_WARN 2 /* warning */ -#define HEL_ERROR 3 /* error */ -#define HEL_SEVERE 4 /* severe error */ - -/* - * Standard error codes, the strings are defined in lib/herrs.c - * - * Note that these codes must be allocated sequentially, starting from 1. - * perr.c depends on this fact. - */ - -#define HE_ALLOC 1 /* "can't allocate memory" */ -#define HE_ALLOCSUBR 2 /* "%s: can't allocate memory" */ -#define HE_FREE 3 /* "can't free memory" */ -#define HE_READFR 4 /* "error reading frame %d" */ -#define HE_READFRFILE 5 /* "error reading frame %d from file %s" */ -#define HE_READFILE 6 /* "error reading from file %s" */ -#define HE_READ 7 /* "error during read" */ -#define HE_WRITEFR 8 /* "error writing frame %d" */ -#define HE_WRITEFRFILE 9 /* "error writing frame %d to file %s" */ -#define HE_OPEN 10 /* "can't open file: `%s'" */ -#define HE_SEEK 11 /* "can't perform seek" */ -#define HE_FMTMATCH 12 /* "pixel format mismatch" */ -#define HE_FMTMATCHFILE 13 /* "pixel format mismatch, file %s" */ -#define HE_FMT 14 /* "can't handle pixel format %s" */ -#define HE_FMTFILE 15 /* "can't handle pixel format %s, file: %s" */ -#define HE_POW2 16 /* "image dimensions must be powers of 2" */ -#define HE_SNEG 17 /* "number of frames must be zero or positive" */ -#define HE_SMATCH 18 /* "size mismatch" */ -#define HE_FRMATCH 19 /* "mismatch of number of frames" */ -#define HE_LARGE 20 /* "frame dimensions are too large" */ -#define HE_ZNEG 21 /* "zero or negative dimension" */ -#define HE_BUF 22 /* "%s: buffer limit exceeded" */ -#define HE_CODE 23 /* "%s: unknown op-code" */ -#define HE_CUT1 24 /* "cut_frame: 1 intersection" */ -#define HE_CUTI 25 /* "cut_frame: intersections not between?" */ -#define HE_FFTI 26 /* "%s: strange index=%d" */ -#define HE_PYRTLZ 27 /* "pyrnumpix: toplev less than zero?" */ -#define HE_PYRTL 28 /* "pyrnumpix: toplev too large?" */ -#define HE_REFL 29 /* "%s: Invalid reflection type %d" */ -#define HE_FRMEND 30 /* "read_frame: did not find frame-end" */ -#define HE_HDRREAD 31 /* "error while reading header, file %s" */ -#define HE_HDRPREAD 32 /* "error reading extended parameters, file %s" */ -#define HE_HDRBREAD 33 /* "error reading binary parameters, file %s" */ -#define HE_HDRPTYPE 34 /* "invalid extended parameter format %d, file %s" */ -#define HE_HDRXOV 35 -/* "header parameters overflow, file: %s, size should be %d and was %d" */ -#define HE_HDRWRT 36 /* "error while writing header, file %s" */ -#define HE_HDRPWRT 37 /* "error while writing header parameters, file %s" */ -#define HE_HDRBWRT 38 /* "error while writing header binary area, file %s" */ -#define HE_HDWPTYPE 39 -/* "invalid extended parameter format %d during write, file %s" */ -#define HE_REQ 40 /* "%s: reqested %d, got %d" */ -#define HE_BADFMT 41 /* "invalid format code %d" */ -#define HE_HDPTYPE 42 /* "%s: invalid extended parameter format %d" */ -#define HE_MISSPAR 43 /* "%s: can't find extended parameter %s" */ -#define HE_C_ROW 44 /* "mismatched number of rows, file: %s" */ -#define HE_C_COL 45 /* "mismatched number of columns, file: %s" */ -#define HE_C_FRM 46 /* "mismatched number of frames, file: %s" */ -#define HE_C_FMT 47 /* "mismatched pixel format (%s), file: %s" */ -#define HE_C_NCL 48 /* "mismatched number of colors, file: %s" */ -#define HE_C_NLV 49 /* "mismatched number of pyramid levels, file: %s" */ -#define HE_FMTSUBR 50 /* "%s: can't handle pixel format %s" */ -#define HE_CTORTP 51 /* "%s: unknown complex-to-real conversion: %d" */ -#define HE_METH 52 /* "%s: unknown method (%d), file: %s" */ -#define HE_FMTSUBRFILE 53 /* "%s: can't handle pixel format %s, file: %s" */ -#define HE_SETFP 54 /* "setformat: can't handle pyramid formats" */ -#define HE_SETPF 55 /* "setpyrformat: can only handle pyramid formats" */ -#define HE_RTOCTP 56 /* "%s: unknown real-to-complex conversion: %d" */ -#define HE_MSG 57 /* "%s" */ -#define HE_ROI 58 -/* "setroi: ROI out of bounds, first=(%d,%d), size=(%d,%d)" */ -#define HE_CONV 59 /* "converting from %s to %s, file: %s" */ -#define HE_CONVI 60 /* "converting from %s to %s via integer, file: %s" */ -#define HE_SMALL 61 /* "frame dimensions are too small" */ -#define HE_RNG 62 /* "%s: invalid range" */ -#define HE_XINC 63 -/* "header parameters inconsistency for (%s %d %d %d) offset is %d, file: %s" */ -#define HE_ROI8 64 /* "%s: packed image ROI - columns not multiple of 8" */ -#define HE_ROI8F 65 -/* "%s: packed image ROI - columns not multiple of 8, file: %s" */ -#define HE_ROI8C 66 -/* "%s: packed image ROI - columns not multiple of 8, clearing ROI" */ -#define HE_IMSG 67 /* "%s" */ -#define HE_UNKFLG 68 /* "unrecognised flag option %s\n%s" */ -#define HE_MUTEX 69 /* "flags are mutually exclusive\n%s" */ -#define HE_MISSFPAR 70 /* "missing parameter for flag %s\n%s" */ -#define HE_INVFPAR 71 /* "invalid parameter %s for flag %s\n%s" */ -#define HE_SYNTAX 72 /* "invalid syntax\n%s" */ -#define HE_FILECNT 73 /* "too many image filenames\n%s" */ -#define HE_MISSFILE 74 /* "missing image filenames\n%s" */ -#define HE_INVFILE 75 /* "invalid image filename %s" */ -#define HE_STDIN 76 /* "can't open the standard input twice" */ -#define HE_FMT3SUBR 77 -/* "%s: can't handle pixel format combination %s/%s/%s" */ -#define HE_FMT2SUBR 78 -/* "%s: can't handle pixel format combination %s/%s" */ -#define HE_RCSELN 79 /* "%s: row/column selection out of range" */ -#define HE_C_OROW 80 /* "mismatched total number of rows, file: %s" */ -#define HE_C_OCOL 81 /* "mismatched total number of columns, file: %s" */ -#define HE_C_FRMC 82 -/* "mismatched number of frames and numcolor>1 or numdepth > 1, file: %s" */ -#define HE_MULT2 83 /* "image dimensions must be multiples of 2" */ -#define HE_MSKFUNFILE 84/* "bad mask function number %d, file: %s" */ -#define HE_MSKFUNSUBR 85/* "%s: bad mask function number %d" */ -#define HE_MSKCNT 86 /* "%s: mask function %d, bad mask count %d" */ -#define HE_SIGMA 87 /* "%s: sigma less than or equal to zero" */ -#define HE_PTWICE 88 /* "flag `-%s' specified more than once" */ -#define HE_WINDSZ 89 /* "%s: invalid window size (%d)" */ -#define HE_COMPOV 90 /* "component table overflow" */ -#define HE_PNTOV 91 /* "point table overflow" */ -#define HE_FILTPAR 92 /* "bad filter parameter" */ -#define HE_HDRPTYPES 93 /* "invalid extended parameter format %s, file %s" */ -#define HE_COLSPEC 94 /* "%s: invalid color specification: `%s'" */ -#define HE_PNAME 95 /* "%s: parameter name contains white space: `%s'" */ -#define HE_PCOUNT 96 /* "%s: supplied count doesn't match that of `%s'" */ -#define HE_COLOVF 97 /* "%s: colormap table overflow, file: %s */ -#define HE_FMTSLEN 98 /* "length of formats array mismatch, file: %s" */ -#define HE_COL1 99 /* "input 3-color image has numcolor>1, file %s" */ -#define HE_COL3 100 -/* "can't convert 1-color image with numcolor!=3 to 3-color, file %s" */ -#define HE_C_DEPTH 101 /* "mismatched number of depths, file: %s" */ -#define HE_C_DPTHC 102 -/* "mismatched number of depths and numcolor>1 or numdepth > 1, file: %s" */ -#define HE_BADDEPTH 103 /* "bad value of depth, should be > 0" */ -#define MAXERR 103 - -/* error print formats */ - -#define HEP_N 0 /* no arguments */ -#define HEP_D 1 /* %d */ -#define HEP_S 2 /* %s */ -#define HEP_SD 3 /* %s %d */ -#define HEP_DS 4 /* %d %s */ -#define HEP_SS 5 /* %s %s */ -#define HEP_SDD 6 /* %s %d %d */ -#define HEP_SDS 7 /* %s %d %s */ -#define HEP_SSS 8 /* %s %s %s */ -#define HEP_DDDD 9 /* %d %d %d %d */ -#define HEP_SDDDDS 10 /* %s %d %d %d %d %s */ -#define HEP_SSSS 11 /* %s %s %s %s */ - -#endif diff --git a/include/hips_header.h b/include/hips_header.h deleted file mode 100644 index eb242f4e499..00000000000 --- a/include/hips_header.h +++ /dev/null @@ -1,180 +0,0 @@ -/** - * @file hips_header.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: zkaufman $ - * $Date: 2016/02/24 16:23:27 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef HIPS_HEADER_H -#define HIPS_HEADER_H - -/* - * Copyright (c) 1991 Michael Landy - * - * Disclaimer: No guarantees of performance accompany this software, - * nor is any responsibility assumed on the part of the authors. All the - * software has been tested extensively and every effort has been made to - * insure its reliability. - */ - -/* - * hips_header.h - definitions related to the HIPS header - * - * Michael Landy - 12/28/90 - */ - -/* The HIPS header as stored in memory */ - -struct header -{ - char *orig_name; /* The originator of this sequence */ - h_boolean ondealloc; /* If nonzero, free orig_name when requested */ - char *seq_name; /* The name of this sequence */ - h_boolean sndealloc; /* If nonzero, free seq_name when requested */ - int num_frame; /* The number of frames in this sequence */ - char *orig_date; /* The date the sequence was originated */ - h_boolean oddealloc; /* If nonzero, free orig_date when requested */ - int orows; /* The number of rows in each stored image */ - int ocols; /* The number of columns in each stored image */ - int rows; /* The number of rows in each image (ROI) */ - int cols; /* The number of columns in each image (ROI) */ - int frow; /* The first ROI row */ - int fcol; /* The first ROI col */ - int pixel_format; /* The format of each pixel */ - int numcolor; /* The number of color frames per image */ - int numpix; /* The number of pixels per stored frame */ - fs_hsize_t sizepix; /* The number of bytes per pixel */ - fs_hsize_t sizeimage; /* The number of bytes per stored frame */ - byte *image; /* The image itself */ - h_boolean imdealloc; /* if nonzero, free image when requested */ - byte *firstpix; /* Pointer to first pixel (for ROI) */ - int sizehist; /* Number of bytes in history (excluding - null, including ) */ - char *seq_history; /* The sequence's history of transformations */ - h_boolean histdealloc; /* If nonzero, free history when requested */ - int sizedesc; /* Number of bytes in description (excluding - null, including ) */ - char *seq_desc; /* Descriptive information */ - h_boolean seqddealloc; /* If nonzero, free desc when requested */ - int numparam; /* Count of additional parameters */ - h_boolean paramdealloc; /* If nonzero, free param structures and/or - param values when requested */ - struct extpar *params; /* Additional parameters */ - float xsize ; - float ysize ; -}; - -struct hips_roi -{ - int rows; /* The number of rows in the ROI */ - int cols; /* The number of columns in the ROI */ - int frow; /* The first ROI row */ - int fcol; /* The first ROI col */ -}; - -/* - * Pixel Format Codes - */ - -#define PFBYTE 0 /* Bytes interpreted as unsigned integers */ -#define PFSHORT 1 /* Short integers (2 bytes) */ -#define PFINT 2 /* Integers (4 bytes) */ -#define PFFLOAT 3 /* Float's (4 bytes)*/ -#define PFCOMPLEX 4 /* 2 Float's interpreted as (real,imaginary) */ -#define PFASCII 5 /* ASCII rep, with linefeeds after each row */ -#define PFDOUBLE 6 /* Double's (8 byte floats) */ -#define PFDBLCOM 7 /* Double complex's (2 Double's) */ -#define PFQUAD 10 /* quad-tree encoding (Mimaging) */ -#define PFQUAD1 11 /* quad-tree encoding */ -#define PFHIST 12 /* histogram of an image (using ints) */ -#define PFSPAN 13 /* spanning tree format */ -#define PLOT3D 24 /* plot-3d format */ -#define PFMSBF 30 /* packed, most-significant-bit first */ -#define PFLSBF 31 /* packed, least-significant-bit first */ -#define PFSBYTE 32 /* signed bytes */ -#define PFUSHORT 33 /* unsigned shorts */ -#define PFUINT 34 /* unsigned ints */ -#define PFRGB 35 /* RGB RGB RGB bytes */ -#define PFRGBZ 36 /* RGB0 RGB0 RGB0 bytes */ -#define PFZRGB 37 /* 0RGB 0RGB 0RGB bytes */ -#define PFMIXED 40 /* multiple frames in different pixel formats */ -#define PFBGR 41 /* BGR BGR BGR bytes */ -#define PFBGRZ 42 /* BGR0 BGR0 BGR0 bytes */ -#define PFZBGR 43 /* 0BGR 0BGR 0BGR bytes */ -#define PFINTPYR 50 /* integer pyramid */ -#define PFFLOATPYR 51 /* float pyramid */ -#define PFPOLYLINE 100 /* 2D points */ -#define PFCOLVEC 101 /* Set of RGB triplets defining colours */ -#define PFUKOOA 102 /* Data in standard UKOOA format */ -#define PFTRAINING 104 /* Set of colour vector training examples */ -#define PFTOSPACE 105 /* TOspace world model data structure */ -#define PFSTEREO 106 /* Stereo sequence (l, r, l, r, ...) */ -#define PFRGPLINE 107 /* 2D points with regions */ -#define PFRGISPLINE 108 /* 2D points with regions and interfaces */ -#define PFCHAIN 200 /* Chain code encoding (Mimaging) */ -#define PFLUT 300 /* LUT format (uses Ints) (Mimaging) */ -#define PFAHC 400 /* adaptive hierarchical encoding */ -#define PFOCT 401 /* oct-tree encoding */ -#define PFBT 402 /* binary tree encoding */ -#define PFAHC3 403 /* 3-d adaptive hierarchical encoding */ -#define PFBQ 404 /* binquad encoding */ -#define PFRLED 500 /* run-length encoding */ -#define PFRLEB 501 /* run-length encoding, line begins black */ -#define PFRLEW 502 /* run-length encoding, line begins white */ -#define PFPOLAR 600 /* rho-theta format (Mimaging) */ -#define PFGRLE 601 /* gray scale run-length encoding */ -#define PFSRLE 602 /* monochrome run-scale encoding */ -#define PFVFFT3D 701 /* float complex 3D virtual-very fast FT */ -#define PFVFFT2D 702 /* float complex 2D virtual-very fast FT */ -#define PFDVFFT3D 703 /* double complex 3D VFFT */ -#define PFDVFFT2D 704 /* double complex 2D VFFT */ -#define PFVVFFT3D 705 /* float 3D VFFT in separated planes */ -#define PFDVVFFT3D 706 /* double 3D VVFFT in separated planes */ - - -/* The Extended Parameters Structure */ - -struct extpar -{ - char *name; /* name of this variable */ - int format; /* format of values (PFBYTE, PFINT, etc.) */ - int count; /* number of values */ - union { - byte v_b; /* PFBYTE/PFASCII, count = 1 */ - int v_i; /* PFINT, count = 1 */ - short v_s; /* PFSHORT, count = 1 */ - float v_f; /* PFFLOAT, count = 1 */ - byte *v_pb; /* PFBYT/PFASCIIE, count > 1 */ - int *v_pi; /* PFINT, count > 1 */ - short *v_ps; /* PFSHORT, count > 1 */ - float *v_pf; /* PFFLOAT, count > 1 */ - } val; - h_boolean dealloc; /* if nonzero, free memory for val */ - struct extpar *nextp; /* next parameter in list */ -}; - -#define FBUFLIMIT 30000 /* increase this if you use large PLOT3D -files */ -#define LINELENGTH 200 /* max characters per line in header vars */ -#define NULLPAR ((struct extpar *) 0) - -#endif diff --git a/include/hips_parser.h b/include/hips_parser.h deleted file mode 100644 index 0be2d175dee..00000000000 --- a/include/hips_parser.h +++ /dev/null @@ -1,177 +0,0 @@ -/** - * @file hips_parser.h - * @brief definitions related to the HIPS argument parser - * - */ -/* - * Original Author: Michael Landy - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2010/03/13 01:32:40 $ - * $Revision: 1.3 $ - * - * Copyright (c) 1991 Michael Landy - * - * Disclaimer: No guarantees of performance accompany this software, - * nor is any responsibility assumed on the part of the authors. All the - * software has been tested extensively and every effort has been made to - * insure its reliability. - */ - -/* - * Make the library visible. - */ - -extern int parseargs (); - -/* - * Define an enumeration for the accepted trailing filename formats. Note - * that these should keep in sequence since they are used as index values - * in data structures internal to the parser. - */ - -#define FFNONE 0 -#define FFONE 1 -#define FFTWO 2 -#define FFLIST 3 - -typedef int Filename_Format; - -/* - * Define a flag as a character string of arbitrary length. - */ - -typedef char *Flag; - -#define LASTFLAG (Flag) 0 /* Terminator for flag list */ - -/* - * Define an enumeration for the accepted parameter types. Note that - * these values should keep in sequence since they are used as index - * values in data structures internal to the parser. - */ - -#define PTNULL -1 /* Null type used as error/terminator */ -#define PTBOOLEAN 0 -#define PTCHAR 1 -#define PTSTRING 2 -#define PTINT 3 -#define PTDOUBLE 4 -#define PTFILENAME 5 -#define PTLIST 6 - -typedef int Parameter_Type; - -#define LASTPARAMETER PTNULL /* Terminator for parameter type list */ - -/* - * Define a structure for a parameter to a flag option. This holds the - * type of the parameter and its default value. Note that the default - * value is given as a string. - */ - -struct parameter -{ - Parameter_Type type; - char *pdefault; - char *par_usage; -}; - -typedef struct parameter Parameter; - -/* - * Define a structure for the format of the flag options accepted by a HIPS - * filter. This consists of the flag option itself, a list of all the - * mutually exclusive flag options, a count of the minimum number of - * parameters which must be present and a list of the types and default - * values of all parameters associated with the option. - * - * Note that this is the structure which is filled in by the user for - * each flag recognised by a filter and passed to the parser. - */ - -#define MAX_MUTEX_FLAGS 20 /* Arbitrary limits - may be extended */ -#define MAX_PARAMETERS 20 - -struct flag_format -{ - Flag value; - Flag mutex_flags [MAX_MUTEX_FLAGS]; - int min_parameters; - Parameter parameters [MAX_PARAMETERS]; -}; - -typedef struct flag_format Flag_Format; - -/* - * Define a structure to hold a list of trailing filenames. - */ - -struct file_list -{ - int *count; - char ***list; -}; - -typedef struct file_list File_List; - -/* - * Define a pointer to the filenames associated with each of the - * accepted filename formats. - */ - -union filename_ptr -{ - char **filename; - char **filepair [2]; - File_List filenames; -}; - -typedef union filename_ptr Filename_Ptr; - -/* - * Define a structure to hold a PTLIST parameter - */ - -struct listarg -{ - int argcount; - char **args; -}; - -typedef struct listarg Listarg; - -/* - * Define a generic pointer to a parameter of arbitrary type. - */ - -union generic_ptr -{ - int *boolean_ptr; - char *char_ptr; - char **string_ptr; - int *int_ptr; - double *double_ptr; - char **filename_ptr; - Listarg *listarg_ptr; -}; - -typedef union generic_ptr Generic_Ptr; - -/* - * Define a structure to hold a list of pointers to each of the - * parameters assoociated with a flag. The variables pointed to by these - * pointers are set to contain the required operating mode for the - * filter. The structure also holds a signal to indicate whether a flag - * is mutually excluded. - */ - -struct flag_key -{ - Flag_Format *format; - Generic_Ptr parameter_ptrs[MAX_PARAMETERS]; - int locked; /* Really h_boolean*/ - h_boolean specified; -}; - -typedef struct flag_key Flag_Key; diff --git a/include/hipsext.h b/include/hipsext.h deleted file mode 100644 index 58c3cef8f74..00000000000 --- a/include/hipsext.h +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @file hipsext.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/****************************************************** - * Name: hipsext.h - * Purpose: include file for hips library extentions - ******************************************************/ - -#ifndef INC_HIPSEXT - -#define INC_HIPSEXT - -#include"canny.h" -#include"const.h" -#include"diag.h" -#include"error.h" -#include"general.h" -#include"handle.h" -#include"hmem.h" -#include"image.h" -#include"iutils.h" -#include"ldtmplt.h" -#include"lp.h" -#include"machine.h" -#include"macros.h" -#include"matfile.h" -#include"matrix.h" -#include"mthread.h" -#include"proto.h" -#include"queue.h" -#include"thread.h" -#include"utils.h" -#include"window.h" - - -#endif diff --git a/include/hipsh.h b/include/hipsh.h deleted file mode 100644 index 8135c0247fe..00000000000 --- a/include/hipsh.h +++ /dev/null @@ -1,963 +0,0 @@ -/** - * @file hipsh.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef HIPSH_H -#define HIPSH_H - -#include "hips.h" - -/**************** hipsh.h *********************/ -/******************* seqord.c ***********************/ -int h_seqord(struct header *hdi,struct header *hdo); -int h_seqord_i(struct header *hdi,struct header *hdo); -int h_seqord_f(struct header *hdi,struct header *hdo); -int h_seqord_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_seqord_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_invseqord(struct header *hdi,struct header *hdo); -int h_invseqord_i(struct header *hdi,struct header *hdo); -int h_invseqord_f(struct header *hdi,struct header *hdo); -int h_invseqord_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_invseqord_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int invorder(int index,int len); -/******************* abdou.c ***********************/ -int h_abdou(struct header *hdi,struct header *hdo,int size); -int h_abdou_b(struct header *hdi,struct header *hdo,int size); -int h_abdou_B(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int size); -/******************* hconvolv.c ***********************/ -int h_hconvolve(struct header *hdi,struct header *hdo,int *mask,int nmask,int offset); -int h_hconvolve_i(struct header *hdi,struct header *hdo,int *mask,int nmask,int offset); -int h_hconvolve_f(struct header *hdi,struct header *hdo,float *mask,int nmask,int offset); -int h_hconvolve_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int *mask,int nmask,int offset); -int h_hconvolve_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float *mask,int nmask,int offset); -/******************* nonisot.c ***********************/ -int h_nonisot(struct header *hdi,struct header *hdc,int nmasks,struct header **hdm ,struct header *hdo); -int h_nonisot_i(struct header *hdi,struct header *hdc,int nmasks,struct header **hdm ,struct header *hdo); -int h_nonisot_I(int *imagei,int *imagec,int nmasks,int **imagem ,int *imageo,int nr,int nc,int nlpi,int nlpc,int *nrm,int *ncm,int *nlpm,int nlpo); -/******************* abs.c ***********************/ -int h_abs(struct header *hdi,struct header *hdo); -int h_abs_i(struct header *hdi,struct header *hdo); -int h_abs_f(struct header *hdi,struct header *hdo); -int h_abs_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_abs_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* absdiff.c ***********************/ -int h_absdiff(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_absdiff_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_absdiff_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_absdiff_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_absdiff_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_absdiff_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_absdiff_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_absdiff_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_absdiff_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_absdiff_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_absdiff_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* add.c ***********************/ -int h_add(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_bii(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_bsb(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_c(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_dc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_add_BII(unsigned char *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_add_BSB(unsigned char *imagei1,short *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_add_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_add_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_add_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_add_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_add_C(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_add_DC(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* addcos.c ***********************/ -int h_addcos(struct header *hdi,struct header *hdo,double xf,double yf,double phase,double amplitude); -int h_addcos_f(struct header *hdi,struct header *hdo,double xf,double yf,double phase,double amplitude); -int h_addcos_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double xf,double yf,double phase,double amplitude); -/******************* addgabor.c ***********************/ -int h_addgabor(struct header *hdi,struct header *hdo,double xm,double ym,double xf,double yf,double xs,double ys,double phase,double amplitude); -int h_addgabor_f(struct header *hdi,struct header *hdo,double xm,double ym,double xf,double yf,double xs,double ys,double phase,double amplitude); -int h_addgabor_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double xm,double ym,double xf,double yf,double xs,double ys,double phase,double amplitude); -/******************* affine.c ***********************/ -int h_affine(struct header *hdi,struct header *hdo,double A,double B,double C,double a,double b,double c); -int h_affine_b(struct header *hdi,struct header *hdo,double A,double B,double C,double a,double b,double c); -int h_affine_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nor,int noc,int nlpo,double A,double B,double C,double a,double b,double c); -/******************* and.c ***********************/ -int h_and(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_and_mp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_and_lp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_and_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_and_MP(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_and_LP(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_and_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* applylut.c ***********************/ -int h_applylut(struct header *hdi,struct header *hdo,int count,unsigned char *lut); -int h_applylut_b(struct header *hdi,struct header *hdo,int count,unsigned char *lut); -int h_applylut_s(struct header *hdi,struct header *hdo,int count,short *lut); -int h_applylut_i(struct header *hdi,struct header *hdo,int count,int *lut); -int h_applylut_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int count,unsigned char *lut); -int h_applylut_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,int count,short *lut); -int h_applylut_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int count,int *lut); -/******************* avg.c ***********************/ -int h_avg(struct header *hdi1,struct header *hdi2,struct header *hdo,double wt1,double wt2); -int h_avg_b(struct header *hdi1,struct header *hdi2,struct header *hdo,double wt1,double wt2); -int h_avg_s(struct header *hdi1,struct header *hdi2,struct header *hdo,double wt1,double wt2); -int h_avg_i(struct header *hdi1,struct header *hdi2,struct header *hdo,double wt1,double wt2); -int h_avg_f(struct header *hdi1,struct header *hdi2,struct header *hdo,double wt1,double wt2); -int h_avg_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,double wt1,double wt2); -int h_avg_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,double wt1,double wt2); -int h_avg_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,double wt1,double wt2); -int h_avg_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,double wt1,double wt2); -/******************* bclean.c ***********************/ -int h_bclean(struct header *hd,int size); -int h_bclean_b(struct header *hd,int size); -int h_bclean_B(unsigned char *image,int nr,int nc,int nlp,int size); -int addneigh(int xx,int yy,int comp); -int inlist(int xx,int yy); -/******************* bnoise.c ***********************/ -int h_bnoise(struct header *hdi,struct header *hdo,int n,double p,union pixelval *addc,union pixelval *mulc); -int h_bnoise_b(struct header *hdi,struct header *hdo,int n,double p,union pixelval *addc,union pixelval *mulc); -int h_bnoise_i(struct header *hdi,struct header *hdo,int n,double p,union pixelval *addc,union pixelval *mulc); -int h_bnoise_f(struct header *hdi,struct header *hdo,int n,double p,union pixelval *addc,union pixelval *mulc); -int h_bnoise_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int n,double p,int addc,int mulc); -int h_bnoise_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int n,double p,int addc,int mulc); -int h_bnoise_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int n,double p,double addc,double mulc); -int compute_blookup(int n,double p); -/******************* checkers.c ***********************/ -int h_checkers(struct header *hd,int highflag); -int h_checkers_b(struct header *hd,int highflag); -int h_checkers_B(unsigned char *image,int nr,int nc,int nlp,int highflag); -/******************* clearhis.c ***********************/ -int h_clearhisto(struct hips_histo *histogram); -int h_Clearhisto(int nbins,int *histo); -/******************* colorkey.c ***********************/ -int h_colorkey(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_bb(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_bi(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_bf(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_ib(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_ii(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_if(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_ipip(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_ipfp(struct header *hdc,int nimage,struct header **hdi ,struct header *hdo,int bflag); -int h_colorkey_BB(unsigned char *imagec,int nimage,unsigned char **imagei ,unsigned char *imageo,int nr,int nc,int nlpc,int *nlpi,int nlpo,int bflag); -int h_colorkey_BI(unsigned char *imagec,int nimage,int **imagei ,int *imageo,int nr,int nc,int nlpc,int *nlpi,int nlpo,int bflag); -int h_colorkey_BF(unsigned char *imagec,int nimage,float **imagei ,float *imageo,int nr,int nc,int nlpc,int *nlpi,int nlpo,int bflag); -int h_colorkey_IB(int *imagec,int nimage,unsigned char **imagei ,unsigned char *imageo,int nr,int nc,int nlpc,int *nlpi,int nlpo,int bflag); -int h_colorkey_II(int *imagec,int nimage,int **imagei ,int *imageo,int nr,int nc,int nlpc,int *nlpi,int nlpo,int bflag); -int h_colorkey_IF(int *imagec,int nimage,float **imagei ,float *imageo,int nr,int nc,int nlpc,int *nlpi,int nlpo,int bflag); -int h_colorkargs(int nimage,struct header **hdi ); -int h_colorkargsp(int nimage,struct header **hdi ); -/******************* combine.c ***********************/ -int h_combine(struct header *hdi1,struct header *hdi2,struct header *hdo,int phasemagflag); -int h_combine_f(struct header *hdi1,struct header *hdi2,struct header *hdo,int phasemagflag); -int h_combine_d(struct header *hdi1,struct header *hdi2,struct header *hdo,int phasemagflag); -int h_combine_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,int phasemagflag); -int h_combine_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,int phasemagflag); -/******************* convolve.c ***********************/ -int h_convolve(struct header *hdi,struct header *hdk,struct header *hdo,int firsti,int firstk,int numf); -int h_convolve_i(struct header *hdi,struct header *hdk,struct header *hdo,int firsti,int firstk,int numf); -int h_convolve_f(struct header *hdi,struct header *hdk,struct header *hdo,int firsti,int firstk,int numf); -int h_convolve_I(int *imagei,int *imagek,int *imageo,int nri,int nci,int tnri,int nlpi,int nrk,int nck,int tnrk,int nlpk,int nfrk,int nlpo,int firsti,int firstk,int numf); -int h_convolve_F(float *imagei,float *imagek,float *imageo,int nri,int nci,int tnri,int nlpi,int nrk,int nck,int tnrk,int nlpk,int nfrk,int nlpo,int firsti,int firstk,int numf); -/******************* copy.c ***********************/ -int h_copy(struct header *hdi,struct header *hdo); -int h_copy_mp(struct header *hdi,struct header *hdo); -int h_copy_lp(struct header *hdi,struct header *hdo); -int h_copy_b(struct header *hdi,struct header *hdo); -int h_copy_s(struct header *hdi,struct header *hdo); -int h_copy_i(struct header *hdi,struct header *hdo); -int h_copy_f(struct header *hdi,struct header *hdo); -int h_copy_d(struct header *hdi,struct header *hdo); -int h_copy_c(struct header *hdi,struct header *hdo); -int h_copy_dc(struct header *hdi,struct header *hdo); -int h_copy_MP(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_LP(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_copy_DC(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* correl.c ***********************/ -int h_correl(struct header *hdi1,struct header *hdi2,struct header *hdo,int dr0,int dc0); -int h_correl_f(struct header *hdi1,struct header *hdi2,struct header *hdo,int dr0,int dc0); -int h_correl_F(float *imagei1,float *imagei2,float *imageo,int nr1,int nc1,int nr2,int nc2,int nro,int nco,int nlpi1,int nlpi2,int nlpo,int dr0,int dc0); -/******************* dct.c ***********************/ -int h_dct(struct header *ihd,struct header *ohd); -int h_dct_f(struct header *ihd,struct header *ohd); -int h_dct_d(struct header *ihd,struct header *ohd); -int h_dct_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_dct_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo); -int h_dctinv(struct header *ihd,struct header *ohd); -int h_dctinv_f(struct header *ihd,struct header *ohd); -int h_dctinv_d(struct header *ihd,struct header *ohd); -int h_dctinv_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_dctinv_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo); -int h_dct2d_f(float *veci,float *veco,int logrows,int logcols,int nlpi,int nlpo); -int h_dctinv2d_f(float *veci,float *veco,int logrows,int logcols,int nlpi,int nlpo); -int h_dct2d_d(double *veci,double *veco,int logrows,int logcols,int nlpi,int nlpo); -int h_dctinv2d_d(double *veci,double *veco,int logrows,int logcols,int nlpi,int nlpo); -int h_dctfree(void); -/******************* diff.c ***********************/ -int h_diff(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_ibi(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_c(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_dc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_diff_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_diff_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_diff_IBI(int *imagei1,unsigned char *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_diff_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_diff_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_diff_C(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_diff_DC(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* discedge.c ***********************/ -int h_discedge2(struct header *hdi,struct header *hdo,int size,double varcrit,int edgethresh); -int h_discedge2_b(struct header *hdi,struct header *hdo,int size,double varcrit,int edgethresh); -int h_discedge2_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int size,double varcrit,int edgethresh); -/******************* disphist.c ***********************/ -int h_disphist(struct hips_histo *histo,struct header *hd,int barwidth,int barheight,int maxcnt,int borderw,int borderg); -int h_disphist_b(struct hips_histo *histo,struct header *hd,int barwidth,int barheight,int maxcnt,int borderw,int borderg); -int h_disphist_B(int *histo,int nbins,unsigned char *image,int nlp,int barwidth,int barheight,int maxcnt,int borderw,int borderg); -/******************* dither.c ***********************/ -int h_dither(struct header *hdi,struct header *hdo); -int h_dither_b(struct header *hdi,struct header *hdo); -int h_dither_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* div.c ***********************/ -int h_div(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_fc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_ddc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_c(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_cf(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_dc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_dcd(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_div_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_FC(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_DDC(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_C(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_CF(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_DC(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_div_DCD(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* divscale.c ***********************/ -int h_divscale(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_s(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_ib(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_i(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_if(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_f(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_c(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_dc(struct header *hdi,struct header *hdo,union pixelval *b); -int h_divscale_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,short b); -int h_divscale_Ss(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,short b); -int h_divscale_Sf(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,short b); -int h_divscale_IB(int *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int b); -int h_divscale_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int b); -int h_divscale_IF(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double b); -int h_divscale_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double b); -int h_divscale_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double b); -int h_divscale_DC(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,double b); -/******************* dotdiff.c ***********************/ -int h_dotdiff(struct header *hdi,struct header *hdt,struct header *hdo); -int h_dotdiff_b(struct header *hdi,struct header *hdt,struct header *hdo); -int h_dotdiff_S(unsigned char *imagei,short *imaget,unsigned char *imageo,int nr,int nc,int nlpi,int nlpt,int nlpo); -int weight(int x,int y); -/******************* enlarge.c ***********************/ -int h_enlarge(struct header *hdi,struct header *hdo,int xf,int yf); -int h_enlarge_b(struct header *hdi,struct header *hdo,int xf,int yf); -int h_enlarge_i(struct header *hdi,struct header *hdo,int xf,int yf); -int h_enlarge_f(struct header *hdi,struct header *hdo,int xf,int yf); -int h_enlarge_c(struct header *hdi,struct header *hdo,int xf,int yf); -int h_enlarge_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -int h_enlarge_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -int h_enlarge_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -int h_enlarge_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -/******************* entropy.c ***********************/ -double h_entropy(int *table,int count,int pairflag); -/******************* entropyc.c ***********************/ -int h_entropycnt(struct header *hd,int *table,int pairflag); -int h_entropycnt_b(struct header *hd,int *table,int pairflag); -int h_entropycnt_B(unsigned char *image,int nr,int nc,int nlp,int *table,int pairflag); -/******************* exp.c ***********************/ -int h_exp(struct header *hdi,struct header *hdo); -int h_exp_b(struct header *hdi,struct header *hdo); -int h_exp_s(struct header *hdi,struct header *hdo); -int h_exp_i(struct header *hdi,struct header *hdo); -int h_exp_f(struct header *hdi,struct header *hdo); -int h_exp_B(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_exp_S(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_exp_I(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_exp_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* extract.c ***********************/ -int h_extract(struct header *hdi,struct header *hdo,int frow,int fcol,int nrows,int ncols); -/******************* extremum.c ***********************/ -int h_extremum(struct header *hdi,struct header *hdo,int size); -int h_extremum_b(struct header *hdi,struct header *hdo,int size); -int h_extremum_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int size); -/******************* fastaddc.c ***********************/ -int h_fastaddcos(struct header *hdi,struct header *hdo,int xf,int yf,double phase,double amplitude); -int h_fastaddcos_f(struct header *hdi,struct header *hdo,int xf,int yf,double phase,double amplitude); -int h_fastaddcos_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf,double phase,double amplitude); -/******************* fft2.c ***********************/ -int h_fft_ri_c(float *rvec,float *ivec,int loglen); -int h_fft2d_ri_c(float *rvec,float *ivec,int loglen); -int h_fft2dgen_ri_c(float *rvec,float *ivec,int logrows,int logcols); -int h_fftn_ri_c(float *rvec,float *ivec,int loglen,int nskip); -int h_fft_ri_dc(double *rvec,double *ivec,int loglen); -int h_fft2d_ri_dc(double *rvec,double *ivec,int loglen); -int h_fft2dgen_ri_dc(double *rvec,double *ivec,int logrows,int logcols); -int h_fftn_ri_dc(double *rvec,double *ivec,int loglen,int nskip); -/******************* filter.c ***********************/ -int h_filter(struct header *hdi,struct header *hdo,struct hips_filter *filter); -int h_filter_f(struct header *hdi,struct header *hdo,struct hips_filter *filter); -int h_filter_d(struct header *hdi,struct header *hdo,struct hips_filter *filter); -int h_filter_c(struct header *hdi,struct header *hdo,struct hips_filter *filter); -int h_filter_dc(struct header *hdi,struct header *hdo,struct hips_filter *filter); -int h_filter_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int method,int disttype,int ftype,double dmetric,double lowcut,int loworder,double highcut,int highorder); -int h_filter_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,int method,int disttype,int ftype,double dmetric,double lowcut,int loworder,double highcut,int highorder); -int h_filter_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int method,int disttype,int ftype,double dmetric,double lowcut,int loworder,double highcut,int highorder); -int h_filter_DC(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,int method,int disttype,int ftype,double dmetric,double lowcut,int loworder,double highcut,int highorder); -int calcdist(int disttype,double dmetric,int nr2,int nc2); -double modulate(void); -/******************* flipquad.c ***********************/ -int h_flipquad(struct header *hdi,struct header *hdo); -int h_flipquad_b(struct header *hdi,struct header *hdo); -int h_flipquad_f(struct header *hdi,struct header *hdo); -int h_flipquad_d(struct header *hdi,struct header *hdo); -int h_flipquad_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_flipquad_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -int h_flipquad_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* fourtr.c ***********************/ -int h_fourtr(struct header *hd); -int h_fourtr_c(struct header *hd); -int h_fourtr_dc(struct header *hd); -int h_fourtr_C(float (*image)[2],int nr,int nc,int nlp); -int h_fourtr_DC(double (*image)[2],int nr,int nc,int nlp); -int h_fft_c(float (*vec)[2],int loglen); -int h_fft2d_c(float (*vec)[2],int loglen,int nlp); -int h_fft2dgen_c(float (*vec)[2],int logrows,int logcols,int nlp); -int h_fftn_c(float (*vec)[2],int loglen,int nskip); -int h_fft_dc(double (*vec)[2],int loglen); -int h_fft2d_dc(double (*vec)[2],int loglen,int nlp); -int h_fft2dgen_dc(double (*vec)[2],int logrows,int logcols,int nlp); -int h_fftn_dc(double (*vec)[2],int loglen,int nskip); -/******************* fourtr3d.c ***********************/ -int h_fourtr3d(struct header *hd); -int h_fourtr3d_c(struct header *hd); -int h_fourtr3d_C(float (*image)[2],int nr,int nc,int nf); -/******************* gaussmas.c ***********************/ -double h_gaussmask(double sigma,int nmask,float *maskarr,int precision); -/******************* gnoise.c ***********************/ -int h_gnoise(struct header *hdi,struct header *hdo,double p,int fastflag); -int h_gnoise_s(struct header *hdi,struct header *hdo,double p,int fastflag); -int h_gnoise_f(struct header *hdi,struct header *hdo,double p,int fastflag); -int h_gnoise_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,double p,int fastflag); -int h_gnoise_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double p,int fastflag); -double rand_gauss(void); -int srand_g(unsigned int x); -double rand_g(void); -/******************* greybar.c ***********************/ -int h_greybar(struct header *hd,int width,double low,double step); -int h_greybar_b(struct header *hd,int width,double low,double step); -int h_greybar_B(unsigned char *image,int nr,int nc,int nlp,int width,double low,double step); -/******************* gridwarp.c ***********************/ -int h_gridwarp(struct header *hdi,struct header *hdo,int nx,int ny,float *ogridx,float *ogridy,float *igridx,float *igridy); -int h_gridwarp_b(struct header *hdi,struct header *hdo,int nx,int ny,float *ogridx,float *ogridy,float *igridx,float *igridy); -int h_gridwarp_B(unsigned char *imagei,unsigned char *imageo,int nri,int nci,int nlpi,int nro,int nco,int nlpo,int nx,int ny,float *ogridx,float *ogridy,float *igridx,float *igridy); -int truncup(double x); -int truncdown(double x); -/******************* halftone.c ***********************/ -int h_halftone(struct header *hdi,struct header *hdo); -int h_halftone2(struct header *hdi,struct header *hdo,int lower,int upper,int rflag,int alpha,int beta,int gamma,int delta); -int h_halftone_b(struct header *hdi,struct header *hdo,int lower,int upper,int rflag,int alpha,int beta,int gamma,int delta); -int h_halftone_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int lower,int upper,int rflag,int alpha,int beta,int gamma,int delta); -/******************* hardthre.c ***********************/ -int h_hardthresh(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_hardthresh_b(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_hardthresh_i(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_hardthresh_f(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_hardthresh_c(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_hardthresh_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,unsigned char thresh); -int h_hardthresh_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int thresh); -int h_hardthresh_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double thresh); -int h_hardthresh_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double thresh); -/******************* histo.c ***********************/ -int h_histo(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_b(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_sb(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_s(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_us(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_i(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_ui(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_f(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_d(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_c(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_dc(struct header *hd,struct hips_histo *histogram,int nzflag,int *count); -int h_histo_B(unsigned char *image,int nr,int nc,int nlp,int nbins,int *histo,unsigned char min,unsigned char width,int nzflag,int *count); -int h_histo_SB(char *image,int nr,int nc,int nlp,int nbins,int *histo,char min,char width,int nzflag,int *count); -int h_histo_S(short *image,int nr,int nc,int nlp,int nbins,int *histo,short min,short width,int nzflag,int *count); -int h_histo_US(unsigned short *image,int nr,int nc,int nlp,int nbins,int *histo,unsigned short min,unsigned short width,int nzflag,int *count); -int h_histo_I(int *image,int nr,int nc,int nlp,int nbins,int *histo,int min,int width,int nzflag,int *count); -int h_histo_UI(unsigned int *image,int nr,int nc,int nlp,int nbins,int *histo,unsigned int min,unsigned int width,int nzflag,int *count); -int h_histo_F(float *image,int nr,int nc,int nlp,int nbins,int *histo,double min,double width,int nzflag,int *count); -int h_histo_D(double *image,int nr,int nc,int nlp,int nbins,int *histo,double min,double width,int nzflag,int *count); -int h_histo_C(float *image,int nr,int nc,int nlp,int nbins,int *histo,double min,double width,int nzflag,int *count); -int h_histo_DC(double *image,int nr,int nc,int nlp,int nbins,int *histo,double min,double width,int nzflag,int *count); -/******************* histoeq.c ***********************/ -int h_histoeq(struct hips_histo *histogram,int count,unsigned char *map); -int h_histoeq_b(struct hips_histo *histogram,int count,unsigned char *map); -int h_histoeq_B(int nbins,int *histo,int count,unsigned char *map); -/******************* ienlarge.c ***********************/ -int h_ienlarge3(struct header *hdi1,struct header *hdi2,struct header *hdo,int xf,int yf,int tf,int t); -int h_ienlarge3_b(struct header *hdi1,struct header *hdi2,struct header *hdo,int xf,int yf,int tf,int t); -int h_ienlarge3_i(struct header *hdi1,struct header *hdi2,struct header *hdo,int xf,int yf,int tf,int t); -int h_ienlarge3_f(struct header *hdi1,struct header *hdi2,struct header *hdo,int xf,int yf,int tf,int t); -int h_ienlarge3_c(struct header *hdi1,struct header *hdi2,struct header *hdo,int xf,int yf,int tf,int t); -int h_ienlarge3_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,int xf,int yf,int tf,int t); -int h_ienlarge3_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,int xf,int yf,int tf,int t); -int h_ienlarge3_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,int xf,int yf,int tf,int t); -int h_ienlarge3_C(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo,int xf,int yf,int tf,int t); -int ienl3_alloc(int xf,int yf,int tf); -/******************* invert.c ***********************/ -int h_invert(struct header *hdi,struct header *hdo); -int h_invert_lp(struct header *hdi,struct header *hdo); -int h_invert_mp(struct header *hdi,struct header *hdo); -int h_invert_b(struct header *hdi,struct header *hdo); -int h_invert_i(struct header *hdi,struct header *hdo); -int h_invert_f(struct header *hdi,struct header *hdo); -int h_invert_MP(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_invert_LP(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_invert_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_invert_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_invert_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* invfourt.c ***********************/ -int h_invfourtr(struct header *hd); -int h_invfourtr_c(struct header *hd); -int h_invfourtr_dc(struct header *hd); -int h_invfourtr_C(float (*image)[2],int nr,int nc,int nlp); -int h_invfourtr_DC(double (*image)[2],int nr,int nc,int nlp); -/******************* linscale.c ***********************/ -int h_linscale(struct header *hdi,struct header *hdo,float b,float c); -int h_linscale_b(struct header *hdi,struct header *hdo,float b,float c); -int h_linscale_s(struct header *hdi,struct header *hdo,float b,float c); -int h_linscale_i(struct header *hdi,struct header *hdo,float b,float c); -int h_linscale_f(struct header *hdi,struct header *hdo,float b,float c); -int h_linscale_B(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -int h_linscale_Bs(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -int h_linscale_Bf(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -int h_linscale_S(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -int h_linscale_Ss(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -int h_linscale_Sf(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -int h_linscale_I(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -int h_linscale_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float b,float c); -/******************* log.c ***********************/ -int h_log(struct header *hdi,struct header *hdo,double offset); -int h_log_b(struct header *hdi,struct header *hdo,double offset); -int h_log_s(struct header *hdi,struct header *hdo,double offset); -int h_log_i(struct header *hdi,struct header *hdo,double offset); -int h_log_f(struct header *hdi,struct header *hdo,double offset); -int h_log_B(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_Bs(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_Bf(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_S(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_Ss(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_Sf(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_I(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_Is(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_If(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -int h_log_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double offset); -/******************* mask.c ***********************/ -int h_mask(struct header *hdi,struct hips_mask *mask,struct header *hdo); -int h_mask_bif(struct header *hdi,struct hips_mask *mask,struct header *hdo); -int h_mask_bff(struct header *hdi,struct hips_mask *mask,struct header *hdo); -int h_mask_iif(struct header *hdi,struct hips_mask *mask,struct header *hdo); -int h_mask_iff(struct header *hdi,struct hips_mask *mask,struct header *hdo); -int h_mask_fff(struct header *hdi,struct hips_mask *mask,struct header *hdo); -int h_mask_BIF(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int nmasks,int maskfunc,int **masks ,int *mrows,int *mcols,int *mrowoff,int *mcoloff); -int h_mask_BFF(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int nmasks,int maskfunc,float **masks ,int *mrows,int *mcols,int *mrowoff,int *mcoloff); -int h_mask_IIF(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int nmasks,int maskfunc,int **masks ,int *mrows,int *mcols,int *mrowoff,int *mcoloff); -int h_mask_IFF(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int nmasks,int maskfunc,float **masks ,int *mrows,int *mcols,int *mrowoff,int *mcoloff); -int h_mask_FFF(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int nmasks,int maskfunc,float **masks ,int *mrows,int *mcols,int *mrowoff,int *mcoloff); -int h_mask_alloc(int nr,int nc,int nlpi,int *mrows,int *mcols,int *mrowoff,int *mcoloff); -int h_mask_valloc(int format); -float h_mask_value_i(void); -float h_mask_value_f(void); -/******************* max.c ***********************/ -int h_max(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_b(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_sb(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_s(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_us(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_i(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_ui(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_f(struct header *hd,union pixelval *maxval,int nzflag); -int h_max_d(struct header *hd,union pixelval *maxval,int nzflag); -unsigned char h_max_B(unsigned char *image,int nr,int nc,int nlp,int nzflag); -char h_max_SB(char *image,int nr,int nc,int nlp,int nzflag); -short h_max_S(short *image,int nr,int nc,int nlp,int nzflag); -unsigned short h_max_US(unsigned short *image,int nr,int nc,int nlp,int nzflag); -int h_max_I(int *image,int nr,int nc,int nlp,int nzflag); -unsigned int h_max_UI(unsigned int *image,int nr,int nc,int nlp,int nzflag); -float h_max_F(float *image,int nr,int nc,int nlp,int nzflag); -double h_max_D(double *image,int nr,int nc,int nlp,int nzflag); -/******************* maxabsp.c ***********************/ -int h_maxabsp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxabsp_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxabsp_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxabsp_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxabsp_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxabsp_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxabsp_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxabsp_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_maxabsp_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_maxabsp_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_maxabsp_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* maxhisto.c ***********************/ -int h_maxhisto(struct hips_histo *histo); -int h_Maxhisto(int *histo,int nbins); -/******************* maxp.c ***********************/ -int h_maxp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_maxp_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_maxp_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_maxp_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_maxp_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_maxp_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* mean.c ***********************/ -int h_mean(struct header *hd,float *mean,int nzflag); -int h_mean_f(struct header *hd,float *mean,int nzflag); -float h_mean_F(float *image,int nr,int nc,int nlp,int nzflag); -/******************* median.c ***********************/ -int h_median(struct header *hdi,struct header *hdo,int size); -int h_median_b(struct header *hdi,struct header *hdo,int size); -int h_median_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int size); -int sselect(int k,int *lo,int *hi); -/******************* minabsp.c ***********************/ -int h_minabsp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minabsp_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minabsp_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minabsp_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minabsp_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minabsp_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minabsp_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minabsp_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_minabsp_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_minabsp_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_minabsp_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* minmax.c ***********************/ -int h_minmax(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_b(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_sb(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_s(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_us(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_i(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_ui(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_f(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_d(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_c(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_dc(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag); -int h_minmax_B(unsigned char *image,int nr,int nc,int nlp,unsigned char *rmin,unsigned char *rmax,int nzflag); -int h_minmax_SB(char *image,int nr,int nc,int nlp,char *rmin,char *rmax,int nzflag); -int h_minmax_S(short *image,int nr,int nc,int nlp,short *rmin,short *rmax,int nzflag); -int h_minmax_US(unsigned short *image,int nr,int nc,int nlp,unsigned short *rmin,unsigned short *rmax,int nzflag); -int h_minmax_I(int *image,int nr,int nc,int nlp,int *rmin,int *rmax,int nzflag); -int h_minmax_UI(unsigned int *image,int nr,int nc,int nlp,unsigned int *rmin,unsigned int *rmax,int nzflag); -int h_minmax_F(float *image,int nr,int nc,int nlp,float *rmin,float *rmax,int nzflag); -int h_minmax_D(double *image,int nr,int nc,int nlp,double *rmin,double *rmax,int nzflag); -int h_minmax_C(float *image,int nr,int nc,int nlp,float *rmin,float *rmax,int nzflag); -int h_minmax_DC(double *image,int nr,int nc,int nlp,double *rmin,double *rmax,int nzflag); -/******************* minp.c ***********************/ -int h_minp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_minp_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_minp_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_minp_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_minp_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_minp_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* minroi.c ***********************/ -int h_minroi(struct header *hd,int gray); -int h_minroi_b(struct header *hd,int gray); -int h_minroi_B(unsigned char *image,int nr,int nc,int nlp,int *frow,int *fcol,int *lrow,int *lcol,int gray); -/******************* morphdil.c ***********************/ -int h_morphdil(struct header *hdi,struct header *hde,struct header *hdo,int centerr,int centerc,int gray); -int h_morphdil_b(struct header *hdi,struct header *hde,struct header *hdo,int centerr,int centerc,int gray); -int h_morphdil_B(unsigned char *imagei,unsigned char *imagee,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int nre,int nce,int nlpe,int centerr,int centerc,int gray); -/******************* morphero.c ***********************/ -int h_morphero(struct header *hdi,struct header *hde,struct header *hdt,struct header *hdo,int centerr,int centerc,int gray); -int h_morphero_b(struct header *hdi,struct header *hde,struct header *hdt,struct header *hdo,int centerr,int centerc,int gray); -int h_morphero_B(unsigned char *imagei,unsigned char *imagee,int *imaget,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int nlpt,int nre,int nce,int nlpe,int centerr,int centerc,int gray); -/******************* mul.c ***********************/ -int h_mul(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_s(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_i(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_fc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_d(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_ddc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_c(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_dc(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_ip(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_fp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_mul_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_S(short *imagei1,short *imagei2,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_I(int *imagei1,int *imagei2,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_FC(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_D(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_DDC(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_C(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_mul_DC(double *imagei1,double *imagei2,double *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* mulscale.c ***********************/ -int h_mulscale(struct header *hdi,struct header *hdo,union pixelval *b); -int h_mulscale_b(struct header *hdi,struct header *hdo,union pixelval *b); -int h_mulscale_s(struct header *hdi,struct header *hdo,union pixelval *b); -int h_mulscale_i(struct header *hdi,struct header *hdo,union pixelval *b); -int h_mulscale_f(struct header *hdi,struct header *hdo,union pixelval *b); -int h_mulscale_d(struct header *hdi,struct header *hdo,union pixelval *b); -int h_mulscale_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,unsigned char b); -int h_mulscale_Bs(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,unsigned char b); -int h_mulscale_Bf(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,unsigned char b); -int h_mulscale_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,short b); -int h_mulscale_Ss(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,short b); -int h_mulscale_Sf(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,short b); -int h_mulscale_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int b); -int h_mulscale_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double b); -int h_mulscale_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,double b); -/******************* neg.c ***********************/ -int h_neg(struct header *hdi,struct header *hdo); -int h_neg_mp(struct header *hdi,struct header *hdo); -int h_neg_lp(struct header *hdi,struct header *hdo); -int h_neg_b(struct header *hdi,struct header *hdo); -int h_neg_s(struct header *hdi,struct header *hdo); -int h_neg_i(struct header *hdi,struct header *hdo); -int h_neg_f(struct header *hdi,struct header *hdo); -int h_neg_MP(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_neg_LP(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_neg_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_neg_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo); -int h_neg_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_neg_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* noise.c ***********************/ -int h_noise(struct header *hdi,struct header *hdo,double p,int *counter,int bpp); -int h_noise_b(struct header *hdi,struct header *hdo,double p,int *counter,int bpp); -int h_noise_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,double p,int *counter,int bpp); -/******************* or.c ***********************/ -int h_or(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_or_mp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_or_lp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_or_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_or_MP(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_or_LP(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_or_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* pixmap.c ***********************/ -int h_pixmap(struct header *hdi,struct header *hdo,unsigned char *map); -int h_pixmap_b(struct header *hdi,struct header *hdo,unsigned char *map); -int h_pixmap_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,unsigned char *map); -/******************* power.c ***********************/ -int h_power(struct header *hdi,struct header *hdo,double power); -int h_power_b(struct header *hdi,struct header *hdo,double power); -int h_power_s(struct header *hdi,struct header *hdo,double power); -int h_power_i(struct header *hdi,struct header *hdo,double power); -int h_power_f(struct header *hdi,struct header *hdo,double power); -int h_power_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,double power); -int h_power_Bs(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,double power); -int h_power_Bf(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,double power); -int h_power_S(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double power); -int h_power_Ss(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double power); -int h_power_Sf(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double power); -int h_power_I(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double power); -int h_power_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double power); -/******************* pyrdisp.c ***********************/ -#if 0 -int h_pyrdisp(struct FIMAGEtag *pyr,int botlev,int toplev,struct header *hdo,int cflag,int margin); -int h_pyrdisp_i(struct IIMAGEtag *pyr,int botlev,int toplev,struct header *hdo,int cflag,int margin); -int h_pyrdisp_f(struct FIMAGEtag *pyr,int botlev,int toplev,struct header *hdo,int cflag,int margin); -int h_pyrdisp_I(struct IIMAGEtag *pyr,int botlev,int toplev,int *imageo,int nlpo,int cflag,int margin); -int h_pyrdisp_F(struct FIMAGEtag *pyr,int botlev,int toplev,float *imageo,int nlpo,int cflag,int margin); -#endif -/******************* quadscal.c ***********************/ -int h_quadscale(struct header *hdi,struct header *hdo,double a,double b,double c); -int h_quadscale_b(struct header *hdi,struct header *hdo,double a,double b,double c); -int h_quadscale_s(struct header *hdi,struct header *hdo,double a,double b,double c); -int h_quadscale_i(struct header *hdi,struct header *hdo,double a,double b,double c); -int h_quadscale_f(struct header *hdi,struct header *hdo,double a,double b,double c); -int h_quadscale_B(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -int h_quadscale_Bs(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -int h_quadscale_Bf(unsigned char *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -int h_quadscale_S(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -int h_quadscale_Ss(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -int h_quadscale_Sf(short *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -int h_quadscale_I(int *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -int h_quadscale_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double a,double b,double c); -/******************* reduce.c ***********************/ -int h_reduce(struct header *hdi,struct header *hdo,int xf,int yf); -int h_reduce_bi(struct header *hdi,struct header *hdo,int xf,int yf); -int h_reduce_s(struct header *hdi,struct header *hdo,int xf,int yf); -int h_reduce_i(struct header *hdi,struct header *hdo,int xf,int yf); -int h_reduce_f(struct header *hdi,struct header *hdo,int xf,int yf); -int h_reduce_c(struct header *hdi,struct header *hdo,int xf,int yf); -int h_reduce_BI(unsigned char *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -int h_reduce_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -int h_reduce_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -int h_reduce_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -int h_reduce_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int xf,int yf); -/******************* reflect.c ***********************/ -int h_reflect(struct header *hdi,struct header *hdo); -int h_reflect_b(struct header *hdi,struct header *hdo); -int h_reflect_i(struct header *hdi,struct header *hdo); -int h_reflect_f(struct header *hdi,struct header *hdo); -int h_reflect_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_reflect_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_reflect_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* rot180.c ***********************/ -int h_rot180(struct header *hdi,struct header *hdo); -int h_rot180_b(struct header *hdi,struct header *hdo); -int h_rot180_i(struct header *hdi,struct header *hdo); -int h_rot180_f(struct header *hdi,struct header *hdo); -int h_rot180_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_rot180_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_rot180_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* rot90.c ***********************/ -int h_rot90(struct header *hdi,struct header *hdo,int dirflag); -int h_rot90_b(struct header *hdi,struct header *hdo,int dirflag); -int h_rot90_i(struct header *hdi,struct header *hdo,int dirflag); -int h_rot90_f(struct header *hdi,struct header *hdo,int dirflag); -int h_rot90_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int dirflag); -int h_rot90_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int dirflag); -int h_rot90_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int dirflag); -/******************* sample.c ***********************/ -int h_sample(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_b(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_s(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_i(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_f(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_d(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_c(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_dc(struct header *hdi,struct header *hdo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int ratex,int ratey,int offsetx,int offsety); -int h_sample_DC(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,int ratex,int ratey,int offsetx,int offsety); -/******************* scaleadd.c ***********************/ -int h_scaleadd(struct header *hdi,struct header *hdo,double s); -int h_scaleadd_f(struct header *hdi,struct header *hdo,double s); -int h_scaleadd_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double s); -/******************* sepconv.c ***********************/ -int h_sepconv(struct header *hdi,struct header *hdt,struct header *hdo,int *maskh,int nmaskh,int offseth,int *maskv,int nmaskv,int offsetv); -int h_sepconv_i(struct header *hdi,struct header *hdt,struct header *hdo,int *maskh,int nmaskh,int offseth,int *maskv,int nmaskv,int offsetv); -int h_sepconv_f(struct header *hdi,struct header *hdt,struct header *hdo,float *maskh,int nmaskh,int offseth,float *maskv,int nmaskv,int offsetv); -/******************* setimage.c ***********************/ -int h_setimage(struct header *hd,union pixelval *val); -int h_setimage_mp(struct header *hd,union pixelval *val); -int h_setimage_lp(struct header *hd,union pixelval *val); -int h_setimage_b(struct header *hd,union pixelval *val); -int h_setimage_sb(struct header *hd,union pixelval *val); -int h_setimage_s(struct header *hd,union pixelval *val); -int h_setimage_us(struct header *hd,union pixelval *val); -int h_setimage_i(struct header *hd,union pixelval *val); -int h_setimage_ui(struct header *hd,union pixelval *val); -int h_setimage_f(struct header *hd,union pixelval *val); -int h_setimage_d(struct header *hd,union pixelval *val); -int h_setimage_c(struct header *hd,union pixelval *val); -int h_setimage_dc(struct header *hd,union pixelval *val); -int h_setimage_MP(unsigned char *image,int nr,int nc,int nlp,unsigned char val); -int h_setimage_LP(unsigned char *image,int nr,int nc,int nlp,unsigned char val); -int h_setimage_B(unsigned char *image,int nr,int nc,int nlp,unsigned char val); -int h_setimage_SB(char *image,int nr,int nc,int nlp,char val); -int h_setimage_S(short *image,int nr,int nc,int nlp,short val); -int h_setimage_US(unsigned short *image,int nr,int nc,int nlp,unsigned short val); -int h_setimage_I(int *image,int nr,int nc,int nlp,int val); -int h_setimage_UI(unsigned int *image,int nr,int nc,int nlp,unsigned int val); -int h_setimage_F(float *image,int nr,int nc,int nlp,double val); -int h_setimage_D(double *image,int nr,int nc,int nlp,double val); -int h_setimage_C(float *image,int nr,int nc,int nlp,float *val); -int h_setimage_DC(double *image,int nr,int nc,int nlp,double *val); -/******************* shift.c ***********************/ -int h_shift(struct header *hdi,struct header *hdo,int shift); -int h_shift_b(struct header *hdi,struct header *hdo,int shift); -int h_shift_i(struct header *hdi,struct header *hdo,int shift); -int h_shift_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int shift); -int h_shift_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int shift); -/******************* shufflea.c ***********************/ -int h_shuffleadd(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_shuffleadd_bsb(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_shuffleadd_f(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_shuffleadd_BSB(unsigned char *imagei1,short *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_shuffleadd_F(float *imagei1,float *imagei2,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int shuffle(int *p,int n); -/******************* slice.c ***********************/ -int h_slice(struct header *hdi,struct header *hdo,int rowcol,int vflag); -int h_slice_b(struct header *hdi,struct header *hdo,int rowcol,int vflag); -int h_slice_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int rowcol,int vflag); -/******************* softthre.c ***********************/ -int h_softthresh(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_softthresh_b(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_softthresh_i(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_softthresh_f(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_softthresh_c(struct header *hdi,struct header *hdo,union pixelval *thresh); -int h_softthresh_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,unsigned char thresh); -int h_softthresh_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int thresh); -int h_softthresh_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double thresh); -int h_softthresh_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double thresh); -/******************* stats.c ***********************/ -int h_stats(struct header *hd,struct hips_stats *stats,int nzflag); -int h_stats_b(struct header *hd,struct hips_stats *stats,int nzflag); -int h_stats_f(struct header *hd,struct hips_stats *stats,int nzflag); -int h_stats_B(unsigned char *image,int nr,int nc,int nlp,int *rnelem,unsigned char *rmin,unsigned char *rmax,double *rsum,double *rssq,int nzflag); -int h_stats_F(float *image,int nr,int nc,int nlp,int *rnelem,float *rmin,float *rmax,double *rsum,double *rssq,int nzflag); -/******************* stretch.c ***********************/ -int h_stretch(struct header *hdi,struct header *hdo,double d,double expt1,double expt2,union pixelval *mval); -int h_stretch_b(struct header *hdi,struct header *hdo,double d,double expt1,double expt2,union pixelval *mval); -int h_stretch_s(struct header *hdi,struct header *hdo,double d,double expt1,double expt2,union pixelval *mval); -int h_stretch_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,double d,double expt1,double expt2,unsigned char mval); -int h_stretch_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,double d,double expt1,double expt2,short mval); -int h_stretch_Sf(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,double d,double expt1,double expt2,short mval); -int h_stretch_Ss(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,double d,double expt1,double expt2,short mval); -/******************* stretchi.c ***********************/ -int h_stretchimg(struct header *hdi,struct header *hdo); -int h_stretchimg_b(struct header *hdi,struct header *hdo); -int h_stretchimg_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nor,int noc,int nlpo); -/******************* thicken.c ***********************/ -int h_thicken(struct header *hdi,struct header *hdo); -int h_thicken_b(struct header *hdi,struct header *hdo); -int h_thicken_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* thin.c ***********************/ -int h_thin(struct header *hd,int *passflag,int sflag,int vflag,int f); -int h_thin_b(struct header *hd,int *passflag,int sflag,int vflag,int f); -int h_thin_B(unsigned char *image,int nr,int nc,int nlp,int *passflag,int sflag,int vflag,int f); -int addmult(int row,int col,int label); -int neighbor(int r,int c,int d); -/******************* translat.c ***********************/ -int h_translate(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_b(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_s(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_i(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_f(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_d(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_c(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_dc(struct header *hdi,struct header *hdo,int shiftx,int shifty,int palinflag); -int h_translate_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo,int shiftx,int shifty,int palinflag); -int h_translate_S(short *imagei,short *imageo,int nr,int nc,int nlpi,int nlpo,int shiftx,int shifty,int palinflag); -int h_translate_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int shiftx,int shifty,int palinflag); -int h_translate_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int shiftx,int shifty,int palinflag); -int h_translate_D(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,int shiftx,int shifty,int palinflag); -int h_translate_C(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,int shiftx,int shifty,int palinflag); -int h_translate_DC(double *imagei,double *imageo,int nr,int nc,int nlpi,int nlpo,int shiftx,int shifty,int palinflag); -/******************* transpos.c ***********************/ -int h_transpose(struct header *hdi,struct header *hdo); -int h_transpose_b(struct header *hdi,struct header *hdo); -int h_transpose_i(struct header *hdi,struct header *hdo); -int h_transpose_f(struct header *hdi,struct header *hdo); -int h_transpose_B(unsigned char *imagei,unsigned char *imageo,int nr,int nc,int nlpi,int nlpo); -int h_transpose_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo); -int h_transpose_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo); -/******************* vconvolv.c ***********************/ -int h_vconvolve(struct header *hdi,struct header *hdo,int *mask,int nmask,int offset); -int h_vconvolve_i(struct header *hdi,struct header *hdo,int *mask,int nmask,int offset); -int h_vconvolve_f(struct header *hdi,struct header *hdo,float *mask,int nmask,int offset); -int h_vconvolve_I(int *imagei,int *imageo,int nr,int nc,int nlpi,int nlpo,int *mask,int nmask,int offset); -int h_vconvolve_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,float *mask,int nmask,int offset); -/******************* walshtr.c ***********************/ -int h_walshtr(struct header *hd); -int h_walshtr_i(struct header *hd); -int h_walshtr_f(struct header *hd); -int h_walshtr_I(int *image,int nr,int nc); -int h_walshtr_F(float *image,int nr,int nc); -int h_fwt_i(int *vec,int loglen); -int h_fwt_f(float *vec,int loglen); -/******************* wgauss.c ***********************/ -int h_wgauss(struct header *hdi,struct header *hdo,double rowmu,double colmu,double rowsigma,double colsigma,double factor); -int h_wgauss_f(struct header *hdi,struct header *hdo,double rowmu,double colmu,double rowsigma,double colsigma,double factor); -int h_wgauss_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double rowmu,double colmu,double rowsigma,double colsigma,double factor); -/******************* wtsum3.c ***********************/ -int h_wtsum3(struct header *hdi1,struct header *hdi2,struct header *hdi3,struct header *hdo,double wt1,double wt2,double wt3); -int h_wtsum3_b(struct header *hdi1,struct header *hdi2,struct header *hdi3,struct header *hdo,double wt1,double wt2,double wt3); -int h_wtsum3_s(struct header *hdi1,struct header *hdi2,struct header *hdi3,struct header *hdo,double wt1,double wt2,double wt3); -int h_wtsum3_i(struct header *hdi1,struct header *hdi2,struct header *hdi3,struct header *hdo,double wt1,double wt2,double wt3); -int h_wtsum3_f(struct header *hdi1,struct header *hdi2,struct header *hdi3,struct header *hdo,double wt1,double wt2,double wt3); -int h_wtsum3_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imagei3,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpi3,int nlpo,double wt1,double wt2,double wt3); -int h_wtsum3_S(short *imagei1,short *imagei2,short *imagei3,short *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpi3,int nlpo,double wt1,double wt2,double wt3); -int h_wtsum3_I(int *imagei1,int *imagei2,int *imagei3,int *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpi3,int nlpo,double wt1,double wt2,double wt3); -int h_wtsum3_F(float *imagei1,float *imagei2,float *imagei3,float *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpi3,int nlpo,double wt1,double wt2,double wt3); -/******************* xor.c ***********************/ -int h_xor(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_xor_mp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_xor_lp(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_xor_b(struct header *hdi1,struct header *hdi2,struct header *hdo); -int h_xor_MP(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_xor_LP(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -int h_xor_B(unsigned char *imagei1,unsigned char *imagei2,unsigned char *imageo,int nr,int nc,int nlpi1,int nlpi2,int nlpo); -/******************* zc.c ***********************/ -int h_zc(struct header *hdi,struct header *hdo,double error,int nflag,int zflag); -int h_zc_f(struct header *hdi,struct header *hdo,double error,int nflag,int zflag); -int h_zc_F(float *imagei,float *imageo,int nr,int nc,int nlpi,int nlpo,double error,int nflag,int zflag); -/******************* invft3d.c ***********************/ -int h_invfourtr3d(struct header *hd); -int h_invfourtr3d_c(struct header *hd); -int h_invfourtr3d_C(float (*image)[2],int nr,int nc,int nf); - -int h_canny(struct header *Isrc, struct header *Idst, double sigma, - int mask_size,double lfrac,double hfrac,int dothin); - -int h_logmap(struct header *phd,struct header *phd_LM, LMtable *ptable); -int h_LMtable_uniform(LMtable *ptable,struct header *phd_w,int Irows,int Icols, - float a,int R,int Fx,int Fy,float disk_size) ; - -#endif diff --git a/include/hipspub.h b/include/hipspub.h deleted file mode 100644 index d724fac381a..00000000000 --- a/include/hipspub.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file hipspub.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - * Copyright (c) 1992 Michael Landy - * - * Disclaimer: No guarantees of performance accompany this software, - * nor is any responsibility assumed on the part of the authors. All the - * software has been tested extensively and every effort has been made to - * insure its reliability. - */ - -/* - * hipspub.h - definitions of raster HIPS formats - * - * Michael Landy - 9/30/92 - */ - -/* - * Pixel Format Codes (raster formats only) - */ - -#define PFBYTE 0 /* Bytes interpreted as unsigned integers */ -#define PFSHORT 1 /* Short integers (2 bytes) */ -#define PFINT 2 /* Integers (4 bytes) */ -#define PFFLOAT 3 /* Float's (4 bytes)*/ -#define PFCOMPLEX 4 /* 2 Float's interpreted as (real,imaginary) */ -#define PFASCII 5 /* ASCII rep, with linefeeds after each row */ -#define PFDOUBLE 6 /* Double's (8 byte floats) */ -#define PFDBLCOM 7 /* Double complex's (2 Double's) */ -#define PFMSBF 30 /* packed, most-significant-bit first */ -#define PFLSBF 31 /* packed, least-significant-bit first */ -#define PFSBYTE 32 /* signed bytes */ -#define PFUSHORT 33 /* unsigned shorts */ -#define PFUINT 34 /* unsigned ints */ -#define PFRGB 35 /* RGBRGBRGB bytes */ -#define PFRGBZ 36 /* RGB0RGB0RGB0 bytes */ - -#define LINELENGTH 200 /* max characters per line in header vars */ - -#define MSBFIRST 1 /* HIPS-1 bit_packing value for PFMSBF */ -#define LSBFIRST 2 /* HIPS-1 bit_packing value for PFLSBF */ diff --git a/include/hipsu.h b/include/hipsu.h deleted file mode 100644 index 856494f5cc0..00000000000 --- a/include/hipsu.h +++ /dev/null @@ -1,490 +0,0 @@ -/** - * @file hipsu.h - * @brief Header file for hips utility functions - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#include -#include -#include - -/**************** hipsu.h *********************/ -/* Header file for hips utility functions */ -/******************* add_head.c ***********************/ -int history_set(struct header *hda,...); -int history_append(struct header *hda,...); -int history_indentadd(struct header *hd,char *s); -/******************* addplot.c ***********************/ -int addpoint(char *buf,int index,int limit,double b,double x,double y,double z); -int addvec(char *buf,int index,int limit,double b,double x1,double y1,double z1,double x2,double y2,double z2); -int addend(char *buf,int index,int limit,double x,double y,double z); -/******************* getplot.c ***********************/ -int getplot(char *buf,int index,int *op,double *b,double *x1,double *y1,double *z1,double *x2,double *y2,double *z2); -/******************* trans_fr.c ***********************/ -int trans_frame(char *buf,int nbuf,double *shift_v,double (*rot_m)[3],int *flags); -/******************* alloc_hi.c ***********************/ -int alloc_histo(struct hips_histo *histo,union pixelval *min,union pixelval *max,int nbins,int format); -int alloc_histobins(struct hips_histo *histo); -/******************* alloc_im.c ***********************/ -int alloc_image(struct header *hd); -int alloc_imagez(struct header *hd); -int free_image(struct header *hd); -/******************* cmapio.c ***********************/ -int readcmap(char *filename,int maxcount,int *count,unsigned char *r,unsigned char *g,unsigned char *b); -/******************* col1toco.c ***********************/ -int h_col1torgb(struct header *hdi,struct header *hdo,int fr); -int h_col1torgbz(struct header *hdi,struct header *hdo,int fr); -int h_col1tozrgb(struct header *hdi,struct header *hdo,int fr); -int h_col1tobgr(struct header *hdi,struct header *hdo,int fr); -int h_col1tobgrz(struct header *hdi,struct header *hdo,int fr); -int h_col1tozbgr(struct header *hdi,struct header *hdo,int fr); -int h_btorgb_1(struct header *hdi,struct header *hdo,int fr); -int h_itorgb_1(struct header *hdi,struct header *hdo,int fr); -int h_btorgbz_1(struct header *hdi,struct header *hdo,int fr); -int h_itorgbz_1(struct header *hdi,struct header *hdo,int fr); -int h_btozrgb_1(struct header *hdi,struct header *hdo,int fr); -int h_itozrgb_1(struct header *hdi,struct header *hdo,int fr); -int h_btobgr_1(struct header *hdi,struct header *hdo,int fr); -int h_itobgr_1(struct header *hdi,struct header *hdo,int fr); -int h_btobgrz_1(struct header *hdi,struct header *hdo,int fr); -int h_itobgrz_1(struct header *hdi,struct header *hdo,int fr); -int h_btozbgr_1(struct header *hdi,struct header *hdo,int fr); -int h_itozbgr_1(struct header *hdi,struct header *hdo,int fr); -int h_1to3_b(unsigned char *pi,unsigned char *po,int np); -int h_1to3_i(int *pi,unsigned char *po,int np); -int h_1to4_b(unsigned char *pi,unsigned char *po,int np); -int h_1to4_i(int *pi,unsigned char *po,int np); -/******************* col3tob.c ***********************/ -int h_col3tob(struct header *hdi,struct header *hdo,int fr); -int h_rgbtob_1(struct header *hdi,struct header *hdo,int fr); -int h_rgbztob_1(struct header *hdi,struct header *hdo,int fr); -int h_zrgbtob_1(struct header *hdi,struct header *hdo,int fr); -int h_bgrtob_1(struct header *hdi,struct header *hdo,int fr); -int h_bgrztob_1(struct header *hdi,struct header *hdo,int fr); -int h_zbgrtob_1(struct header *hdi,struct header *hdo,int fr); -int h_3to1_b(unsigned char *pi,unsigned char *po,int np); -int h_4to1_b(unsigned char *pi,unsigned char *po,int np); -/******************* col3toco.c ***********************/ -int h_torgb(struct header *hdi,struct header *hdo); -int h_torgbz(struct header *hdi,struct header *hdo); -int h_tozrgb(struct header *hdi,struct header *hdo); -int h_tobgr(struct header *hdi,struct header *hdo); -int h_tobgrz(struct header *hdi,struct header *hdo); -int h_tozbgr(struct header *hdi,struct header *hdo); -int h_rgbztorgb(struct header *hdi,struct header *hdo); -int h_zrgbtorgb(struct header *hdi,struct header *hdo); -int h_bgrtorgb(struct header *hdi,struct header *hdo); -int h_bgrztorgb(struct header *hdi,struct header *hdo); -int h_zbgrtorgb(struct header *hdi,struct header *hdo); -int h_rgbtorgbz(struct header *hdi,struct header *hdo); -int h_zrgbtorgbz(struct header *hdi,struct header *hdo); -int h_bgrtorgbz(struct header *hdi,struct header *hdo); -int h_bgrztorgbz(struct header *hdi,struct header *hdo); -int h_zbgrtorgbz(struct header *hdi,struct header *hdo); -int h_rgbtozrgb(struct header *hdi,struct header *hdo); -int h_rgbztozrgb(struct header *hdi,struct header *hdo); -int h_bgrtozrgb(struct header *hdi,struct header *hdo); -int h_bgrztozrgb(struct header *hdi,struct header *hdo); -int h_zbgrtozrgb(struct header *hdi,struct header *hdo); -int h_rgbtobgr(struct header *hdi,struct header *hdo); -int h_rgbztobgr(struct header *hdi,struct header *hdo); -int h_zrgbtobgr(struct header *hdi,struct header *hdo); -int h_bgrztobgr(struct header *hdi,struct header *hdo); -int h_zbgrtobgr(struct header *hdi,struct header *hdo); -int h_rgbtobgrz(struct header *hdi,struct header *hdo); -int h_rgbztobgrz(struct header *hdi,struct header *hdo); -int h_zrgbtobgrz(struct header *hdi,struct header *hdo); -int h_bgrtobgrz(struct header *hdi,struct header *hdo); -int h_zbgrtobgrz(struct header *hdi,struct header *hdo); -int h_rgbtozbgr(struct header *hdi,struct header *hdo); -int h_rgbztozbgr(struct header *hdi,struct header *hdo); -int h_zrgbtozbgr(struct header *hdi,struct header *hdo); -int h_bgrtozbgr(struct header *hdi,struct header *hdo); -int h_bgrztozbgr(struct header *hdi,struct header *hdo); -int h_30to3(struct header *hdi,struct header *hdo); -int h_03to3(struct header *hdi,struct header *hdo); -int h_3to3_flip(struct header *hdi,struct header *hdo); -int h_30to3_flip(struct header *hdi,struct header *hdo); -int h_03to3_flip(struct header *hdi,struct header *hdo); -int h_3to30(struct header *hdi,struct header *hdo); -int h_03to30(struct header *hdi,struct header *hdo); -int h_3to30_flip(struct header *hdi,struct header *hdo); -int h_30to30_flip(struct header *hdi,struct header *hdo); -int h_03to30_flip(struct header *hdi,struct header *hdo); -int h_3to03(struct header *hdi,struct header *hdo); -int h_30to03(struct header *hdi,struct header *hdo); -int h_3to03_flip(struct header *hdi,struct header *hdo); -int h_30to03_flip(struct header *hdi,struct header *hdo); -int h_03to03_flip(struct header *hdi,struct header *hdo); -/******************* col3toi.c ***********************/ -int h_col3toi(struct header *hdi,struct header *hdo,int fr); -int h_rgbtoi_1(struct header *hdi,struct header *hdo,int fr); -int h_rgbztoi_1(struct header *hdi,struct header *hdo,int fr); -int h_zrgbtoi_1(struct header *hdi,struct header *hdo,int fr); -int h_bgrtoi_1(struct header *hdi,struct header *hdo,int fr); -int h_bgrztoi_1(struct header *hdi,struct header *hdo,int fr); -int h_zbgrtoi_1(struct header *hdi,struct header *hdo,int fr); -int h_3to1_i(unsigned char *pi,int *po,int np); -int h_4to1_i(unsigned char *pi,int *po,int np); -/******************* conversi.c ***********************/ -int find_closest(struct header *hd,int *typeslist); -int ffind_closest(struct header *hd,int *typeslist,char *fname); -int pfind_closest(int pfmt,int *typeslist,char *fname); -int in_typeslist(int type,int *typeslist); -int find_method(int typein,int typeout); -int ffind_method(int typein,int typeout,char *fname); -int set_conversion(struct header *hd,struct header *hdp,int *typeslist); -int fset_conversion(struct header *hd,struct header *hdp,int *typeslist,char *fname); -int pset_conversion(struct header *hd,struct header *hdp,int ptype,char *fname); -int hconvert(struct header *hd,struct header *hdp,int method,int fr); -int fhconvert(struct header *hd,struct header *hdp,int method,int fr,char *fname); -int hconvertback(struct header *hd,struct header *hdp,int method,int fr); -int setupconvback(struct header *hd,struct header *hdp,struct header *hdcb); -int read_imagec(struct header *hd,struct header *hdp,int method,int fr); -int fread_imagec(FILE *fp,struct header *hd,struct header *hdp,int method,int fr,char *fname); -int write_imagec(struct header *hd,struct header *hdp,int method,int flag,int fr); -int fwrite_imagec(FILE *fp,struct header *hd,struct header *hdp,int method,int flag,int fr,char *fname); -/******************* cut_fram.c ***********************/ -int cut_frame(char *inbuf,int nbytes,char *outbuf,int limit,double x0,double y0,double xn,double yn); -/******************* desc_set.c ***********************/ -int desc_set(struct header *hd,char *s); -int desc_append(struct header *hd,char *s); -int desc_set2(struct header *hda,...); -int desc_append2(struct header *hda,...); -int desc_indentadd(struct header *hd,char *s); -/******************* dup_head.c ***********************/ -int dup_header(struct header *hd1,struct header *hd2); -int dup_headern(struct header *hd1,struct header *hd2); -/******************* formathe.c ***********************/ -char *formatheader(struct header *h); -char *formatheadera(struct header *h); -char *formatheaderc(struct header *h,int aflag); -int adddec(int i); -int addstr(char *s); -/******************* fread_ol.c ***********************/ -int fread_oldhdr(FILE *fp,struct header *hd,char *firsts,char *fname); -//int getline(FILE *fp,char **s ,int *l); -int swallownl(FILE *fp); -int hfgets(char *s,int n,FILE *fp); -/******************* free_hea.c ***********************/ -int free_header(struct header *hd); -int free_hdrcon(struct header *hd); -/******************* futils.c ***********************/ -FILE *ffopen(char *name,char *mode); -FILE *ffreopen(char *name,char *mode,FILE *stream1); -int ffread(char *ptr,int size,int nelem,FILE *stream); -int ffwrite(char *ptr,int size,int nelem,FILE *stream); -FILE *hfopenr(char *filename); -/******************* halloc.c ***********************/ -unsigned char *halloc(int i,int j); -unsigned char *hmalloc(unsigned long i); -char *memalloc(int nelem,unsigned long elsize); -/******************* hdepth.c ***********************/ -int hgetdepth(struct header *hd); -int hsetdepth(struct header *hd,int depth); -/******************* herrs.c ***********************/ -/******************* hformatn.c ***********************/ -char *hformatname(int pfmt); -char *hformatname_f(int pfmtf,int pfmtt); -char *hformatname_t(int pfmtf,int pfmtt); -/******************* hips_ext.c ***********************/ -/******************* hsizepix.c ***********************/ -unsigned long hsizepix(int pfmt); -unsigned long hbitsperpixel(int pfmt); -/******************* htypes.c ***********************/ -/******************* init_hea.c ***********************/ -int init_header(struct header *hd,char *onm,char *snm,int nfr,char *odt,int rw,int cl,int pfmt,int nc,char *desc); -int init_hdr_alloc(struct header *hd,char *onm,char *snm,int nfr,char *odt,int rw,int cl,int pfmt,int nc,char *desc); -int init_header_d(struct header *hd,char *onm,int onmd,char *snm,int snmd,int nfr,char *odt,int odtd,int rw,int cl,int pfmt,int nc,char *desc,int descd); -int init_hdr_alloc_d(struct header *hd,char *onm,int onmd,char *snm,int snmd,int nfr,char *odt,int odtd,int rw,int cl,int pfmt,int nc,char *desc,int descd); -/******************* maxforma.c ***********************/ -int hformatlevel(int pfmt); -int maxformat(int pfmt1,int pfmt2,int *typeslist,char *fname1,char *fname2); -/******************* pa_defau.c ***********************/ -int set_defaults(void); -int set_flag_defaults(void); -int set_filename_defaults(void); -/******************* pa_exter.c ***********************/ -/******************* pa_main.c ***********************/ -int parseargs(char *va_alist); -int parseargsu(char *va_alist); -/******************* pa_parse.c ***********************/ -int parse_command_line(int argc,char **argv ); -int accept_flag(int *arg_count,char ***arg_list ); -int accept_filter_flag(int *arg_count,char ***arg_list ,int *is_filter_flag); -int accept_filter_parameters(struct flag_key *flag_ptr,int *arg_count,char ***arg_list ); -int accept_parameter_value(union generic_ptr *parameter_ptr,int parameter_type,char *value,int *is_valid); -int accept_parameter_list(union generic_ptr *parameter_ptr,char ***arglist ,int *argcount,int *is_valid); -void disable_mutex_flags(char **flag_list ); -int accept_standard_flag(int *arg_count,char ***arg_list ,int *is_standard_flag); -int accept_filenames(int *arg_count,char ***arg_list ); -int accept_file_value(char **filename_ptr ,char *value,int *accept_stdin,int *is_valid_filename); -/******************* pa_table.c ***********************/ -int get_flag_data(char **varguments ); -int count_flags(struct flag_format *flag_list); -void add_flag_to_table(struct flag_format *flag_ptr,struct flag_key *table_ptr,char **varguments ); -struct flag_key *find_flag(char *value); -void unlock_all_flags(void); -void lock_flags(char **flag_list ); -void get_filename_data(char **varguments ); -/******************* pa_types.c ***********************/ -int isboolean(char *string); -int ischaracter(char *string); -int isstring(char *string); -int isinteger(char *string); -int isreal(char *string); -int isfilename(char *string); -int isflag(char *string); -/******************* pa_usage.c ***********************/ -void build_usage_message(void); -void add_group_to_usage(struct flag_key *flag_ptr); -void add_flag_to_usage(struct flag_format *flag_ptr,char *groupusage); -char *get_ptype_text(int ptype); -void add_filenames_to_usage(void); -void print_usage(void); -/******************* perr.c ***********************/ -int install_perr_printf(int (*new_printf)(const char *,...)); -int perr(int err,...); -/******************* pix_code.c ***********************/ -int pix_code(char *buf,int nbytes,unsigned char *pic,int rows,int nlp); -int codepoint(double b,double x,double y,unsigned char *pic,int rows,int nlp); -int codevec(double b,double x1,double y1,double x2,double y2,unsigned char *pic,int rows,int nlp); -int codeendp(double x,double y,unsigned char *pic,int rows,int nlp); -int fillvect(int ib,double fx0,double fy0,double fx1,double fy1,unsigned char *pic,int rows,int nlp); -/******************* pyralloc.c ***********************/ -#if 0 -int def_ipyr(struct IIMAGEtag *pyr,int lev,int nr,int nc); -int alloc_ipyr(struct IIMAGEtag *pyr,int botlev,int toplev); -int free_ipyr(struct IIMAGEtag *pyr,int botlev,int toplev); -int def_fpyr(struct FIMAGEtag *pyr,int lev,int nr,int nc); -int alloc_fpyr(struct FIMAGEtag *pyr,int botlev,int toplev); -int free_fpyr(struct FIMAGEtag *pyr,int botlev,int toplev); -int alloc_iimage(struct IIMAGEtag *img); -int free_iimage(struct IIMAGEtag img); -int free_fimage(struct FIMAGEtag img); -int alloc_fimage(struct FIMAGEtag *img); -#endif -int **_alloc_iimage(int nr,int nc) ; -float **_alloc_fimage(int nr,int nc) ; -int _free_iimage(int **img ); -int _free_fimage(float **img ); -/******************* pyrcopy.c ***********************/ -#if 0 -int copy_itoii(struct header *hd,struct IIMAGEtag img); -int copy_ftoff(struct header *hd,struct FIMAGEtag img); -#endif -/******************* pyrfilti.c ***********************/ -#if 0 -int getpyrfilters(char *filename,struct FILTERtag *rf,struct FILTERtag *ef); -int read_1dfilter(struct FILTERtag *f,FILE *stream,char *filename); -int default_1dfilter(struct FILTERtag *f); -#endif -/******************* pyrio.c ***********************/ -#if 0 -int read_iimage(FILE *stream,struct IIMAGEtag img,int fr,char *fname); -int read_fimage(FILE *stream,struct FIMAGEtag img,int fr,char *fname); -int write_iimage(FILE *stream,struct IIMAGEtag img,int fr); -int write_fimage(FILE *stream,struct FIMAGEtag img,int fr); -int read_ipyr(FILE *stream,struct IIMAGEtag *pyr,int botlev,int toplev,int fr,char *fname); -int read_fpyr(FILE *stream,struct FIMAGEtag *pyr,int botlev,int toplev,int fr,char *fname); -int write_ipyr(FILE *stream,struct IIMAGEtag *pyr,int botlev,int toplev,int fr); -int write_fpyr(FILE *stream,struct FIMAGEtag *pyr,int botlev,int toplev,int fr); -int _read_iimage(FILE *stream,int **img ,int nr,int nc,int fr,char *fname); -int _read_fimage(FILE *stream,float **img ,int nr,int nc,int fr,char *fname); -int _write_iimage(FILE *stream,int **p ,int nr,int nc,int fr); -int _write_fimage(FILE *stream,float **p ,int nr,int nc,int fr); -/******************* pyrnumpi.c ***********************/ -int pyrnumpix(int toplev,int nr,int nc); -/******************* pyrredex.c ***********************/ -int freduce(struct FIMAGEtag *pyr,int botlev,int toplev,struct FILTERtag rf,int rtype); -int fexpand(struct FIMAGEtag *pyr,int botlev,int toplev,struct FILTERtag ef,int mode,int rtype); -int _freduce_odd(struct FIMAGEtag in,struct FIMAGEtag out,struct FILTERtag rf,int rtype); -int _fexpand_odd(struct FIMAGEtag in,struct FIMAGEtag out,struct FILTERtag ef,int mode,int rtype); -int ireduce(struct IIMAGEtag *pyr,int botlev,int toplev,struct FILTERtag rf,int rtype); -int iexpand(struct IIMAGEtag *pyr,int botlev,int toplev,struct FILTERtag ef,int mode,int rtype); -int _ireduce_odd(struct IIMAGEtag in,struct IIMAGEtag out,struct FILTERtag rf,int rtype); -int _iexpand_odd(struct IIMAGEtag in,struct IIMAGEtag out,struct FILTERtag ef,int mode,int rtype); -/******************* pyrrefle.c ***********************/ -int hor_reflectf(struct FIMAGEtag h,int border,int rtype); -int ver_reflectf(struct FIMAGEtag v,int border,int rtype); -int reflectf(struct FIMAGEtag image,int border,int rtype); -int hor_reflecti(struct IIMAGEtag h,int border,int rtype); -int ver_reflecti(struct IIMAGEtag v,int border,int rtype); -int reflecti(struct IIMAGEtag image,int border,int rtype); -#endif -/******************* read_fra.c ***********************/ -int read_frame(FILE *fp,char *buf,int buf_limit,int *flags,double *shift_vector,double (*rot_matrix)[3],int fr,char *fname); -/******************* read_hea.c ***********************/ -int read_header(struct header *hd); -int fread_header(FILE *fp,struct header *hd,const char *fname); -/******************* read_his.c ***********************/ -int read_histo(struct hips_histo *histo,int fr); -int fread_histo(FILE *fp,struct hips_histo *histo,int fr,char *fname); -int hdr_to_histo(struct header *hd,struct hips_histo *histo); -/******************* read_hut.c ***********************/ -int read_hdr_a(struct header *hd); -int fread_hdr_a(FILE *fp,struct header *hd,char *fname); -int read_hdr_cpf(struct header *hd,int *typelist); -int fread_hdr_cpf(FILE *fp,struct header *hd,int *typelist,char *fname); -int read_hdr_cpfa(struct header *hd,int *typelist); -int fread_hdr_cpfa(FILE *fp,struct header *hd,int *typelist,char *fname); -int fread_hdr_cpfac(FILE *fp,struct header *hd,int *typelist,char *fname,int flagc,int flaga); -int read_hdr_cc(struct header *hd,struct header *chd,int mask); -int fread_hdr_cc(FILE *fp,struct header *hd,struct header *chd,int mask,char *fname); -int read_hdr_cca(struct header *hd,struct header *chd,int mask); -int fread_hdr_cca(FILE *fp,struct header *hd,struct header *chd,int mask,char *fname); -int fread_hdr_ccac(FILE *fp,struct header *hd,struct header *chd,int mask,char *fname,int flaga); -/******************* read_ima.c ***********************/ -int read_image(struct header *hd,int fr); -int fread_image(FILE *fp,struct header *hd,int fr,const char *fname); -/******************* read_roi.c ***********************/ -int read_roi(struct header *hd,int fr); -int fread_roi(FILE *fp,struct header *hd,int fr,const char *fname); -/******************* rgb.c ***********************/ -int h_btorgb(struct header *hdr,struct header *hdg,struct header *hdb,struct header *hdo); -int h_btorgbz(struct header *hdr,struct header *hdg,struct header *hdb,struct header *hdo); -int h_rgbtob(struct header *hdi,struct header *hdr,struct header *hdg,struct header *hdb); -int h_rgbztob(struct header *hdi,struct header *hdr,struct header *hdg,struct header *hdb); -int h_rgbtob2(struct header *hdi,struct header *hdo,char *color); -int h_rgbztob2(struct header *hdi,struct header *hdo,char *color); -/******************* setforma.c ***********************/ -int setformat(struct header *hd,int pfmt); -int setpyrformat(struct header *hd,int pfmt,int toplev); -/******************* setroi.c ***********************/ -int setroi(struct header *hd,int fr,int fc,int nr,int nc); -int setroi2(struct header *hd,struct hips_roi *roi); -int getroi(struct header *hd,struct hips_roi *roi); -int clearroi(struct header *hd); -/******************* setsize.c ***********************/ -int setsize(struct header *hd,int r,int c); -/******************* strsave.c ***********************/ -char *strsave(char *s); -/******************* tob.c ***********************/ -int h_tob(struct header *hdi,struct header *hdo); -int h_mptob(struct header *hdi,struct header *hdo); -int h_lptob(struct header *hdi,struct header *hdo); -int h_stob(struct header *hdi,struct header *hdo); -int h_itob(struct header *hdi,struct header *hdo); -int h_ftob(struct header *hdi,struct header *hdo); -/******************* toc.c ***********************/ -int h_toc(struct header *hdi,struct header *hdo); -int h_itoc(struct header *hdi,struct header *hdo); -int h_ftoc(struct header *hdi,struct header *hdo); -int h_dtoc(struct header *hdi,struct header *hdo); -int h_dctoc(struct header *hdi,struct header *hdo); -/******************* tod.c ***********************/ -int h_tod(struct header *hdi,struct header *hdo); -int h_itod(struct header *hdi,struct header *hdo); -int h_ftod(struct header *hdi,struct header *hdo); -int h_ctod(struct header *hdi,struct header *hdo); -int h_dctod(struct header *hdi,struct header *hdo); -/******************* todc.c ***********************/ -int h_todc(struct header *hdi,struct header *hdo); -int h_itodc(struct header *hdi,struct header *hdo); -int h_ftodc(struct header *hdi,struct header *hdo); -int h_dtodc(struct header *hdi,struct header *hdo); -int h_ctodc(struct header *hdi,struct header *hdo); -/******************* tof.c ***********************/ -int h_tof(struct header *hdi,struct header *hdo); -int h_btof(struct header *hdi,struct header *hdo); -int h_stof(struct header *hdi,struct header *hdo); -int h_itof(struct header *hdi,struct header *hdo); -int h_dtof(struct header *hdi,struct header *hdo); -int h_ctof(struct header *hdi,struct header *hdo); -int h_dctof(struct header *hdi,struct header *hdo); -/******************* toi.c ***********************/ -int h_toi(struct header *hdi,struct header *hdo); -int h_mptoi(struct header *hdi,struct header *hdo); -int h_lptoi(struct header *hdi,struct header *hdo); -int h_btoi(struct header *hdi,struct header *hdo); -int h_sbtoi(struct header *hdi,struct header *hdo); -int h_ustoi(struct header *hdi,struct header *hdo); -int h_stoi(struct header *hdi,struct header *hdo); -int h_uitoi(struct header *hdi,struct header *hdo); -int h_ftoi(struct header *hdi,struct header *hdo); -int h_dtoi(struct header *hdi,struct header *hdo); -int h_ctoi(struct header *hdi,struct header *hdo); -int h_dctoi(struct header *hdi,struct header *hdo); -/******************* tolp.c ***********************/ -int h_tolp(struct header *hdi,struct header *hdo); -int h_btolp(struct header *hdi,struct header *hdo); -int h_itolp(struct header *hdi,struct header *hdo); -/******************* tomp.c ***********************/ -int h_tomp(struct header *hdi,struct header *hdo); -int h_btomp(struct header *hdi,struct header *hdo); -int h_itomp(struct header *hdi,struct header *hdo); -/******************* tos.c ***********************/ -int h_tos(struct header *hdi,struct header *hdo); -int h_btos(struct header *hdi,struct header *hdo); -int h_sbtos(struct header *hdi,struct header *hdo); -int h_itos(struct header *hdi,struct header *hdo); -int h_ftos(struct header *hdi,struct header *hdo); -/******************* tosb.c ***********************/ -int h_tosb(struct header *hdi,struct header *hdo); -int h_stosb(struct header *hdi,struct header *hdo); -int h_itosb(struct header *hdi,struct header *hdo); -/******************* toui.c ***********************/ -int h_toui(struct header *hdi,struct header *hdo); -int h_itoui(struct header *hdi,struct header *hdo); -/******************* tous.c ***********************/ -int h_tous(struct header *hdi,struct header *hdo); -int h_itous(struct header *hdi,struct header *hdo); -/******************* type_is_.c ***********************/ -int type_is_col3(struct header *hd); -int ptype_is_col3(int pfmt); -/******************* update_h.c ***********************/ -int update_header(struct header *hd,int argc,char **argv ); -int update_headern(struct header *hd,int argc,char **argv ); -int update_headerc(struct header *hd,int argc,char **argv ,int pflag); -/******************* view_fra.c ***********************/ -int view_frame(char *inbuf,int nbytes,char *outbuf,int limit,double dist); -/******************* write_fr.c ***********************/ -int write_frame(FILE *fp,char *buf,int nbytes,double *shift_v,double (*rot_m)[3],int fr); -/******************* write_he.c ***********************/ -int write_headeru(struct header *hd,int argc,char **argv ); -int write_headeru2(struct header *hd,struct header *hdp,int argc,char **argv ,int flag); -int write_headerun(struct header *hd,int argc,char **argv ); -int write_header(struct header *hd); -int fwrite_header(FILE *fp,struct header *hd,const char *fname); -/******************* write_hi.c ***********************/ -int write_histo(struct hips_histo *histo,int fr); -int fwrite_histo(FILE *fp,struct hips_histo *histo,int fr,char *fname); -int histo_to_hdr(struct header *hd,struct hips_histo *histo); -/******************* write_im.c ***********************/ -int write_image(struct header *hd,int fr); -int fwrite_image(FILE *fp,struct header *hd,int fr,const char *fname); -/******************* write_ro.c ***********************/ -int write_roi(struct header *hd,int fr); -int fwrite_roi(FILE *fp,struct header *hd,int fr,char *fname); -/******************* wsubs.c ***********************/ -int wnocr(FILE *fp,char *s); -int dfprintf(FILE *fp,int i,char *fname); -/******************* xparam.c ***********************/ -int setparam(struct header *hda,...); -int setparamd(struct header *hda,...); -int getparam(struct header *hda,...); -int clearparam(struct header *hd,char *name); -struct extpar *findparam(struct header *hd,char *name); -int checkname(char *name); -int mergeparam(struct header *hd1,struct header *hd2); -struct extpar *grepparam(struct header *hd,char *name); -char *strstr1(char *s1,char *s2); diff --git a/include/histo.h b/include/histo.h index 1bd567fee72..854d9a8fb84 100644 --- a/include/histo.h +++ b/include/histo.h @@ -89,7 +89,7 @@ int HISTOcountPeaksInRegion(HISTOGRAM *h, int wsize, float min_pct, int HISTOfindFirstPeakInRegion(HISTOGRAM *h, int wsize, float min_pct, int b0, int b1) ; int HISTOfindHighestPeakInRegion(HISTOGRAM *h, int b0, int b1); -int HISTOplot(HISTOGRAM *histo, char *fname) ; +int HISTOplot(HISTOGRAM *histo, const char *fname) ; int HISTOaddFractionalSample(HISTOGRAM *histo, float val, float bmin, float bmax, float frac); int HISTOaddSample(HISTOGRAM *histo, float val, float bmin, float bmax) ; int HISTOfindCurrentPeak(HISTOGRAM *histo, @@ -185,7 +185,7 @@ HISTOGRAM2D *HISTO2DsmoothBins2(HISTOGRAM2D *histo_src, HISTOGRAM2D *histo_dst,f HISTOGRAM2D *HISTO2Dread(char *fname) ; HISTOGRAM2D *HISTO2DsoapBubbleZeros(HISTOGRAM2D *hsrc, HISTOGRAM2D *hdst, int niters) ; float HISTOcomputeFWHM(HISTOGRAM *h, int peak) ; -int HISTOwriteTxt(HISTOGRAM *histo, char *fname) ; +int HISTOwriteTxt(HISTOGRAM *histo, const char *fname) ; int HISTOsumNorm(HISTOGRAM *histo); HISTOGRAM *HISTOcumsum(HISTOGRAM *h, HISTOGRAM *hout); diff --git a/include/image.h b/include/image.h index 9a7e1e76367..0d7e7c423d3 100644 --- a/include/image.h +++ b/include/image.h @@ -33,7 +33,7 @@ #define UCHAR unsigned char #endif -#include "hipl_format.h" +#include "hips.h" typedef struct header IMAGE ; @@ -253,6 +253,11 @@ IMAGE *ImageDownsample2Horizontal(IMAGE *Isrc, IMAGE *Idst) ; IMAGE *ImageDownsample2(IMAGE *Isrc, IMAGE *Idst) ; IMAGE *ImageUpsample2(IMAGE *Isrc, IMAGE *Idst) ; +// hips functions +int init_header(IMAGE *I,char *onm,char *snm,int nfr,char *odt,int rw,int cl,int pfmt,int nc,const char *desc); +int h_copy(IMAGE *Isrc, IMAGE *Idst); +int free_header(IMAGE *I); + /* constants which specify the morphological operation carried out by ImageMorph routine. diff --git a/include/imautils.h b/include/imautils.h index a420c5748a0..7bc8df55f67 100644 --- a/include/imautils.h +++ b/include/imautils.h @@ -83,9 +83,9 @@ IMAFILEINFO; /*******************************************/ typedef struct { - char *key; + const char *key; int offset; - char *typestring; + const char *typestring; int type; int typesize; int nitems; @@ -95,7 +95,7 @@ IMA_DICTIONARY_ENTRY; extern IMA_DICTIONARY_ENTRY ImaDictionary[NMAX_IMA_DICTIONARY]; extern int nImaDictionary, ImaDictionaryGood; -extern char *imaTypeString[6]; +extern const char *imaTypeString[6]; extern int imaTypeSize[6]; int imaTypeFromString(const char *typestring); diff --git a/include/inverse.h b/include/inverse.h deleted file mode 100644 index ec8fa67c611..00000000000 --- a/include/inverse.h +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file inverse.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef INVERSE_H -#define INVERSE_H - -#include "matrix.h" -#include "rec.h" - -typedef struct -{ - int version ; - int neeg_channels ; - int nmeg_channels ; - int nchan ; /* sum of the previous two */ - int ndipoles_per_location ; /* 1 for orientation, 3 otherwise */ - int ndipoles ; /* # of dipole locations */ - int ndipole_files ; - float pthresh ; /*threshold that was used to generate priors*/ - int *dipole_vertices ; /* vertex numbers where dipoles are situated*/ - VECTOR *spatial_priors ; /* fMRI at the moment */ - int *bad_sensors ; - VECTOR *pvals ; /* statistics from fMRI */ - float *dipole_normalization ; - MATRIX *m_iop ; /* actual inverse operator */ - MATRIX *m_forward ; /* forward solution */ -} -INVERSE_OPERATOR, IOP ; - -IOP *IOPRead(char *fname, int hemi) ; -int IOPWrite(IOP *iop, char *fname) ; -int IOPFree(IOP **piop) ; -int IOPNormalize(IOP *iop) ; -MATRIX *IOPapplyInverseOperator(IOP *iop, REC *rec, MATRIX *m_sol) ; - - -#define INVERSE_RH 1 -#define INVERSE_LH 2 - -#endif diff --git a/include/iutils.h b/include/iutils.h deleted file mode 100644 index 211be28f067..00000000000 --- a/include/iutils.h +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @file iutils.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef IUTILS_H -#define IUTILS_H - -#if 1 -/* - these prototypes cause the canny edge detector to fail - I don't know why, - and I'm not going to spend the time to find out. -*/ -void crop_image(unsigned char *imageptr, int *cols,int *rows, int cropcornerax, - int cropcorneray, int cropcornerbx, int cropcornerby) ; -#endif -void get_histogram_threshold(int hgram[], int histsize, int pixelmax, - int pixelmin, float fraction, - int zflag, float *ht, float *lt) ; -void histogram(short *theimage, int xsize, int ysize, int pixelmax, - int pixelmin, int hgram[], int histsize) ; - -#endif diff --git a/include/json.hpp b/include/json.h similarity index 100% rename from include/json.hpp rename to include/json.h diff --git a/include/kinput.h b/include/kinput.h deleted file mode 100644 index 065f059ae0f..00000000000 --- a/include/kinput.h +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file kinput.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef KINPUT_H -#define KINPUT_H - -#include "image.h" - - -#define IN_SIZE 3 -#define NHALF_IN ((IN_SIZE-1)/2) -#define HALF_IN (IN_SIZE/2) -#define NPYR 2 -#define TROW 15 -#define TCOL 15 -#define MAX_SCALES 8 -#define SIGMA_SCALE_FACTOR 1.5f - -#define USE_PYRAMID 0 - -/* this structure will be used to write data into a .bp file */ -typedef struct -{ - int nscales ; - int input_size ; - float sigmas[MAX_SCALES] ; - char pc_fname[75] ; - char coef_fname[75] ; - int abs_gradient ; - float sigma_scale_factor ; -} -KINPUT_PARMS ; - -typedef struct -{ -#if USE_PYRAMID - HIPSPyramid *xpyr ; - HIPSPyramid *ypyr ; - IMAGE *xImage ; - IMAGE *yImage ; -#else - IMAGE *xInputs ; /* sequence of nscales images */ - IMAGE *yInputs ; - IMAGE *gImages[MAX_SCALES] ; -#endif - float *inputs ; - int nscales ; - int ninputs ; - KINPUT_PARMS parms ; -} -KINPUT ; - - -KINPUT *KinputAlloc(int rows, int cols, int scales, int input_size, - float sigma, float sigma_scale_factor, int abs_gradient) ; -int KinputFree(KINPUT **pkinput) ; -int KinputInit(KINPUT *kinput, IMAGE *image) ; -int KinputVector(KINPUT *kinput, int x, int y) ; - - -#define SIGMA 0.5f - -#endif diff --git a/include/label.h b/include/label.h index 1531fc49656..a69bc010a0d 100644 --- a/include/label.h +++ b/include/label.h @@ -28,7 +28,7 @@ #ifndef LABEL_H #define LABEL_H -#include "minc_volume_io.h" +#include "minc.h" #include "matrix.h" #include "const.h" @@ -114,7 +114,7 @@ LABEL *LabelRemoveAlmostDuplicates(LABEL *area, double dist, LABEL *ldst); LABEL *LabelCompact(LABEL *lsrc, LABEL *ldst) ; int LabelRemoveDuplicates(LABEL *area) ; int LabelHasVertex(int vtxno, LABEL *lb); -LABEL *LabelAlloc(int max_points, char *subject_name, char *label_name) ; +LABEL *LabelAlloc(int max_points, const char *subject_name, const char *label_name) ; LABEL *LabelRealloc(LABEL *lb, int max_points); int LabelCurvFill(LABEL *area, int *vertex_list, int nvertices, int max_vertices, MRI_SURFACE *mris) ; diff --git a/include/ldtmplt.h b/include/ldtmplt.h deleted file mode 100644 index 2ba94efeb51..00000000000 --- a/include/ldtmplt.h +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @file ldtmplt.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -IMAGE *loadTemplates(int argc, char *argv[]) ; -IMAGE *loadTemplate(char *fname, IMAGE *Itemplates) ; diff --git a/include/log.h b/include/log.h new file mode 100644 index 00000000000..2d46cb86a6a --- /dev/null +++ b/include/log.h @@ -0,0 +1,71 @@ +#ifndef LOG_H +#define LOG_H + +#include + + +/// \class StreamLogger +/// +/// A stream-style logging object for printing status messages. +/// +/// In general, this class shouldn't used directly. Status messages should +/// be printed via the standard logging macros. For example: +/// +/// logWarning << "exceeded standard iteration count"; +/// logError << "vertex has no neighbors"; +/// logFatal(1) << "could not find file"; + +class StreamLogger { +public: + enum MessageStatus {Warning, Error, Debug}; + + StreamLogger(MessageStatus status) : status(status), exitout(false) {}; + StreamLogger(MessageStatus status, int exitcode) : status(status), retcode(exitcode), exitout(true) {}; + ~StreamLogger(); + + template + StreamLogger& operator << (const T& t) { + ss << t; + return *this; + } + + // for std::endl + StreamLogger& operator << (std::ostream&(*f)(std::ostream&)) { + f(ss); + return *this; + } + +private: + MessageStatus status; + int retcode; + bool exitout; + std::ostringstream ss; +}; + +// terminal output colors +namespace term { + const char* black(); + const char* red(); + const char* green(); + const char* yellow(); + const char* blue(); + const char* purple(); + const char* cyan(); + const char* light_gray(); + const char* white(); + const char* light_red(); + const char* dim(); + // formating + const char* bold(); + const char* underline(); + // reset + const char* reset(); +} + +// macros for easy logging of standard message types +#define logDebug StreamLogger(StreamLogger::Debug) +#define logWarning StreamLogger(StreamLogger::Warning) +#define logError StreamLogger(StreamLogger::Error) +#define logFatal(ret) StreamLogger(StreamLogger::Error, ret) + +#endif diff --git a/include/log.hpp b/include/log.hpp deleted file mode 100644 index 8066833b861..00000000000 --- a/include/log.hpp +++ /dev/null @@ -1,73 +0,0 @@ -// Note: this file contains code that was derived from the Loguru logging -// library (by Emil Ernerfeldt), which is developed in the public domain: -// https://github.com/emilk/loguru - -#ifndef LOG_HPP -#define LOG_HPP - -#include - - -namespace fs -{ - // message status types - enum MessageStatus {Debug, Warning, Error}; - - /// \class Logger - /// A stream-style logging object - class Logger - { - public: - Logger(MessageStatus status); - Logger(MessageStatus status, int exitcode); - ~Logger(); - - template - Logger& operator << (const T& t) { - ss << t; - return *this; - } - - // for std::endl - Logger& operator << (std::ostream&(*f)(std::ostream&)) { - f(ss); - return *this; - } - - private: - void print(std::string content); - MessageStatus msg_status; - int retcode; - bool exitout; - std::ostringstream ss; - }; - - // terminal output colors - namespace term - { - const char* black(); - const char* red(); - const char* green(); - const char* yellow(); - const char* blue(); - const char* purple(); - const char* cyan(); - const char* light_gray(); - const char* white(); - const char* light_red(); - const char* dim(); - // formating - const char* bold(); - const char* underline(); - // reset - const char* reset(); - } -} - -// macros for easy logging of standard message types -#define fs_debug fs::Logger(fs::Debug) -#define fs_warning fs::Logger(fs::Warning) -#define fs_error fs::Logger(fs::Error) -#define fs_fatal(ret) fs::Logger(fs::Error, ret) - -#endif diff --git a/include/lpafile.h b/include/lpafile.h deleted file mode 100644 index 544e1f8f4de..00000000000 --- a/include/lpafile.h +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @file lpafile.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef LPAFILE_H -#define LPAFILE_H - - -#define NPOINTS 4 - -typedef struct -{ - int xp[NPOINTS] ; /* x coordinates of corners */ - int yp[NPOINTS] ; /* y coordinates of corners */ - int xc ; /* x coordinate of centroid */ - int yc ; /* y coordinate of centroid */ - long fpos ; /* position in answer file */ -} -LP_BOX ; - -typedef struct -{ - char fname[100] ; /* name of the file */ - FILE *fp ; - char **filelist ; /* array of pointers */ - int nfiles ; /* size of filelist */ - LP_BOX *coords ; - int last_written ; /* index of last written lp_box */ - int current ; - int flush ; -} -LP_ANSWER_FILE, LPAF ; - -LPAF *LPAFcreate(char *out_fname, int argc, char *argv[]) ; -int LPAFwrite(LPAF *lpaf, int current) ; -int LPAFread(LPAF *lpaf, int current) ; -int LPAFset(LPAF *lpaf, int current, int *xp, int *yp, int xc, int yc) ; -int LPAFwriteImageAnswer(LPAF *lpaf, int current) ; -int LPAFresetImageAnswer(LPAF *lpaf, int current) ; -int LPAFreadImageAnswer(LPAF *lpaf, int current) ; - -#endif diff --git a/include/lut.hpp b/include/lut.h similarity index 95% rename from include/lut.hpp rename to include/lut.h index e1b753f0bd0..75ec4bc3657 100644 --- a/include/lut.hpp +++ b/include/lut.h @@ -1,5 +1,5 @@ -#ifndef LUT_HPP -#define LUT_HPP +#ifndef LUT_H +#define LUT_H #include #include diff --git a/include/mailbox.h b/include/mailbox.h deleted file mode 100644 index b22666d3fc8..00000000000 --- a/include/mailbox.h +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @file mailbox.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)mailbox.h 1.2 - 8/10/95 -*/ -/*------------------------------------------------------------------------ - File Name: mailbox.h - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: - -------------------------------------------------------------------------*/ -#ifndef MAILBOX_H -#define MAILBOX_H - -#include -#include -#include - -typedef struct -{ - int iMachineId ; /* machine ID of sender */ - int iTid ; /* thread ID of sender */ - struct timeb timePosted ; /* time message was posted */ - long lMsgId ; /* 4-character message ID */ - int iUsers ; /* # of users of this message */ - int iLen ; /* length of the data (excluding header) */ - void *pvData ; -} -MSG ; - -int MBinit(int size) ; -int MBprintf(long lMsgId, char *strFmt, ...) ; -int MBsend(long iMsgId, int iLen, void *pvData) ; -int MBreceive(long iMsgId, void (*func)(MSG *pmsg, void *parm), - int iTid, void *parm) ; -int MBinvoke(MSG *msg) ; - - -#endif diff --git a/include/map.h b/include/map.h deleted file mode 100644 index cd9ece0098a..00000000000 --- a/include/map.h +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @file map.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:09 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)map.h 1.2 - 8/10/95 -*/ -/*------------------------------------------------------------------------ - File Name: logmap.h - - Author: Bruce Fischl - - Created: Jan. 1993 - - Description: - -------------------------------------------------------------------------*/ - - -/*---------------------------------------------------------------------- - File Name: - - Author: - - Description: - -----------------------------------------------------------------------*/ - - -#ifndef MAP_H -#define MAP_H - - -#include "hips.h" -#include "macros.h" - -typedef struct -{ - int rows ; - int cols ; - UCHAR *image ; -} -CMAP ; - -typedef struct -{ - int rows ; - int cols ; - int *image ; -} -IMAP ; - -/* - this macro will alow access to the map cell at row,col. It - is only used for 2-D maps. 1-D maps just index directly. -*/ -#define MAPcell(m, x, y) (*((m)->image + ((y) * m->cols) + x)) - -void MapIHipsWrite(IMAP *map, char *fname) ; -void MapCHipsWrite(CMAP *map, char *fname) ; -CMAP *MapClone(CMAP *m) ; -void MapCopy(CMAP *mSrc, CMAP *mDst) ; -void MapAdd(CMAP *m1, CMAP *m2, CMAP *mSum) ; -IMAP *MapIAlloc(int cols, int rows) ; -CMAP *MapCAlloc(int cols, int rows) ; -void MapIFree(IMAP *map) ; -void MapCFree(CMAP *map) ; -void MapIHipsWrite(IMAP *map, char *fname) ; -void MapCHipsWrite(CMAP *map, char *fname) ; -void MapCShowImage(CMAP *map, char *name) ; -void MapIShowImage(IMAP *map, char *name) ; -void MapSoapBubbleRelax(IMAP *mVal, CMAP *mVisited) ; -void MapIPrint(IMAP *map, FILE *fp) ; -void MapCPrint(CMAP *map, FILE *fp) ; - - - -#endif diff --git a/include/matrix.h b/include/matrix.h index 4c6772a9124..2ca7052dde4 100644 --- a/include/matrix.h +++ b/include/matrix.h @@ -26,11 +26,6 @@ #ifndef MATRIX_H #define MATRIX_H -#if defined(__cplusplus) -extern "C" { -#endif - - #ifdef X #undef X #endif @@ -129,7 +124,7 @@ int MatrixPrint(FILE *fp, const MATRIX *mat) ; int MatrixPrintFmt(FILE *fp,const char *fmt, MATRIX *mat); int MatrixPrintOneLine(FILE *fp, MATRIX *mat) ; int MatrixPrintTranspose(FILE *fp, MATRIX *mat) ; -int MatrixPrintWithString(FILE *fp, MATRIX *m, char *Pre, char *Post); +int MatrixPrintWithString(FILE *fp, MATRIX *m, const char *Pre, const char *Post); MATRIX *MatrixTranspose(MATRIX *mIn, MATRIX *mOut) ; MATRIX *MatrixAdd( const MATRIX *m1, const MATRIX *m2, MATRIX *mOut) ; MATRIX *MatrixSubtract( const MATRIX *m1, const MATRIX *m2, MATRIX *mOut) ; @@ -358,10 +353,4 @@ MATRIX *MatrixColNullSpace(MATRIX *M, int *err); MATRIX *MatrixResidualForming(MATRIX *X, MATRIX *R); MATRIX *MatrixGlmFit(MATRIX *y, MATRIX *X, double *pRVar, MATRIX *beta); - -#if defined(__cplusplus) -}; -#endif - - #endif diff --git a/include/mgh_filter.h b/include/mgh_filter.h deleted file mode 100644 index 00de2220827..00000000000 --- a/include/mgh_filter.h +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @file mgh_filter.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef MGH_FILTER_H - -void bpfilter(FLOATTYPE **data,int nchan,int nsamp,float lo,float hi) ; - -#endif diff --git a/include/mgh_matrix.h b/include/mgh_matrix.h deleted file mode 100644 index 30491a28904..00000000000 --- a/include/mgh_matrix.h +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file mgh_matrix.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef MGH_MATRIX_H -#define MGH_MATRIX_H - -#define TINY 1.0e-20 - -#ifndef SQR -#define SQR(x) ((x)*(x)) -#endif - -FLOATTYPE* MGH_vector(int n); -int* MGH_ivector(int n); -FLOATTYPE ** MGH_matrix(int n,int m); -void print_matrix(FLOATTYPE **a,int m,int n); -void read_matrix(FILE *fptr,FLOATTYPE **a,int m,int n); -void print_vector(FLOATTYPE *v,int n); -void row_vector(FLOATTYPE **a,FLOATTYPE *v,int i,int n); -void vector_to_matrix(FLOATTYPE *v,FLOATTYPE **a,int m,int n); -void scale_matrix(FLOATTYPE **a,FLOATTYPE s,int n,int m); -void normalize_matrix(FLOATTYPE **a,int n,int m); -void matrix_copy(FLOATTYPE **a,FLOATTYPE **b,int n,int m); -void matrix_copy2(FLOATTYPE **a,FLOATTYPE **b,int n,int m,int sno,int smo, - int tno,int tmo); -void matrix_transpose(FLOATTYPE **a,FLOATTYPE **at,int n,int m); -void matrix_add(FLOATTYPE **a,FLOATTYPE **b,FLOATTYPE **c, int n,int m); -void matrix_multiply(FLOATTYPE **a,FLOATTYPE **b,FLOATTYPE **c,int n,int m); -void matrix_multiply2(FLOATTYPE **a,FLOATTYPE **b,FLOATTYPE **c,int n,int m, - int l); -void matrix_angles(FLOATTYPE **a,FLOATTYPE **b,FLOATTYPE **c,int n,int m); -void vector_subtract(FLOATTYPE *a,FLOATTYPE *b,FLOATTYPE *c,int n); -void vector_add(FLOATTYPE *a,FLOATTYPE *b,FLOATTYPE *c,FLOATTYPE fa, - FLOATTYPE fb,int n); -void vector_multiply(FLOATTYPE **a,FLOATTYPE *b,FLOATTYPE *c,int n,int m); -void derivative_matrix(FLOATTYPE **D,int dy,int dx); -void MGH_identity_matrix(FLOATTYPE **I,int n); -void regularization_matrix(FLOATTYPE **R,int n); -void covariance_matrix(FLOATTYPE **R,int n); -void MGH_nrerror(char *s); -void mgh_ludcmp(FLOATTYPE **a,int n,int *indx,FLOATTYPE *d); -void mgh_lubksb(FLOATTYPE **a,int n,int *indx,FLOATTYPE *b); -void inverse(FLOATTYPE **a,FLOATTYPE **y,int n); -FLOATTYPE determinant(FLOATTYPE **a,int n); -FLOATTYPE MGH_svd(FLOATTYPE **A,FLOATTYPE **V,FLOATTYPE *z,int m,int n); -void mgh_svdcmp(FLOATTYPE **a,FLOATTYPE *w,FLOATTYPE **v,int m,int n); - - -#endif diff --git a/include/mincutils.h b/include/mincutils.h deleted file mode 100644 index a1d09498936..00000000000 --- a/include/mincutils.h +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @file mincutils.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef MINCUTILS_H -#define MINCUTILS_H - -#include -#include "mri.h" - -/*-----------------------------------------------------*/ -typedef struct -{ - int VoxAxisId; /* 0, 1, 2 */ - char *VoxAxisName; /* col, row, slice */ - int MINCAxisId; /* 0, 1 2 */ - char *MINCAxisName; /* xspace, yspace, zspace */ - int Len; /* Length of axis */ - float Res; /* Resolution */ - float DirCos[3]; /* Direction Cosine*/ -} -MINCAXIS; - -/*-----------------------------------------------------*/ -typedef struct -{ - int VoxAxisStorageOrder[3]; - float VolCenterVox[3]; - float VolCenterWorld[3]; - MINCAXIS Axis[3]; -} -MINCAXES; - -/*-----------------------------------------------------*/ -int DumpMINCAxes(FILE *fp, MINCAXES *MA); -MINCAXES *ConfigMINCAxes(MRI *mri); -int NameMINCAxes(MINCAXES *MA); -int MINCAxesStorageOrder(MINCAXES *MA); - - - - - - - - - - - - - - - -#endif /* #ifndef MINCUTILS_H */ diff --git a/include/minmaxrc.h b/include/minmaxrc.h deleted file mode 100644 index 052e748b1ab..00000000000 --- a/include/minmaxrc.h +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @file minmaxrc.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/************************************************************** - * Name: minmaxrc.h - * Author: Douglas N. Greve, 5/14/96 - * Purpose: hips-based routines to find the minimum and maximum - * pixel values in an image as well as their row and - * column. - ***************************************************************/ -#ifndef MINMAXRC_INC -#define MINMAXRC_INC -int h_minmaxrc(struct header *phdSrc, - Pixelval *Min, int MinPoint[2], - Pixelval *Max, int MaxPoint[2]); -int h_minmaxrc_b(struct header *phdSrc, - byte *Min, int MinPoint[2], - byte *Max, int MaxPoint[2]); -int h_minmaxrc_s(struct header *phdSrc, - short *Min, int MinPoint[2], - short *Max, int MaxPoint[2]); -int h_minmaxrc_i(struct header *phdSrc, - int *Min, int MinPoint[2], - int *Max, int MaxPoint[2]); -int h_minmaxrc_f(struct header *phdSrc, - float *Min, int MinPoint[2], - float *Max, int MaxPoint[2]); -#endif /* from #ifndef MINMAXRC_INC */ diff --git a/include/mri.h b/include/mri.h index 735c2998548..6fa48430632 100644 --- a/include/mri.h +++ b/include/mri.h @@ -28,11 +28,7 @@ #include "faster_variants.h" -#if defined(__cplusplus) -extern "C" { -#endif - -#include "minc_volume_io.h" +#include "minc.h" #include "const.h" #include "matrix.h" #include "dmatrix.h" @@ -358,8 +354,8 @@ double MRIptr2dbl(void *pmric, int mritype); size_t MRIsizeof(int mritype); -char * MRIprecisionString(int PrecisionCode); -int MRIprecisionCode(char *PrecisionString); +const char * MRIprecisionString(int PrecisionCode); +int MRIprecisionCode(const char *PrecisionString); MRI *MRImakeMosaic(MRI **mri, int nimages, int rectify) ; @@ -474,8 +470,8 @@ MRI *MRIapplyRASlinearTransformInterp(MRI *mri_src, MRI *mri_dst, MRI *MRIapplyRASinverseLinearTransformInterp(MRI *mri_src, MRI *mri_dst, MATRIX *mA, int interpMethod) ; -int MRIinterpCode(char *InterpString); -char * MRIinterpString(int InterpCode); +int MRIinterpCode(const char *InterpString); +const char * MRIinterpString(int InterpCode); MRI *MRIinterpolate(MRI *mri_src, MRI *mri_dst) ; MRI *MRIconfThresh(MRI *mri_src, MRI *mri_probs, MRI *mri_classes, MRI *mri_dst,float thresh, int min_target,int max_target); @@ -1277,7 +1273,7 @@ MRI *MRIsoapBubbleLabel(MRI *mri_src, MRI *mri_label, MRI *mri_dst, int niter); MRI *MRIsetLabelValues(MRI *mri_src, MRI *mri_label, MRI *mri_dst, int label, float val); -int MRIwriteImageViews(MRI *mri, char *base_name, int target_size) ; +int MRIwriteImageViews(MRI *mri, const char *base_name, int target_size) ; int MRIsetValues(MRI *mri, float val) ; int MRIsetFrameValues(MRI *mri, int frame, float val) ; MRI *MRIwindow(MRI *mri_src, MRI *mri_dst, int which, float x0, float y0, @@ -1492,8 +1488,8 @@ extern int MRIIO_Strip_Pound; float MRIfovCol(MRI *mri); int MRIdircosToOrientationString(MRI *mri, char *ostr); -int MRIorientationStringToDircos(MRI *mri, char *ostr); -char *MRIcheckOrientationString(char *ostr); +int MRIorientationStringToDircos(MRI *mri, const char *ostr); +char *MRIcheckOrientationString(const char *ostr); char *MRIsliceDirectionName(MRI *mri); MRI *MRIreverseSliceOrder(MRI *invol, MRI *outvol); MRI *MRIconformSliceOrder(MRI *mri); @@ -1617,9 +1613,4 @@ MRI *MRIsolveLaplaceEquation(MRI *mri_interior, MRI *mri_seg, int source_label, int MRIsampleVolumeFrameMasked(const MRI *mri, const MRI *mri_mask, double x, double y, double z, const int frame, double *pval); -#if defined(__cplusplus) -}; -#endif - - #endif diff --git a/include/mri2.h b/include/mri2.h index ca018e991f4..904e005f878 100644 --- a/include/mri2.h +++ b/include/mri2.h @@ -31,10 +31,6 @@ #ifndef MRI2_H #define MRI2_H -#if defined(__cplusplus) -extern "C" { -#endif - #include "mri.h" #include "mriTransform.h" #include "mrisurf.h" @@ -44,7 +40,7 @@ MRI *mri_load_bvolume(char *bfstem); int mri_save_as_bvolume(MRI *vol, char *stem, int svendian, int svtype); MRI *mri_load_bvolume_frame(char *bfstem, int frameno); int mri_framepower(MRI *vol, float *framepower); -MRI *mri_binarize(MRI *vol, float thresh, char *tail, int invert, +MRI *mri_binarize(MRI *vol, float thresh, const char *tail, int invert, MRI *volbin, int *nover); MRI *mri_rescale(MRI *invol, float min, float max, MRI *outvol); int mri_save_as_cor(MRI *vol, char *cordir, int frame, int rescale); @@ -156,8 +152,4 @@ MRI *MRImergeSegs(MRI *seg, int *seglist, int nsegs, int NewSegId, MRI *newseg); MRI *MRImatchSegs(MRI *seg, int *seglist, int nsegs, int MaskId, MRI *mask); HISTOGRAM *HISTOseg(MRI *seg, int segid, MRI *vol, double bmin, double bmax, double bdelta); -#if defined(__cplusplus) -}; -#endif - #endif diff --git a/include/mriBSpline.h b/include/mriBSpline.h index 2cdc98a5e80..34e09632417 100644 --- a/include/mriBSpline.h +++ b/include/mriBSpline.h @@ -33,10 +33,6 @@ #ifndef MRIBSPLINE_H #define MRIBSPLINE_H -#if defined(__cplusplus) -extern "C" { -#endif - #include "mri.h" #include "transform.h" @@ -88,9 +84,4 @@ MRI *MRIdownsample2BSpline(const MRI* mri_src, MRI *mri_dst) ; /** Direct methods for upsample (based on simplified algorithm) */ MRI *MRIupsample2BSpline(const MRI* mri_src, MRI *mri_dst) ; - -#if defined(__cplusplus) -}; -#endif - #endif diff --git a/include/mriFunctionalDataAccess.h b/include/mriFunctionalDataAccess.h deleted file mode 100644 index 7c0227b6734..00000000000 --- a/include/mriFunctionalDataAccess.h +++ /dev/null @@ -1,661 +0,0 @@ -/** - * @file mriFunctionalDataAccess.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: fischl $ - * $Date: 2012/07/16 01:29:17 $ - * $Revision: 1.32 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef tkmFunctionalDataAccess_H -#define tkmFunctionalDataAccess_H - -#include "xTypes.h" -#include "xVoxel.h" -#include "xList.h" -#include "mriTransform.h" -#include "mriVolume.h" - -/* Enable this to turn macros on, see details below. */ -#define FUND_USE_MACROS - - -/* error constants. */ -typedef enum -{ - FunD_tErr_NoError = 0, - FunD_tErr_InvalidSignature, - FunD_tErr_InvalidPtr, - FunD_tErr_PathNotFound, - FunD_tErr_CouldntGuessStem, - FunD_tErr_DataNotFound, - FunD_tErr_HeaderNotFound, - FunD_tErr_CouldntAllocateVolume, - FunD_tErr_UnrecognizedHeaderFormat, - FunD_tErr_QuestionableHeaderFormat, - FunD_tErr_CouldntDetermineDataType, - FunD_tErr_CouldntAllocateStorage, - FunD_tErr_CouldntAllocateMRI, - FunD_tErr_CouldntAllocateMatrix, - FunD_tErr_CouldntReadMRI, - FunD_tErr_CouldntReadRegisterFile, - FunD_tErr_CouldntCalculateDeviations, - FunD_tErr_ErrorAccessingTransform, - FunD_tErr_InvalidParameter, - FunD_tErr_InvalidTimeResolution, - FunD_tErr_InvalidNumPreStimTimePoints, - FunD_tErr_InvalidFunctionalVoxel, - FunD_tErr_InvalidConditionIndex, - FunD_tErr_InvalidTimePoint, - FunD_tErr_CouldntTransformMask, - FunD_tErr_ErrorPerformingFDR, - FunD_tErr_InvalidErrorCode, - FunD_tErr_knNumErrorCodes -} FunD_tErr; - -typedef enum -{ - FunD_tDataType_Short, - FunD_tDataType_Float -} FunD_tDataType; - -/* This should be kept in sync with the SAMPLE_* constants in mri.h */ -typedef enum -{ - FunD_tSampleType_Nearest = 0, - FunD_tSampleType_Trilinear, - FunD_tSampleType_Sinc, - FunD_knNumSampleTypes -} FunD_tSampleType; - -/* methods of func idx conversion. this is the rounding method used to - get the functional index from an ras coord. */ -typedef enum -{ - FunD_tConversionMethod_FFF = 0, /* floor, floor, floor */ - FunD_tConversionMethod_Round, /* rint */ - FunD_tConversionMethod_FCF, /* floor, ceil, floor */ - FunD_knNumConversionMethods -} FunD_tConversionMethod; - -/* Methods of finding the registration. Specified in the New function. */ -typedef enum -{ - FunD_tRegistration_None = -1, - FunD_tRegistration_File = 0, - FunD_tRegistration_Find, - FunD_tRegistration_Identity, - FunD_tRegistration_NoneNeeded, - FunD_knNumRegistrationTypes -} FunD_tRegistrationType; - -#define FunD_ksConversionMethod_FFF "floor" -#define FunD_ksConversionMethod_Round "round" -#define FunD_ksConversionMethod_FCF "tkregister" - -#define FunD_kSignature 0xe871bc90 - -#define FunD_knPathLen 1024 - -#define FunD_knNumFrequencyBins 100 - -/* the volume struct. */ -typedef struct -{ - - long mSignature; - - char msFileName[FunD_knPathLen]; - char msRegistrationFileName[FunD_knPathLen]; - - /* Conversion method */ - FunD_tConversionMethod mConvMethod; - - /* How to intrepret additional frames of data (see below). */ - int mNumTimePoints; - int mNumConditions; - tBoolean mbNullConditionPresent; - - /* The data. */ - MRI* mpData; - - /* If we're scalar data, we don't use transformation objects. */ - tBoolean mbScalar; - - /* Sample type to use. */ - FunD_tSampleType mSampleType; - - float mMaxValue; - float mMinValue; - - /* Addtl meta data. */ - float mTimeResolution; /* Num seconds between time points. */ - int mNumPreStimTimePoints; /* Num of time points before stimuleus */ - char msSubjectName[1024]; - float mBrightnessScale; - float mRegistrationPixelSize; - float mRegistrationThickness; - - /* transformation objects. */ - mriTransformRef mIdxToIdxTransform; - mriTransformRef mOriginalIdxToIdxTransform; - - /* When we know we have error values present, these are used */ - tBoolean mbErrorDataPresent; - float** mCovMtx; /* [conditions-1*timepts][conditions-1*timepts] */ - - /* TODO: If the client tells us its bound size, we'll try making a - resampled volume in client space to speed up data access (avoids - coordinate conversion and bounds checking. */ - MRI* mpResampledData; - tBoolean mbHaveClientBounds; - int mClientXMin; - int mClientYMin; - int mClientZMin; - int mClientXMax; - int mClientYMax; - int mClientZMax; - - /* used to calculate quintiles */ - int* mFrequencies; - int mNumBins; - - /* temp storage in conversions */ - xVoxel mTmpVoxel1; - xVoxel mTmpVoxel2; - int mTmpFrame; - double mTmpReal; - -} -mriFunctionalData, *mriFunctionalDataRef; - -/* A note on the format of the data in the MRI struct: functional data - is probably of multiple frames. These frames are interpreted as - time points and conditions. - - Additionally, the MRI data could contain error data, which is an - additional frame of data for each condition, but only the first - number is valid in each condition. Additionally, the MRI has a set - of 'null data' and a sigma data at the first condition if error - data is present. - - Here is how it is ordered: - - - WITHOUT ERROR DATA - - condition - time point - frame of displayable data - - time - frame condition point type - 0 0 0 data - 1 0 1 data - 2 1 0 data - 3 1 1 data - - WITH ERROR DATA - - condition 0 - time point - null values (ignored) - sigma values - condition 1..n - time point - frame of displayable data - std dev (ignored) - - time - frame condition point type - 0 0 null (ignored) - 1 0 null (ignored) - 2 0 null (ignored) - 3 0 0 sigma - 4 0 1 sigma - 5 0 2 sigma - 6 1 0 data - 7 1 1 data - 8 1 2 data - 9 1 std dev (ignored) - 10 1 std dev (ignored) - 11 1 std dev (ignored) - 12 2 0 data - 13 2 1 data - 14 2 2 data - 15 2 std dev (ignored) - 16 2 std dev (ignored) - 17 2 std dev (ignored) - -*/ - - -/* Allocates and deletes volumes. Volumes can be interpreted as - anatomically-based volumes that are registered onto a real - anatomical volume, or as a scalar volume, with a list of indexed - values. isFileName should be something appropriate for - MRIread. iRegistrationType is one of the registration types, and is - used if the volume turns out to be anatomical. isRegistrationFile - is an optional registration file to be used if the registration - type is FunD_tRegistration_File. inScalarSize is a number of scalar - values; if specified (not -1), the size of the volumeis compared to - this number and if it matches, the volume will be treated as a - scalar value set, and registration will not be - use. iAnatomicalVolume is used if the registration type is - FunD_tRegistration_Identity to calculate an identity registration, - and can be NULL. */ - -FunD_tErr FunD_New ( mriFunctionalDataRef* opVolume, - char* isFileName, - FunD_tRegistrationType iRegistrationType, - char* isRegistrationFile, - int inScalarSize, - mriVolumeRef iAnatomicalVolume, - tBoolean ibIsLeftHemi) ; - -FunD_tErr FunD_Delete ( mriFunctionalDataRef* iopVolume ); - -/* Parse a stem header if available. */ -FunD_tErr FunD_FindAndParseStemHeader_ ( mriFunctionalDataRef this ); - -/* Get meta information from MRI data. */ -FunD_tErr FunD_GuessMetaInformation_ ( mriFunctionalDataRef this ); - -/* Reads the register.dat file, allocates and initializes matricies. */ -FunD_tErr FunD_ParseRegistrationAndInitMatricies_ ( mriFunctionalDataRef this, - FunD_tRegistrationType iType, - mriVolumeRef iAnatomicalVolume ); - -/* Restores registration matrix to original copy. */ -FunD_tErr FunD_RestoreRegistration ( mriFunctionalDataRef this ); - -/* Calcs the deviations. Needs sigma and CovMtx, should be done after - reading the header _and_ data files. Deviations are calced by - multplying sigma by the square root of the diagonal of the CovMtx, - then indexing in by time major (time,cond 0,0, 1,0, 2,0...) */ -FunD_tErr FunD_CalcDeviations_ ( mriFunctionalDataRef this ); - - -/* Sets the client information so that functional volume can use a - resampled volume of the data in client space. */ -FunD_tErr FunD_SetClientCoordBounds ( mriFunctionalDataRef this, - int inXMin, - int inYMin, - int inZMin, - int inXMax, - int inYMax, - int inZMax ); - -/* Sets the value conversion method for getting integer values. */ -FunD_tErr FunD_SetConversionMethod ( mriFunctionalDataRef this, - FunD_tConversionMethod iMethod ); - -/* Gets and sets the sample type for interpolating data. Only is - used with the GetSampledData function. */ -FunD_tErr FunD_GetSampleType ( mriFunctionalDataRef this, - FunD_tSampleType* oType ); - -FunD_tErr FunD_SetSampleType ( mriFunctionalDataRef this, - FunD_tSampleType iType ); - -/* Whether or not the volume is scalar and has been reshaped. */ -FunD_tErr FunD_IsScalar ( mriFunctionalDataRef this, - tBoolean* obScalar ); - -/* Use this if the coordinates in the client space are actually in - native tkRegRAS space (e.g. surface). This will set the A->RAS - matrix in the IdxToIdx transform to identity. */ -FunD_tErr FunD_ClientSpaceIsTkRegRAS ( mriFunctionalDataRef this ); - -/* Value accessors. */ -FunD_tErr FunD_GetData ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - int iTimePoint, - int iCondition, - float* oData ); -FunD_tErr FunD_GetSampledData ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - int iTimePoint, - int iCondition, - float* oData ); -FunD_tErr FunD_GetDataForAllTimePoints ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - int iCondition, - float* oaData ); - -FunD_tErr FunD_GetDeviation ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - int iCondition, - int iTimePoint, - float* oValue ); -FunD_tErr FunD_GetDeviationForAllTimePoints ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - int iCondition, - float* oaData ); - - -/* Smooths the data. */ -FunD_tErr FunD_Smooth ( mriFunctionalDataRef this, - int iTimePoint, - int iCondition, - float iSigma ); - -/* Normalizes the data over all time points. */ -FunD_tErr FunD_NormalizeOverAll ( mriFunctionalDataRef this ); - - -/* converts a time point index to a second based on the time - resolution and time resolution */ -FunD_tErr FunD_ConvertTimePointToSecond ( mriFunctionalDataRef this, - int iTimePoint, - float* oSecond ); -FunD_tErr FunD_ConvertSecondToTimePoint ( mriFunctionalDataRef this, - float iSecond, - int* oTimePoint ); - -/* setting these values changes the way time points are converted to - seconds. */ -FunD_tErr FunD_SetTimeResolution ( mriFunctionalDataRef this, - float inTimeRes ); -FunD_tErr FunD_SetNumPreStimTimePoints ( mriFunctionalDataRef this, - int inNumPoints ); - -/* accessors for volume information. */ -FunD_tErr FunD_GetSubjectName ( mriFunctionalDataRef this, - char* out ); -FunD_tErr FunD_GetNumTimePoints ( mriFunctionalDataRef this, - int* out ); -FunD_tErr FunD_GetNumConditions ( mriFunctionalDataRef this, - int* out ); -FunD_tErr FunD_GetTimeResolution ( mriFunctionalDataRef this, - float* out ); -FunD_tErr FunD_GetNumPreStimTimePoints ( mriFunctionalDataRef this, - int* out ); -FunD_tErr FunD_GetValueRange ( mriFunctionalDataRef this, - float* outMin, - float* outMax ); -FunD_tErr FunD_IsErrorDataPresent ( mriFunctionalDataRef this, - tBoolean* oPresent ); -/* Gets bounds in client coords. Ghis is actually a bounding box in - client space. If the functional data is oblique to the client, it - will have coords that arn't valid in functional space, but it is a - good place to start iterating for the in anatomical space. */ -FunD_tErr FunD_GetBoundsInClientSpace ( mriFunctionalDataRef this, - xVoxelRef outBeginCorner, - xVoxelRef outEndCorner ); - -/* Gets the value at a quintile. Assumes quintile is within 0-100. */ -FunD_tErr FunD_GetValueAtPercentile ( mriFunctionalDataRef this, - float inPercent, - float* outValue ); - - -/* Saves the registration to file, making a backup if it already - exists. */ -FunD_tErr FunD_SaveRegistration ( mriFunctionalDataRef this ); - -/* Sets registration to identity matrix. */ -FunD_tErr FunD_SetRegistrationToIdentity ( mriFunctionalDataRef this ); - -/* Applies a transformation to the registration, which can later be - saved out as a new registration. */ -FunD_tErr FunD_ApplyTransformToRegistration ( mriFunctionalDataRef this, - MATRIX* iTransform ); - -/* Geometric trasnformations on the registration. */ -FunD_tErr FunD_TranslateRegistration ( mriFunctionalDataRef this, - float ifDistance, - tAxis iAxis ); -FunD_tErr FunD_RotateRegistration ( mriFunctionalDataRef this, - float ifDegrees, - tAxis iAxis, - xVoxelRef iCenterFuncRAS ); -FunD_tErr FunD_ScaleRegistration ( mriFunctionalDataRef this, - float ifFactor, - tAxis iAxis ); - - -/* Get the FDR threshold for a frame. */ -FunD_tErr FunD_CalcFDRThreshold ( mriFunctionalDataRef this, - int iCondition, - int iTimePoint, - int iSign, - float iRate, - MRI* iMaskVolume, - float* oThresholdMin ); - -/* This function doesn't seem to work very well but is left here for - reference . */ -#if 0 -FunD_tErr FunD_GetPercentileOfValue ( mriFunctionalDataRef this, - float inValue, - float* outPercentile ); -#endif - - -/* internal functions */ - -/* If the dimensions of the data, multiplied, match the number of - values here, the data is reshaped into the x direction and treated - as a scalar volume with no transform. */ -FunD_tErr FunD_ReshapeIfScalar_ ( mriFunctionalDataRef this, - int inNumValues, - tBoolean* obReshaped, - tBoolean ibIsLeftHemisphere); - -/* Resamples the data into client space for fast lookup. */ -FunD_tErr FunD_ResampleData_ ( mriFunctionalDataRef this ); - -/* Calculate a histogram for the data, dividing it up into a number of - bins. Allocates internal memory. */ -FunD_tErr FunD_CalcFrequencies_ ( mriFunctionalDataRef this, - int inNumBins ); - -/* Converts between client and functional voxel coordinates. */ -/* NOTE: FunD_ConvertClientToFuncIdx_ is now a macro */ -void FunD_ConvertFuncIdxToClient_ ( mriFunctionalDataRef this, - xVoxelRef iFuncIdx, - xVoxelRef oClientVox ); -void FunD_ConvertClientToFuncRAS_ ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - xVoxelRef oFuncRAS ); - - -void FunD_GetSigma_ ( mriFunctionalDataRef this, - xVoxelRef iFuncIdx, - int iTimePoint, - float* oSigma ); - -#define FunD_GetSigmaFrameNumber(iTimePoint,oFrame) \ - if( this->mbErrorDataPresent ) { \ - *(oFrame) = this->mNumTimePoints + (iTimePoint); \ - } else { \ - *(oFrame) = 0 ; \ - } - - -/* Note that the functions in this section are implemented as - functions and macros. The functions are slower but safer, and the - macros are faster but don't make any checks. So you should test - with the functions and then build with the macros turned on. And - keep the macro and functions version synced in - development. _grin_ Turn the flag on at the top of this file. */ -#ifndef FUND_USE_MACROS - -void FunD_GetValue_ ( mriFunctionalDataRef this, - MRI* iData, - xVoxelRef iIdx, - int iCondition, - int iTimePoint, - float* oValue ); - -void FunD_GetSampledValue_ ( mriFunctionalDataRef this, - MRI* iData, - xVoxelRef iIdx, - int iCondition, - int iTimePoint, - float* oValue ); - -void FunD_SetValue_ ( mriFunctionalDataRef this, - MRI* iData, - xVoxelRef iIdx, - int iCondition, - int iTimePoint, - float oValue ); - -/* This converts to functional index and performs the proper rounding - on the result. */ -void FunD_ConvertClientToFuncIdx_ ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - xVoxelRef oFuncIdx ); -/* This converts to func idx with floating info intact. */ -void FunD_ConvertClientToFloatFuncIdx_ ( mriFunctionalDataRef this, - xVoxelRef iClientVox, - xVoxelRef oFuncIdx ); - -#define FunD_GetDataFrameNumber(iCondition,iTimePoint,oFrame) \ - if( this->mbErrorDataPresent ) { \ - *(oFrame) = ((iCondition) * 2 * this->mNumTimePoints) + (iTimePoint); \ - } else { \ - *(oFrame) = ((iCondition) * this->mNumTimePoints) + (iTimePoint); \ - } - - -#else /* FUND_USE_MACROS */ - - -#define FunD_GetDataFrameNumber(iCondition,iTimePoint,oFrame) \ - if( this->mbErrorDataPresent ) { \ - *(oFrame) = ((iCondition) * 2 * this->mNumTimePoints) + (iTimePoint); \ - } else { \ - *(oFrame) = ((iCondition) * this->mNumTimePoints) + (iTimePoint); \ - } - -#define FunD_GetValue_(this,iData,iIdx,inCondition,inTimePoint,oValue) \ - if( this->mbErrorDataPresent ) { \ - this->mTmpFrame = \ - ((inCondition) * 2 * this->mNumTimePoints) + (inTimePoint); \ - } else { \ - this->mTmpFrame = (inCondition * this->mNumTimePoints) + inTimePoint; \ - } \ - MRIsampleVolumeFrameType( (iData), \ - xVoxl_GetFloatX((iIdx)),\ - xVoxl_GetFloatY((iIdx)),\ - xVoxl_GetFloatZ((iIdx)),\ - this->mTmpFrame, \ - SAMPLE_NEAREST, \ - &this->mTmpReal ); \ - *(oValue) = this->mTmpReal; - -#define FunD_GetSampledValue_(this,iData,iIdx,inCondition,inTimePoint,oValue) \ - if( this->mbErrorDataPresent ) { \ - this->mTmpFrame = \ -((inCondition) * 2 * this->mNumTimePoints) + (inTimePoint); \ - } else { \ - this->mTmpFrame = (inCondition * this->mNumTimePoints) + inTimePoint; \ - } \ - MRIsampleVolumeFrameType( (iData), \ - xVoxl_GetFloatX((iIdx)),\ - xVoxl_GetFloatY((iIdx)),\ - xVoxl_GetFloatZ((iIdx)),\ - this->mTmpFrame, \ - (int)this->mSampleType, \ - &this->mTmpReal ); \ - *(oValue) = this->mTmpReal; - - -#define FunD_SetValue_(this,iData,iIdx,inCondition,inTimePoint,iValue) \ - if( this->mbErrorDataPresent ) { \ - this->mTmpFrame = \ -((inCondition) * 2 * this->mNumTimePoints) + (inTimePoint); \ - } else { \ - this->mTmpFrame = (inCondition * this->mNumTimePoints) + inTimePoint; \ - } \ - switch( iData->type ) { \ - case MRI_UCHAR: \ - MRIseq_vox( iData, (int)(iIdx)->mfX, (int)(iIdx)->mfY, \ - (int)(iIdx)->mfZ, this->mTmpFrame) = iValue; \ - break; \ - case MRI_INT: \ - MRIIseq_vox( iData, (int)(iIdx)->mfX, (int)(iIdx)->mfY, \ - (int)(iIdx)->mfZ, this->mTmpFrame) = iValue; \ - break; \ - case MRI_LONG: \ - MRILseq_vox( iData, (int)(iIdx)->mfX, (int)(iIdx)->mfY, \ - (int)(iIdx)->mfZ, this->mTmpFrame) = iValue; \ - break; \ - case MRI_FLOAT: \ - MRIFseq_vox( iData, (int)(iIdx)->mfX, (int)(iIdx)->mfY, \ - (int)(iIdx)->mfZ, this->mTmpFrame) = iValue; \ - break; \ - case MRI_SHORT: \ - MRISseq_vox( iData, (int)(iIdx)->mfX, (int)(iIdx)->mfY, \ - (int)(iIdx)->mfZ, this->mTmpFrame) = iValue; \ - break; \ - default: \ - break ; \ - } - - -#define FunD_ConvertClientToFuncIdx_(this,iClientVox,oFuncIdx) \ - \ - Trns_ConvertAtoB( this->mIdxToIdxTransform, \ - (iClientVox), &this->mTmpVoxel2 );\ - \ - switch( this->mConvMethod ) {\ - case FunD_tConversionMethod_FFF:\ - xVoxl_SetFloat( (oFuncIdx), \ - floor(xVoxl_GetFloatX(&this->mTmpVoxel2)),\ - floor(xVoxl_GetFloatY(&this->mTmpVoxel2)),\ - floor(xVoxl_GetFloatZ(&this->mTmpVoxel2)) );\ - break;\ - case FunD_tConversionMethod_Round:\ - xVoxl_SetFloat( (oFuncIdx), \ - rint(xVoxl_GetFloatX(&this->mTmpVoxel2)),\ - rint(xVoxl_GetFloatY(&this->mTmpVoxel2)),\ - rint(xVoxl_GetFloatZ(&this->mTmpVoxel2)) );\ - break;\ - case FunD_tConversionMethod_FCF:\ - xVoxl_SetFloat( (oFuncIdx), \ - floor(xVoxl_GetFloatX(&this->mTmpVoxel2)),\ - ceil(xVoxl_GetFloatY(&this->mTmpVoxel2)),\ - floor(xVoxl_GetFloatZ(&this->mTmpVoxel2)) );\ - break;\ - default:\ - break;\ - } - -#define FunD_ConvertClientToFloatFuncIdx_(this,iClientVox,oFuncIdx) \ - Trns_ConvertAtoB( this->mIdxToIdxTransform, \ - (iClientVox), (oFuncIdx) ); - -#endif - -FunD_tErr FunD_DebugPrint ( mriFunctionalDataRef this ); - -char* FunD_GetErrorString ( FunD_tErr inErr ); - -FunD_tErr FunD_Verify ( mriFunctionalDataRef this ); -FunD_tErr FunD_VerifyFuncIdx_ ( mriFunctionalDataRef this, - xVoxelRef iFuncIdx ); -FunD_tErr FunD_VerifyTimePoint ( mriFunctionalDataRef this, - int iTimePoint ); -FunD_tErr FunD_VerifyCondition ( mriFunctionalDataRef this, - int iCondition ); - -#endif diff --git a/include/mriHeadPointList.h b/include/mriHeadPointList.h deleted file mode 100644 index eb6a38f997e..00000000000 --- a/include/mriHeadPointList.h +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @file mriHeadPointList.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.7 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef mriHeadPointList_h -#define mriHeadPointList_h - -#include "mriTypes.h" -#include "xVoxel.h" -#include "mriTransform.h" - -typedef enum -{ - - HPtL_tErr_NoErr = 0, - HPtL_tErr_InvalidObject, - HPtL_tErr_InvalidParameter, - HPtL_tErr_InvalidSignature, - HPtL_tErr_AllocationFailed, - HPtL_tErr_ErrorOpeningHeadPointFile, - HPtL_tErr_ErrorParsingHeadPointFile, - HPtL_tErr_ErrorOpeningTransformFile, - HPtL_tErr_ErrorParsingTransformFile, - HPtL_tErr_ErrorCreatingTransform, - HPtL_tErr_ErrorAccessingClientTransform, - HPtL_tErr_ErrorAccessingTransform, - HPtL_tErr_LastPoint, - HPtL_tErr_InvalidErrorCode, - HPtL_knNumErrorCodes - -} HPtL_tErr; - -typedef enum -{ - - HPtL_tIterationPlane_X = 0, - HPtL_tIterationPlane_Y, - HPtL_tIterationPlane_Z, - HPtL_tIterationPlane_All, - HPtL_knNumIterationPlanes -} HPtL_tIterationPlane; - -typedef struct -{ - - char msLabel[256]; - int mnIndex; - xVoxel mPoint; /* original point */ - xVoxel mClientPoint; /* client space point */ - -} -HPtL_tHeadPoint, *HPtL_tHeadPointRef; - -#define HPtL_kSignature 0x009087fb - -typedef struct -{ - - long mSignature; - - /* source */ - char msPointFile[256]; - char msTransformFile[256]; - - /* points storage */ - HPtL_tHeadPoint* maPoints; - int mnNumPoints; - - /* transform. a is client, b is head point space. */ - mriTransformRef mTransform; - - /* iterator state */ - HPtL_tIterationPlane mIterPlane; /* in client space */ - float mfIterPlaneNumber; - float mfIterPlaneRange; - int mnCurPoint; - -} -mriHeadPointList, *mriHeadPointListRef; - -HPtL_tErr HPtL_New ( mriHeadPointListRef* oList, - char* isListName, - char* isTransformName, - MATRIX* iClientTransform ); -HPtL_tErr HPtL_Delete ( mriHeadPointListRef* opList ); - -HPtL_tErr HPtL_ReadHeadListFile_ ( mriHeadPointListRef this, - char* isListName ); -HPtL_tErr HPtL_CreateTransform_ ( mriHeadPointListRef this, - char* isTransformName, - MATRIX* iClientTransform ); - -HPtL_tErr HPtL_ConvertListToClientSpace_ ( mriHeadPointListRef this ); - -HPtL_tErr HPtL_WriteTransform ( mriHeadPointListRef this, - char* isDest ); -HPtL_tErr HPtL_WriteHeadPointFile ( mriHeadPointListRef this, - char* isDest ); - -HPtL_tErr HPtL_ResetIterator ( mriHeadPointListRef this, - HPtL_tIterationPlane iPlane, - float ifPlaneNumber, - float ifPlaneRange ); -HPtL_tErr HPtL_NextPoint ( mriHeadPointListRef this, - HPtL_tHeadPointRef* opPoint ); - -HPtL_tErr HPtL_FindNearestPoint ( mriHeadPointListRef this, - HPtL_tIterationPlane iPlane, - float ifPlaneRange, - xVoxelRef iWhere, - HPtL_tHeadPointRef* opPoint ); -HPtL_tErr HPtL_FindFlattenedNearestPoint ( mriHeadPointListRef this, - HPtL_tIterationPlane iPlane, - xVoxelRef iWhere, - HPtL_tHeadPointRef* opPoint ); - -HPtL_tErr HPtL_RestoreTransform ( mriHeadPointListRef this ); -HPtL_tErr HPtL_ApplyTransform ( mriHeadPointListRef this, - MATRIX* iTransform ); -HPtL_tErr HPtL_Translate ( mriHeadPointListRef this, - float ifDistance, - tAxis iAxis ); -HPtL_tErr HPtL_Rotate ( mriHeadPointListRef this, - float ifDegrees, - tAxis iAxis ); -HPtL_tErr HPtL_Scale ( mriHeadPointListRef this, - float ifFactor, - tAxis iAxis ); - -HPtL_tErr HPtL_AlignPointToClientVoxel ( mriHeadPointListRef this, - HPtL_tHeadPointRef iPoint, - xVoxelRef iClientVox ); - -HPtL_tErr HPtL_Verify ( mriHeadPointListRef this ); -char* HPtL_GetErrorString ( HPtL_tErr ieCode ); - -#endif diff --git a/include/mriROI.h b/include/mriROI.h deleted file mode 100644 index 8a0eb1bbc92..00000000000 --- a/include/mriROI.h +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @file mriROI.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef mriROI_h -#define mriROI_h - -#include "xTypes.h" -#include "xDebug.h" -#include "xVoxel.h" -#include "xList.h" - -typedef enum -{ - - ROI_tErr_NoErr = 0, - ROI_tErr_InvalidObject, - ROI_tErr_InvalidParameter, - ROI_tErr_InvalidSignature, - ROI_tErr_AllocationFailed, - ROI_tErr_ErrorAccessingList, - ROI_tErr_LastVoxel, - ROI_tErr_InvalidErrorCode, - ROI_knNumErrorCodes - -} ROI_tErr; - - -typedef enum -{ - - ROI_tIterationPlane_X = 0, - ROI_tIterationPlane_Y, - ROI_tIterationPlane_Z, - ROI_tIterationPlane_All, - ROI_knNumIterationPlanes -} ROI_tIterationPlane; - -/* voxel value pair */ -typedef struct -{ - xVoxel mVoxel; - float* mafValues; -} -ROI_tROIVoxel, *ROI_tROIVoxelRef; - -#define ROI_kSignature 0x01928374 - -typedef struct -{ - - long mSignature; - - /* list of ROI values */ - xListRef mVoxels; - - /* index and name of the ROI */ - int mnIndex; - char msName[256]; - - /* number of values per voxel and their labels */ - int mnNumValuesPerVoxel; - char** masValueLabels; - - /* iterator state */ - ROI_tIterationPlane mIterPlane; - float mfIterPlaneNumber; - float mfIterPlaneRange; - ROI_tROIVoxelRef mIterVoxel; - -} -mriROI, *mriROIRef; - - -ROI_tErr ROI_New ( mriROIRef* opROI, - int inIndex, - char* isName, - int inNumValuesPerVoxel, - char** iasValueLabels ); -ROI_tErr ROI_Delete ( mriROIRef* iopROI ); - -ROI_tErr ROI_AddVoxel ( mriROIRef this, - xVoxelRef iVoxel, - float* iafValues ); - -ROI_tErr ROI_GetIndex ( mriROIRef this, - int* onIndex ); -ROI_tErr ROI_GetName ( mriROIRef this, - char* osName ); - -ROI_tErr ROI_DebugPrint ( mriROIRef this ); - -ROI_tErr ROI_IsVoxelInROI ( mriROIRef this, - xVoxelRef iVoxel, - tBoolean* oIsInROI ); - -/* iterate thru points */ -ROI_tErr ROI_ResetIterator ( mriROIRef this, - ROI_tIterationPlane iPlane, - float ifPlaneNumber, - float ifPlaneRange ); -ROI_tErr ROI_NextVoxel ( mriROIRef this, - ROI_tROIVoxelRef* opPoint ); - -char* ROI_GetErrorString ( ROI_tErr ieCode ); -ROI_tErr ROI_Verify ( mriROIRef this ); - -#endif - - diff --git a/include/mriSurface.h b/include/mriSurface.h deleted file mode 100644 index 15a9e4bd9b8..00000000000 --- a/include/mriSurface.h +++ /dev/null @@ -1,279 +0,0 @@ -/** - * @file mriSurface.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.19 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef mriSurface_h -#define mriSurface_h - -#include "mriTypes.h" -#include "mrisurf.h" -#include "mriTransform.h" -#include "xVoxel.h" -#include "colortab.h" - -typedef enum -{ - - Surf_tErr_NoErr = 0, - Surf_tErr_InvalidObject, - Surf_tErr_InvalidParameter, - Surf_tErr_InvalidSignature, - Surf_tErr_AllocationFailed, - Surf_tErr_ErrorLoadingSurface, - Surf_tErr_ErrorLoadingVertexSet, - Surf_tErr_ErrorLoadingAnnotation, - Surf_tErr_ErrorAccesssingSurface, - Surf_tErr_LastFace, - Surf_tErr_LastVertex, - Surf_tErr_InvalidErrorCode, - Surf_knNumErrorCodes -} Surf_tErr; - -typedef enum -{ - - Surf_tOrientation_X = 0, - Surf_tOrientation_Y, - Surf_tOrientation_Z, - Surf_knNumOrientations -} Surf_tOrientation; - -typedef enum -{ - - Surf_tVertexSet_None = -1, - Surf_tVertexSet_Main = 0, - Surf_tVertexSet_Original, - Surf_tVertexSet_Pial, - Surf_knNumVertexSets -} Surf_tVertexSet; - -typedef enum -{ - - Surf_tValueSet_None = -1, - Surf_tValueSet_Val = 0, - - Surf_knNumValueSets -} Surf_tValueSet; - -#define Surf_kSignature 0x0934cba4 - -typedef struct -{ - - xVoxel mVoxel[Surf_knNumVertexSets][VERTICES_PER_FACE]; - int mnVertexIndex[Surf_knNumVertexSets][VERTICES_PER_FACE]; - -} -Surf_tFace, *Surf_tFaceRef; - -typedef struct -{ - - long mSignature; - - /* source file name */ - char* msFileName; - - /* surface object */ - MRIS* mSurface; - - /* face list */ - Surf_tFace* maFaces; - - /* for checking which faces to iterate over */ - float mfLongestEdge; - - /* transform object. a->b = client->surface space */ - mriTransformRef mTransform; - - /* load status */ - tBoolean mabVertexSetLoaded[ Surf_knNumVertexSets ]; - tBoolean mabVertexSetConverted[ Surf_knNumVertexSets ]; - - /* iterator state */ - Surf_tOrientation mIterOrientation; - float mfIterPlane; - int mnCurFace; - int mnCurVertex; - -} -mriSurface, *mriSurfaceRef; - -/* transformer should be a->b client->surface coordinate system */ -Surf_tErr Surf_New ( mriSurfaceRef* opSurface, - char* isFileName ); -Surf_tErr Surf_Delete ( mriSurfaceRef* iopSurface ); - -/* Set the transform and precalc all the vertex positions in client - space. */ -Surf_tErr Surf_SetTransform ( mriSurfaceRef this, - mriTransformRef iTransform ); - -/* ==================================================================== IO */ - -/* loads a vertex set. if Main, will reload the entire MRIS. if original - or pial, will just shift out the vertex sets */ -Surf_tErr Surf_LoadVertexSet ( mriSurfaceRef this, - char* isName, - Surf_tVertexSet iSet ); - -/* writes the val fields to a separate file. */ -Surf_tErr Surf_WriteValues ( mriSurfaceRef this, - char* isFileName ); - -/* return status of a vertex set */ -Surf_tErr Surf_IsVertexSetLoaded ( mriSurfaceRef this, - Surf_tVertexSet iSet, - tBoolean* obIsLoaded ); - -/* read an annotation file */ -Surf_tErr Surf_LoadAnnotation ( mriSurfaceRef this, - char* isFileName ); - -/* Query and return a color table based on internal data, like if a - annotation had an embedded color table. This allocates a new table - and the caller is repsonsible for deleting it. */ -Surf_tErr Surf_IsInternalColorTablePresent ( mriSurfaceRef this, - tBoolean* obPresent ); -Surf_tErr Surf_NewColorTableFromInternal ( mriSurfaceRef this, - COLOR_TABLE** opTable ); - - -/* ======================================================= Vertex iteration */ - -/* for iterating thru the vertices in the surface. first step is to set the - iteration start point by passing an orientation and plane. the plane should - be a voxel in client space with the coord that is constant on the plane - set and the other coords set to 0. then use GetNextAndNeightborVertex to - get two neighboring verticies. often we compare pairs of - verticies in faces, so we access them as next and last. returns the vertex - in the client's coord system. returns Surf_tErr_LastVertex when done, at - which point the next vertices returned will be in a new face. when - all faces are done, Surf_tErr_LastFace will be returned. */ -Surf_tErr Surf_SetIteratorPosition ( mriSurfaceRef this, - xVoxelRef plane ); -Surf_tErr Surf_GetNextAndNeighborVertex ( mriSurfaceRef this, - Surf_tVertexSet iSet, - xVoxelRef oNextVoxel, - int* onNextIndex, - xVoxelRef oNeighborVoxel, - int* onNeighborIndex); - -/* ==================================================== Geometry managament */ - -/* Copies the MRIS's VOL_GEOM field. */ -Surf_tErr Surf_CopyGeometryInformation ( mriSurfaceRef this, - VOL_GEOM* ioVolumeGeometry ); - -Surf_tErr Surf_TransformToVolumeGeometry ( mriSurfaceRef this, - VOL_GEOM* iVolumeGeometry ); - -/* ========================================================== Vertex access */ - -/* get a vertex by index in voxel space */ -Surf_tErr Surf_GetNthVertex ( mriSurfaceRef this, - Surf_tVertexSet iSet, - int inIndex, - xVoxelRef oClientVoxel, - char* osDescription ); - -/* find the closest vertex to the given location */ -Surf_tErr Surf_GetClosestVertexVoxel ( mriSurfaceRef this, - Surf_tVertexSet iSet, - xVoxelRef iClientVoxel, - xVoxelRef oClientVoxel, - char* osDescription ); - -/* sets a vertex value within the MRIS structure. */ -Surf_tErr Surf_SetVertexValue ( mriSurfaceRef this, - Surf_tVertexSet iVertexSet, - Surf_tValueSet iValueSet, - xVoxelRef iClientVoxel, - float iValue ); -Surf_tErr Surf_GetVertexValue ( mriSurfaceRef this, - Surf_tVertexSet iVertexSet, - Surf_tValueSet iValueSet, - xVoxelRef iClientVoxel, - float* opValue ); - -/* gets an annotation value from a vertex, based on vno. */ -Surf_tErr Surf_GetVertexAnnotationByIndex ( mriSurfaceRef this, - int iVertexIndex, - int* oAnnotation ); - -/* get distance between two points in surface space. */ -Surf_tErr Surf_GetDistance ( mriSurfaceRef this, - xVoxelRef iClientVoxel1, - xVoxelRef iClientVoxel2, - float* ofDistance ); - -/* Sometimes it's easier to just give access to the surface. */ -Surf_tErr Surf_GetMRIS ( mriSurfaceRef this, - MRIS** opSurface ); - -Surf_tErr Surf_GetSurfaceSetName ( Surf_tVertexSet iSet, - char* osName ); - - -Surf_tErr Surf_UsesRealRAS ( mriSurfaceRef this, - tBoolean* obUseRealRAS ); - -/* ============================================================== Processing */ - -/* Most of these are just wrappers to functions in mrisurf.c */ - -Surf_tErr Surf_AverageVertexPositions ( mriSurfaceRef this, - int inNumAverages ); - -/* =============================================================== Internal */ - -/* for each face in the mris surface, create a Surf_tFace, and put the - vertex values in it in client coord system */ -Surf_tErr Surf_ConvertSurfaceToClientSpace_ ( mriSurfaceRef this, - Surf_tVertexSet iSet ); - - -/* helper functions */ -float Surf_GetVertexCoord ( vertex_type* iVertex, - Surf_tVertexSet iSet, - Surf_tOrientation iOrientation ); -void Surf_GetClosestVertex ( mriSurfaceRef this, - Surf_tVertexSet iSet, - xVoxelRef iSurfaceVoxel, - vertex_type** opVertex, - int* onIndex, - float* ofDistance); -void Surf_ConvertVertexToVoxel ( vertex_type* iVertex, - Surf_tVertexSet iSet, - mriTransformRef iTransform, - xVoxelRef oVoxel ); -void Surf_ConvertVoxelToSurfaceSpace ( xVoxelRef iVoxel, - mriTransformRef iTransform, - xVoxelRef oSurfVox ); - -Surf_tErr Surf_Verify ( mriSurfaceRef this ); -char* Surf_GetErrorString ( Surf_tErr ieCode ); - -#endif diff --git a/include/mriTransform.h b/include/mriTransform.h index 00e08f16ffe..09c96ce2fdd 100644 --- a/include/mriTransform.h +++ b/include/mriTransform.h @@ -25,10 +25,6 @@ #ifndef mriTransform_h #define mriTransform_h -#if defined(__cplusplus) -extern "C" { -#endif - #include "matrix.h" #include "mri.h" /* transform.h requires mri.h */ #include "transform.h" @@ -179,18 +175,9 @@ Trns_tErr Trns_CalcMatricies_ ( mriTransformRef ThisKRT ); /* debugging support */ Trns_tErr Trns_Verify ( mriTransformRef ThisKRT ); void Trns_DebugPrint_ ( mriTransformRef ThisKRT ); -void Trns_Signal ( char* inMsg, +void Trns_Signal ( const char* inMsg, int inLineNum, Trns_tErr ieCode ); -char* Trns_GetErrorString ( Trns_tErr ieCode ); +const char* Trns_GetErrorString ( Trns_tErr ieCode ); -#if defined(__cplusplus) -}; #endif - -#endif - - - - - diff --git a/include/mriTypes.h b/include/mriTypes.h deleted file mode 100644 index f5b129c7076..00000000000 --- a/include/mriTypes.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file mriTypes.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.9 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef mriTypes_h -#define mriTypes_h - -#define mri_knSubjectNameLen 256 -#define mri_knPathLen 1024 - -typedef enum -{ - mri_tOrientation_None = -1, - mri_tOrientation_Coronal = 0, - mri_tOrientation_Horizontal, - mri_tOrientation_Sagittal, - mri_knNumOrientations -} mri_tOrientation; - -typedef enum -{ - mri_tCoordSpace_None = -1, - mri_tCoordSpace_VolumeIdx = 0, - mri_tCoordSpace_SurfaceRAS, - mri_tCoordSpace_RAS, - mri_tCoordSpace_Talairach, - mri_knNumCoordSpaces -} mri_tCoordSpace; - -#endif diff --git a/include/mriVolume.h b/include/mriVolume.h deleted file mode 100644 index 0ae5ac7fcc3..00000000000 --- a/include/mriVolume.h +++ /dev/null @@ -1,834 +0,0 @@ -/** - * @file mriVolume.h - * @brief declaration of mri volume structs - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.44 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef mriVolume_h -#define mriVolume_h - -#include "mri.h" -#include "xTypes.h" -#include "xVoxel.h" -#include "mriTypes.h" -#include "mriTransform.h" -#include "transform.h" - -/* Enable this to turn macros on, see details below. */ -#define VOLM_USE_MACROS - -typedef enum -{ - Volm_tErr_Invalid = -1, - Volm_tErr_NoErr = 0, - Volm_tErr_InvalidSignature, - Volm_tErr_InvalidParamater, - Volm_tErr_InvalidIdx, - Volm_tErr_AllocationFailed, - Volm_tErr_CouldntReadVolume, - Volm_tErr_CouldntCopyVolume, - Volm_tErr_CouldntReadTransform, - Volm_tErr_CouldntCopyTransform, - Volm_tErr_CouldntNormalizeVolume, - Volm_tErr_CouldntExportVolumeToCOR, - Volm_tErr_MRIVolumeNotPresent, - Volm_tErr_ScannerTransformNotPresent, - Volm_tErr_IdxToRASTransformNotPresent, - Volm_tErr_FloodVisitCommandNotSupported, - Volm_tErr_FsenvNotFoundWhileSearchingForTransformDest, - Volm_tErr_MNI305NotFoundWhilePopulatingTramsformDest, - Volm_tErr_ErrorReadingMNI305WhilePopulatingTramsformDest, - Volm_knNumErrorCodes -} Volm_tErr; - -#define Volm_knErrStringLen 1024 - -typedef float Volm_tValue; -typedef Volm_tValue *Volm_tValueRef; -#define Volm_knMaxValue 255 -#define Volm_knNumValues 256 -#define Volm_knNumColorTableEntries 256 - -#define Volm_kSignature 0xd9d6b2a9 - -#define Volm_kfDefaultBrightness 0.35 -#define Volm_kfDefaultContrast 12.0 - -#define Volm_knMaxFloodIteration 20000 - -/* Function definition and return codes for a visit callback. The user - supplies their own visit function and it is called in the flood and - VisitAll algorithms. */ -typedef enum -{ - Volm_tVisitComm_Continue = 0, - Volm_tVisitComm_SkipRestOfRow, - Volm_tVisitComm_SkipRestOfPlane, - Volm_tVisitComm_Stop, - Volm_knNumVisitCommands -} Volm_tVisitCommand; -typedef Volm_tVisitCommand(*Volm_tVisitFunction)(xVoxelRef iMRIIdx, - float iValue, - void* ipData); - -/* Parameters for a generic flood algorithm. */ -typedef enum -{ - Volm_tValueComparator_Invalid = -1, - Volm_tValueComparator_LTE = 0, - Volm_tValueComparator_EQ, - Volm_tValueComparator_GTE, - Volm_knNumValueComparators, -} Volm_tValueComparator; -/* Optional comparator function for the flood function. Return true - for a successful flood, i.e. it should continue on this voxel,and - false if not. */ -typedef tBoolean(*Volm_tFloodComparatorFunction)(xVoxelRef iMRIIdx, - float iValue, - void* ipData); - -/* This should be kept in sync with the SAMPLE_* constants in mri.h */ -typedef enum -{ - Volm_tSampleType_Nearest = 0, - Volm_tSampleType_Trilinear, - Volm_tSampleType_Sinc, - Volm_knNumSampleTypes -} Volm_tSampleType; - -typedef enum -{ - Volm_tResampleMethod_RAS = 0, - Volm_tResampleMethod_Slice, - Volm_knNumResampleMethods -} Volm_tResampleMethod; - -typedef struct -{ - xVoxel mSourceIdx; /* The starting voxel */ - float mfSourceValue; /* The value at the starting voxel */ - float mfFuzziness; /* The fuzziness for the comparator */ - Volm_tValueComparator mComparatorType; /* Compare type */ - Volm_tFloodComparatorFunction mComparatorFunc; /* Compare function */ - void* mComparatorFuncData; /* Compare function data */ - float mfMaxDistance; /* Max distance of flood (in voxels) */ - tBoolean mb3D; /* Should the fill be in 3D? */ - mri_tOrientation mOrientation; /* If not, which plane? */ - - Volm_tVisitFunction mpFunction; /* User function, called for each */ - void* mpFunctionData; /* visited. */ - -} -Volm_tFloodParams; - -typedef struct -{ - - long mSignature; - - int mnDimensionX; - int mnDimensionY; - int mnDimensionZ; - int mnDimensionFrame; - - MRI* mpMriValues; /* MRI struct */ - float* mpSnapshot; /* copy of values */ - float** mpMaxValuesX; /* max projection in x plane, [y][z] */ - float** mpMaxValuesY; /* max projection in y plane, [x][z] */ - float** mpMaxValuesZ; /* max projection in z plane, [x][y] */ - - - Volm_tSampleType mSampleType; /* How to sample the volume */ - mriTransformRef mMRIIdxToAnaIdxTransform; /* MRI -> ana (via scnr RAS) */ - mriTransformRef mMNITalLtzToRealTalTransform; /* tal (z<0) -> real tal */ - mriTransformRef mMNITalGtzToRealTalTransform; /* tal (z>0) -> real tal */ - mriTransformRef mScannerTransform; /* idx -> scnaner */ - TRANSFORM* mDisplayTransform; - - char msSubjectName[mri_knSubjectNameLen]; - char msVolumeName[mri_knSubjectNameLen]; - char msOriginalPath[mri_knPathLen]; - - float mfColorBrightness; /* threshold */ - float mfColorContrast; /* squash */ - float mfColorMin; /* min color value for col table */ - float mfColorMax; /* max color value for col table */ - xColor3f mafColorTable[Volm_knNumColorTableEntries]; - xColor3n manColorTable[Volm_knNumColorTableEntries]; - MATRIX *m_resample_orig; /* 256^3->original volume */ - MATRIX *m_resample; /* 256^3->original volume */ - MATRIX *m_resample_inv; /* original volume->256^3 */ - float mfMinValue; /* max value in mpMriValues */ - float mfMaxValue; /* min value in mpMriValues */ - - /* There are two versions of the resample matrices; one that takes - into effect the RAS transform and one that doesn't. Normally you - would want to use the RAS transform, but the other is available - for viewing the volume in its slice orientation. They both have - pixel size component, however. */ - Volm_tResampleMethod mResampleMethod; - MATRIX* mResampleToRAS; - MATRIX* mResampleToRASOrig; - MATRIX* mResampleToRASInverse; - MATRIX* mResampleToSlice; - MATRIX* mResampleToSliceOrig; - MATRIX* mResampleToSliceInverse; - - - VECTOR* mpTmpScreenIdx; /* Used as tmp variables in macros. */ - VECTOR* mpTmpMRIIdx; - xVoxel mTmpVoxel; - xVoxel mTmpVoxel2; - double mTmpReal; - -} -mriVolume, *mriVolumeRef; - -Volm_tErr Volm_New ( mriVolumeRef* opVolume ); -Volm_tErr Volm_Delete ( mriVolumeRef* iopVolume ); -Volm_tErr Volm_DeepClone ( mriVolumeRef this, - mriVolumeRef* opVolume ); - -Volm_tErr Volm_CreateFromVolume( mriVolumeRef this, - mriVolumeRef iVolume ); -Volm_tErr Volm_ImportData ( mriVolumeRef this, - char* isSource ); -Volm_tErr Volm_ExportNormToCOR ( mriVolumeRef this, - char* isPath ); - -Volm_tErr Volm_Save ( mriVolumeRef iVolume, - char* isFileName, - tBoolean ibSaveFileName ); - -Volm_tErr Volm_LoadDisplayTransform ( mriVolumeRef this, - char* isSource ); -Volm_tErr Volm_UnloadDisplayTransform ( mriVolumeRef this ); - - -/* Copies the MRI's VOL_GEOM field. */ -Volm_tErr Volm_CopyGeometryInformation ( mriVolumeRef this, - VOL_GEOM* ioVolumeGeometry ); - -/* Use the GetColor functions when you just need to display a color on - the screen. It gets a sampled value and passes it through the color - table to return an intensity color. */ -void Volm_GetIntColorAtIdx ( mriVolumeRef this, - xVoxelRef iIdx, - xColor3nRef oColor ); -void Volm_GetMaxIntColorAtIdx ( mriVolumeRef this, - xVoxelRef iIdx, - mri_tOrientation iOrientation, - xColor3nRef oColor ); - -Volm_tErr Volm_GetDimensions ( mriVolumeRef this, - int* onDimensionX, - int* onDimensionY, - int* onDimensionZ ); -Volm_tErr Volm_GetNumberOfFrames ( mriVolumeRef this, - int* onDimensionFrames ); -Volm_tErr Volm_GetType ( mriVolumeRef this, - int* onType ); -Volm_tErr Volm_GetValueMinMax ( mriVolumeRef this, - float* ofMin, - float* ofMax ); - -Volm_tErr Volm_GetResampleMethod ( mriVolumeRef this, - Volm_tResampleMethod* oMethod ); -Volm_tErr Volm_SetResampleMethod ( mriVolumeRef this, - Volm_tResampleMethod iMethod ); - -Volm_tErr Volm_GetSampleType ( mriVolumeRef this, - Volm_tSampleType* oType ); -Volm_tErr Volm_SetSampleType ( mriVolumeRef this, - Volm_tSampleType iType ); - -/* Use the GetValue functions when you want the real value of the - voxel. Before calling the unsafe version, make sure the volume is - valid, the index is in bounds, and you're passing a valid - pointer. */ -Volm_tErr Volm_GetValueAtIdx ( mriVolumeRef this, - xVoxelRef iIdx, - float* oValue ); -Volm_tErr Volm_GetValueAtIdxUnsafe ( mriVolumeRef this, - xVoxelRef iIdx, - float* oValue ); -Volm_tErr Volm_SetValueAtIdx ( mriVolumeRef this, - xVoxelRef iIdx, - float iValue ); - -Volm_tErr Volm_GetValueAtIdxFrame ( mriVolumeRef this, - xVoxelRef iIdx, - int iFrame, - float* oValue ); -Volm_tErr Volm_GetValueAtIdxFrameUnsafe ( mriVolumeRef this, - xVoxelRef iIdx, - int iFrame, - float* oValue ); -Volm_tErr Volm_SetValueAtIdxFrame ( mriVolumeRef this, - xVoxelRef iIdx, - int iFrame, - float iValue ); - -/* These work on MRI indices instead of screen indices, for high-res - volumes. */ -Volm_tErr Volm_GetValueAtMRIIdx ( mriVolumeRef this, - xVoxelRef iMRIIdx, - float* oValue ); -Volm_tErr Volm_SetValueAtMRIIdx ( mriVolumeRef this, - xVoxelRef iMRIIdx, - float iValue ); - -/* Returns whether or not we have a talairach transform. */ -Volm_tErr Volm_HasTalTransform ( mriVolumeRef this, - tBoolean* obHasTransform ); - -/* coordinate conversion. idx stands for index and is the 0->dimension-1 - index of the volume. RAS space, aka world space, is centered on the - center of the volume and is in mm. mni tal is mni's version of - talairach space. the other tal is mni tal with a small modification. */ -Volm_tErr Volm_ConvertIdxToRAS ( mriVolumeRef this, - xVoxelRef iIdx, - xVoxelRef oRAS ); -Volm_tErr Volm_ConvertRASToIdx ( mriVolumeRef this, - xVoxelRef iRAS, - xVoxelRef oIdx ); -Volm_tErr Volm_ConvertIdxToMNITal ( mriVolumeRef this, - xVoxelRef iIdx, - xVoxelRef oMNITal ); -Volm_tErr Volm_ConvertIdxToTal ( mriVolumeRef this, - xVoxelRef iIdx, - xVoxelRef oTal ); -Volm_tErr Volm_ConvertTalToIdx ( mriVolumeRef this, - xVoxelRef iTal, - xVoxelRef oIdx ); -Volm_tErr Volm_ConvertIdxToScanner ( mriVolumeRef this, - xVoxelRef iIdx, - xVoxelRef oScanner ); -Volm_tErr Volm_ConvertMRIIdxToScanner ( mriVolumeRef this, - xVoxelRef iMRIIdx, - xVoxelRef oScanner ); -Volm_tErr Volm_ConvertIdxToMRIIdx ( mriVolumeRef this, - xVoxelRef iIdx, - xVoxelRef oMRIIdx ); -Volm_tErr Volm_ConvertMRIIdxToIdx ( mriVolumeRef this, - xVoxelRef iMRIIdx, - xVoxelRef oIdx ); -Volm_tErr Volm_ConvertMRIIdxToRAS ( mriVolumeRef this, - xVoxelRef iMRIIdx, - xVoxelRef oRAS ); -Volm_tErr Volm_ConvertRASToMRIIdx ( mriVolumeRef this, - xVoxelRef iRAS, - xVoxelRef oMRIIdx ); - -/* Use these when converting an RAS coming from the surface to an MRI - index. This is different than normal RAS because surface RAS always - has c_ras = 0, where volume RAS doesn't. */ -Volm_tErr Volm_ConvertMRIIdxToSurfaceRAS ( mriVolumeRef this, - xVoxelRef iMRIIdx, - xVoxelRef oSurfaceRAS ); -Volm_tErr Volm_ConvertSurfaceRASToMRIIdx ( mriVolumeRef this, - xVoxelRef iSurfaceRAS, - xVoxelRef oMRIIdx ); - -Volm_tErr Volm_GetMRIIdxToAnaIdxTransform ( mriVolumeRef this, - mriTransformRef* opTransform ); - -/* Generic flood algorithm. Starts at a user-supplied voxel and floods - outwards, in 3D or inplane, and for every valid voxel, calls the - user-supplied visitation function. User needs to fill out - Volm_tFloodParams struct. */ -Volm_tErr Volm_Flood ( mriVolumeRef this, - Volm_tFloodParams* iParams ); -Volm_tErr Volm_FloodIterate_ ( mriVolumeRef this, - Volm_tFloodParams* iParams, - xVoxelRef iIdx, - tBoolean* visited ); - -/* calls the parameter function for every voxel, passing the MRI index, the - value, and the pointer passed to it. */ -Volm_tErr Volm_VisitAllVoxels ( mriVolumeRef this, - Volm_tVisitFunction iFunc, - void* ipData ); - - -Volm_tErr Volm_FindMaxValues ( mriVolumeRef this ); - -Volm_tErr Volm_MakeColorTable ( mriVolumeRef this ); - -Volm_tErr Volm_SetBrightnessAndContrast ( mriVolumeRef this, - float ifBrightness, - float ifContrast ); -Volm_tErr Volm_SetColorMinMax ( mriVolumeRef this, - float ifMin, - float ifMax ); -Volm_tErr Volm_GetBrightnessAndContrast ( mriVolumeRef this, - float* ofBrightness, - float* ofContrast ); - -Volm_tErr Volm_SaveToSnapshot ( mriVolumeRef this ); -Volm_tErr Volm_RestoreFromSnapshot ( mriVolumeRef this ); - -Volm_tErr Volm_Rotate ( mriVolumeRef this, - mri_tOrientation iAxis, - float ifDegrees ); -Volm_tErr Volm_Threshold ( mriVolumeRef this, - float iThreshold, - tBoolean ibAbove, - float iNewValue ); -Volm_tErr Volm_Flip ( mriVolumeRef this, - mri_tOrientation iAxis ); -Volm_tErr Volm_SetAllValues ( mriVolumeRef this, - float iValue ); - -Volm_tErr Volm_CopySubjectName ( mriVolumeRef this, - char* oSubjectName, - int inDestLen ); -Volm_tErr Volm_CopyVolumeName ( mriVolumeRef this, - char* oVolumeName, - int inDestLen ); -Volm_tErr Volm_CopySourceDir ( mriVolumeRef this, - char* oSourceDir, - int inDestLen ); - -Volm_tErr Volm_SetSubjectName ( mriVolumeRef this, - char* isName ); -Volm_tErr Volm_SetVolumeName ( mriVolumeRef this, - char* isName ); -Volm_tErr Volm_ExtractAndSetSubjectName ( mriVolumeRef this, - char* isSource ); -Volm_tErr Volm_ExtractAndSetVolumeName ( mriVolumeRef this, - char* isSource ); - -/* Sets the mri voxel size and fov so that the smallest dimension is 1. */ -Volm_tErr Volm_SetMinVoxelSizeToOne ( mriVolumeRef this ); - -/* Conforms the volume to 256^3 1mm isotropic. */ -Volm_tErr Volm_Conform ( mriVolumeRef this ); - -/* Sets up internal data structures from an MRI volume and starts - using the given MRI as its voxel values. */ -Volm_tErr Volm_SetFromMRI_ ( mriVolumeRef this, - MRI* iMRI ); - -/* Calculates this->mMRIIdxToAnaIdxTransform baesd on resample method. */ -Volm_tErr Volm_CalculateMRIIdxToAnaIdx_ ( mriVolumeRef this ); - -/* For the max values in an orientation. */ -Volm_tErr Volm_GetMaxValueAtMRIIdx_ ( mriVolumeRef this, - xVoxelRef iMRIIdx, - mri_tOrientation iOrientation, - float* oValue ); - -/* Note that the functions in this section are implemented as - functions and macros. The functions are slower but safer, and the - macros are faster but don't make any checks. So you should test - with the functions and then build with the macros turned on. And - keep the macro and functions version synced in - development. _grin_ Turn the flag on at the top of this file. */ -#ifndef VOLM_USE_MACROS - -/* Note that all the public functions that refer to 'idx' refer to - screen idx, or the index in 256^3 space. The local MRI idx might - not be 256^3, so this conversion takes the idx from 256^3 space to - the local MRI space. This is done using the m_resample matrix. All - the access functions of course need to use the local MRI idx. */ -void Volm_ConvertScreenIdxToMRIIdx_ ( mriVolumeRef this, - xVoxelRef iScreenIdx, - xVoxelRef oMRIIdx ); -void Volm_ConvertMRIIdxToScreenIdx_ ( mriVolumeRef this, - xVoxelRef iMRIIdx, - xVoxelRef oScreenIdx ); - -/* safer function versions of main accessing and setting functions */ -void Volm_GetValueAtIdx_ ( mriVolumeRef this, - xVoxelRef iIdx, - float* oValue ); -void Volm_GetValueAtMRIIdx_ ( mriVolumeRef this, - xVoxelRef iMRIIdx, - float* oValue ); -void Volm_GetValueAtIdxFrame_ ( mriVolumeRef this, - xVoxelRef iIdx, - int iFrame, - float* oValue ); -void Volm_GetSampledValueAtIdx_ ( mriVolumeRef this, - xVoxelRef iIdx, - float* oValue); -void Volm_GetSampledValueAtIdxFrame_ ( mriVolumeRef this, - xVoxelRef iIdx, - int iFrame, - float* oValue ); - - -void Volm_SetValueAtIdx_ ( mriVolumeRef this, - xVoxelRef iIdx, - float iValue ); -void Volm_SetValueAtMRIIdx_ ( mriVolumeRef this, - xVoxelRef iIdx, - float iValue ); -void Volm_SetValueAtIdxFrame_ ( mriVolumeRef this, - xVoxelRef iIdx, - int iFrame, - float iValue ); - -#else /* VOLM_USE_MACROS */ - -/* macro version of main accessing and setting functions */ - -#define Volm_ConvertScreenIdxToMRIIdx_(this,iScreenIdx,oMRIIdx) \ - *MATRIX_RELT(this->mpTmpScreenIdx,1,1) = (iScreenIdx)->mfX; \ - *MATRIX_RELT(this->mpTmpScreenIdx,2,1) = (iScreenIdx)->mfY; \ - *MATRIX_RELT(this->mpTmpScreenIdx,3,1) = (iScreenIdx)->mfZ; \ - *MATRIX_RELT(this->mpTmpScreenIdx,4,1) = 1.0 ; \ - \ - MatrixMultiply( this->m_resample, this->mpTmpScreenIdx, this->mpTmpMRIIdx ); \ - \ - (oMRIIdx)->mfX = *MATRIX_RELT(this->mpTmpMRIIdx,1,1); \ - (oMRIIdx)->mfY = *MATRIX_RELT(this->mpTmpMRIIdx,1,2); \ - (oMRIIdx)->mfZ = *MATRIX_RELT(this->mpTmpMRIIdx,1,3); \ - \ - if( floor((oMRIIdx)->mfX+0.5) < 0 || \ -floor((oMRIIdx)->mfX+0.5) >= this->mnDimensionX || \ - floor((oMRIIdx)->mfY+0.5) < 0 || \ -floor((oMRIIdx)->mfY+0.5) >= this->mnDimensionY || \ - floor((oMRIIdx)->mfZ+0.5) < 0 || \ -floor((oMRIIdx)->mfZ+0.5) >= this->mnDimensionZ ) { \ - xVoxl_Set( oMRIIdx, 0, 0, 0 ); \ - } - -#define Volm_ConvertMRIIdxToScreenIdx_(this,iMRIIdx,oScreenIdx) \ - *MATRIX_RELT(this->mpTmpMRIIdx,1,1) = (iMRIIdx)->mfX; \ - *MATRIX_RELT(this->mpTmpMRIIdx,2,1) = (iMRIIdx)->mfY; \ - *MATRIX_RELT(this->mpTmpMRIIdx,3,1) = (iMRIIdx)->mfZ; \ - *MATRIX_RELT(this->mpTmpMRIIdx,4,1) = 1.0 ; \ - \ - MatrixMultiply( this->m_resample_inv, \ - this->mpTmpMRIIdx, this->mpTmpScreenIdx ); \ - \ - (oScreenIdx)->mfX = *MATRIX_RELT(this->mpTmpScreenIdx,1,1); \ - (oScreenIdx)->mfY = *MATRIX_RELT(this->mpTmpScreenIdx,1,2); \ - (oScreenIdx)->mfZ = *MATRIX_RELT(this->mpTmpScreenIdx,1,3); \ - \ - if( (floor((oScreenIdx)->mfX+0.5) < 0 || \ -floor((oScreenIdx)->mfX+0.5) >= 256 || \ - floor((oScreenIdx)->mfY+0.5) < 0 || \ -floor((oScreenIdx)->mfY+0.5) >= 256 || \ - floor((oScreenIdx)->mfZ+0.5) < 0 || \ -floor((oScreenIdx)->mfZ+0.5) >= 256) ) { \ - \ - xVoxl_Set( oScreenIdx, 0, 0, 0 ); \ - } - - - -#define Volm_GetValueAtIdx_(this,iIdx,oValue) \ - Volm_ConvertScreenIdxToMRIIdx_( this, iIdx, &this->mTmpVoxel ); \ - \ - switch( this->mpMriValues->type ) { \ - case MRI_UCHAR: \ - *oValue = \ - MRIvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ); \ - break; \ - case MRI_INT: \ - *oValue = \ - MRIIvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ); \ - break; \ - case MRI_LONG: \ - *oValue = \ - MRILvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ); \ - break; \ - case MRI_FLOAT: \ - *oValue = \ - MRIFvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ); \ - break; \ - case MRI_SHORT: \ - *oValue = \ - MRISvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ); \ - break; \ - default: \ - *oValue = 0; \ - break ; \ - } - -#define Volm_GetValueAtMRIIdx_(this,iMRIIdx,oValue) \ - switch( this->mpMriValues->type ) { \ - case MRI_UCHAR: \ - *oValue = \ - MRIvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ); \ - break; \ - case MRI_INT: \ - *oValue = \ - MRIIvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ); \ - break; \ - case MRI_LONG: \ - *oValue = \ - MRILvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ); \ - break; \ - case MRI_FLOAT: \ - *oValue = \ - MRIFvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ); \ - break; \ - case MRI_SHORT: \ - *oValue = \ - MRISvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ); \ - break; \ - default: \ - *oValue = 0; \ - break ; \ - } - -#define Volm_GetSampledValueAtIdx_(this,iIdx,oValue) \ - Volm_ConvertScreenIdxToMRIIdx_( this, iIdx, &this->mTmpVoxel ); \ - \ - MRIsampleVolumeType( this->mpMriValues, \ - xVoxl_GetFloatX(&this->mTmpVoxel), \ - xVoxl_GetFloatY(&this->mTmpVoxel), \ - xVoxl_GetFloatZ(&this->mTmpVoxel), \ - &this->mTmpReal, \ - (int)this->mSampleType ); \ - \ - *oValue = (float)this->mTmpReal; - - - -#define Volm_GetSampledValueAtIdxFrame_(this,iIdx,iFrame,oValue) \ - Volm_ConvertScreenIdxToMRIIdx_( this, iIdx, &this->mTmpVoxel ); \ - \ - MRIsampleVolumeFrameType( this->mpMriValues, \ - xVoxl_GetFloatX(&this->mTmpVoxel), \ - xVoxl_GetFloatY(&this->mTmpVoxel), \ - xVoxl_GetFloatZ(&this->mTmpVoxel), \ - iFrame, \ - (int)this->mSampleType, \ - &value ); \ - \ - *oValue = (float)this->mTmpReal; - -#define Volm_SetValueAtIdx_(this,iIdx,iValue) \ - Volm_ConvertScreenIdxToMRIIdx_( this, iIdx, &this->mTmpVoxel ); \ - \ - switch (this->mpMriValues->type) \ - { \ - default: \ - break ; \ - case MRI_UCHAR: \ - MRIvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ) = \ - (BUFTYPE) iValue; \ - break ; \ - case MRI_SHORT: \ - MRISvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ) = \ - (short) iValue; \ - break ; \ - case MRI_FLOAT: \ - MRIFvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ) = \ - (float) iValue; \ - break ; \ - case MRI_LONG: \ - MRILvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ) = \ - (long) iValue; \ - break ; \ - case MRI_INT: \ - MRIIvox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5) ) = \ - (int) iValue; \ - break ; \ - } - -#define Volm_SetValueAtMRIIdx_(this,iMRIIdx,iValue) \ - switch (this->mpMriValues->type) \ - { \ - default: \ - break ; \ - case MRI_UCHAR: \ - MRIvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ) = \ - (BUFTYPE) iValue; \ - break ; \ - case MRI_SHORT: \ - MRISvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ) = \ - (short) iValue; \ - break ; \ - case MRI_FLOAT: \ - MRIFvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ) = \ - (float) iValue; \ - break ; \ - case MRI_LONG: \ - MRILvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ) = \ - (long) iValue; \ - break ; \ - case MRI_INT: \ - MRIIvox( this->mpMriValues, (int)floor((iMRIIdx)->mfX+0.5), \ - (int)floor((iMRIIdx)->mfY+0.5), (int)floor((iMRIIdx)->mfZ+0.5) ) = \ - (int) iValue; \ - break ; \ - } - -#define Volm_GetValueAtIdxFrame_(this,iIdx,iFrame,oValue) \ - Volm_ConvertScreenIdxToMRIIdx_( this, iIdx, &this->mTmpVoxel ); \ - \ - switch( this->mpMriValues->type ) { \ - case MRI_UCHAR: \ - *oValue = \ - MRIseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ); \ - break; \ - case MRI_INT: \ - *oValue = \ - MRIIseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ); \ - break; \ - case MRI_LONG: \ - *oValue = \ - MRILseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ); \ - break; \ - case MRI_FLOAT: \ - *oValue = \ - MRIFseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ); \ - break; \ - case MRI_SHORT: \ - *oValue = \ - MRISseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ); \ - break; \ - default: \ - *oValue = 0; \ - break ; \ - } - -#define Volm_SetValueAtIdxFrame_(this,iIdx,iFrame,iValue) \ - Volm_ConvertScreenIdxToMRIIdx_( this, iIdx, &this->mTmpVoxel ); \ - \ - switch (this->mpMriValues->type) \ - { \ - default: \ - break ; \ - case MRI_UCHAR: \ - MRIseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ) = \ - (BUFTYPE) iValue; \ - break ; \ - case MRI_SHORT: \ - MRISseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ) = \ - (short) iValue; \ - break ; \ - case MRI_FLOAT: \ - MRIFseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ) = \ - (float) iValue; \ - break ; \ - case MRI_LONG: \ - MRILseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ) = \ - (long) iValue; \ - break ; \ - case MRI_INT: \ - MRIIseq_vox( this->mpMriValues, (int)floor((this->mTmpVoxel).mfX+0.5), \ - (int)floor((this->mTmpVoxel).mfY+0.5), \ -(int)floor((this->mTmpVoxel).mfZ+0.5), \ - iFrame ) = \ - (int) iValue; \ - break ; \ - } - -#define Volm_GetSincValueAtIdx_(this,iIdx,irValue) \ - Volm_ConvertScreenIdxToMRIIdx_( this, iIdx, &this->mTmpVoxel ); \ - \ - MRIsincSampleVolume( this->mpMriValues, \ - (this->mTmpVoxel).mfX, \ - (this->mTmpVoxel).mfY, \ - (this->mTmpVoxel).mfZ, \ - 2, irValue); - -#endif /* VOLM_USE_MACROS */ - -/* SOMEBODY changed this code so that the - Volm_ConvertScreenIdxToMRIIdx_ function automatically sets - out-of-bounds voxels to 0,0,0, so these functions are pretty much - worthless because voxels always end up being valid. */ -Volm_tErr Volm_Verify ( mriVolumeRef this ); -Volm_tErr Volm_VerifyIdx ( mriVolumeRef this, - xVoxelRef iIdx ); -Volm_tErr Volm_VerifyIdx_ ( mriVolumeRef this, - xVoxelRef iIdx ); -Volm_tErr Volm_VerifyMRIIdx_ ( mriVolumeRef this, - xVoxelRef iIdx ); - -/* So here is a function that really does return an error when an - index is out of bounds. This can be used to actually verify indices - so you don't end up drawing the value at 0,0,0 when you're outside - the bounds of the volume. -RKT */ -Volm_tErr Volm_VerifyIdxInMRIBounds ( mriVolumeRef this, - xVoxelRef iIdx ); - -Volm_tErr Volm_VerifyFrame_ ( mriVolumeRef this, - int iFrame ); -char* Volm_GetErrorString ( Volm_tErr ieCode ); - - -#endif diff --git a/include/mri_ca_labelMapper.h b/include/mri_ca_labelMapper.h deleted file mode 100644 index 4f188d3b945..00000000000 --- a/include/mri_ca_labelMapper.h +++ /dev/null @@ -1,323 +0,0 @@ -/** - * @file mri_ca_labelMapper.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef LabelMapper_h -#define LabelMapper_h - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "mri_ca_configFile.h" -#include "mri_ca_util.h" -#include "mri_ca_sparse2DMatrix.h" -#include "mri_ca_labelLUT.h" -#include "mri_ca_statisticsVolumeHeader.h" - -extern "C" -{ -#include "mri.h" -} - - -using namespace std; - -typedef map TypeMapSparse2DMatrix; -typedef vector TypeVectorSparse2DMatrix; - - -enum enumVolVizMethod { eThresholdedLabelProbabilities=0, eTranslucentLabelProbabilities}; - -class CLabel2PriorMapper -{ - - - -public: - CLabel2PriorMapper(CLabelLUT& theLabelLUT, CStatisticsVolumeHeader& newStatisticsVolumeHeader) : labelLUT(theLabelLUT), statisticsVolumeHeader(newStatisticsVolumeHeader) - {}; - - - - - TypeMapSparse2DMatrix& loadSlicePriors(int nSliceNumber, int nWidth, int nHeight) - { - priorSlices.clear(); - nCurrSliceNum=nSliceNumber; - // iterate over all labels in labelLUT - TypeMapLUT::iterator it; - - for (it=labelLUT.getMapLUT().begin(); it!=labelLUT.getMapLUT().end(); it++) - { - // form the filename - char strFilename[500]; - int nWhichLabel=it->first; - sprintf(strFilename,"%s/Prior-Slc%03d-Lab%03d.spmat",statisticsVolumeHeader.strStatisticsVolumeDirPath.c_str(),nCurrSliceNum,nWhichLabel); - - // load the sparse matrix - // create an initially zero prior and then use >> to update it if the file exists - CSparse2DMatrix zeroPriorProb(nWidth,nHeight); - //priorSlices[nWhichLabel]=zeroPriorProb; - priorSlices.insert(TypeMapSparse2DMatrix::value_type(nWhichLabel, zeroPriorProb)); - fstream ifs; - ifs.open(strFilename,ios::in | ios::nocreate); - if (ifs.good()) - { - ifs >> priorSlices[nWhichLabel]; - ifs.close(); - } - } - return(priorSlices); - } - - // -----------------------------For Baysian Classifier------------------------------------------------------------------------------ - bool loadLabelProbabilityVolume(int nWhichLabel, bool bDebug=false) - { - bool bLoadedVolumeOK=true; - vectorPriorSlices.clear(); - - // create an initially zero prior and then use >> to update it if the file exists - CSparse2DMatrix zeroPriorProb(statisticsVolumeHeader.nXDIM,statisticsVolumeHeader.nYDIM); - - for (int nWhichSlice=0; nWhichSlice> vectorPriorSlices[nWhichSlice]; - ifs.close(); - } - else - { - bLoadedVolumeOK=false; - } - } - return(bLoadedVolumeOK); - } - - float probability(int nTiX,int nTiY,int nTiZ) - { - return((float)vectorPriorSlices[nTiZ](nTiX,nTiY)/(float)statisticsVolumeHeader.nNumSubjects); - // [[]] could speed by not normalizing return(vectorPriorSlices[nTiZ](nTiX,nTiY)); - } - - // interpolate the probability at the given talairach point for the label loaded with loadMeasureProbabilityVolume() - // NOTE: vectorCanonicalPointsForInterpolation contains the 8 strongly connected locations in talairach space - float probability(float fTiX, float fTiY, float fTiZ, const TypeMatrixFloat& vectorCanonicalPointsForInterpolation) - { - // compute the value at each of the 8 strongly connected locations - TypeVectorFloat vectorValueAtTriplets; - for (int i=0; i<(int)vectorCanonicalPointsForInterpolation.size(); i++) - { - vectorValueAtTriplets.push_back(probability(vectorCanonicalPointsForInterpolation[i][0], - vectorCanonicalPointsForInterpolation[i][1], - vectorCanonicalPointsForInterpolation[i][2])); - } - - // interpolate these 8 strongly connected locations to get the value for the current floating point lcoation in talairach space - return(statisticsVolumeHeader.interpolateLinear(fTiX,fTiY,fTiZ,vectorCanonicalPointsForInterpolation,vectorValueAtTriplets)); - } - - - bool freeLabelProbabilityVolume() - { - vectorPriorSlices.clear(); - return(true); - } - - // ==============================End For Baysian Classifie========================================================================== - - - bool writeSlicePriors() - { - // loop over all priorSlices - TypeMapSparse2DMatrix::iterator it; - for (it=priorSlices.begin(); it!=priorSlices.end(); it++) - { - // form the filename - char strFilename[500]; - int nWhichLabel=it->first; - sprintf(strFilename,"%s/Prior-Slc%03d-Lab%03d.spmat",statisticsVolumeHeader.strStatisticsVolumeDirPath.c_str(),nCurrSliceNum,nWhichLabel); - - fstream ofs; - ofs.open(strFilename,ios::out); - // write the sparse matrix out to disk - ofs << priorSlices[nWhichLabel]; - ofs.close(); - } - - return(true); - } - - - bool updateSlicePriors(MRI* pVolume) - { - // loop over the pixels in slice and increment the corresponding prior location - int nTiZ=nCurrSliceNum; - TypeMapFractionalAreaAndPoints mapFractionalAreaAndPoints; - TypeMapFractionalAreaAndPoints::iterator it; - - - //for (int nTiX=76; nTiX<77; nTiX++) - // for (int nTiY=65; nTiY<66; nTiY++) - for (int nTiX=0; nTiXfirst; - float fFractionalVolume= it->second.fFractionalArea; - priorSlices[nLabel].increment(nTiX,nTiY, fFractionalVolume); - } - } - }; - - return(true); - } - - // makeTestLabelPriorSlices generates a Test label prior vol - bool makeTestLabelPriorSlices() - { - unsigned char ucharFirstLabel=1; - unsigned char ucharSecondLabel=2; - float floatCountFirstLabel; - float floatCountSecondLabel; - - for (int x=0; xfirst; - float floatMaxCount=0; - - float floatCurrLabelCount; - int nWhichLabel; - - - for ( ; it!=itEnd; it++) - { - nWhichLabel=it->first; - floatCurrLabelCount=priorSlices[nWhichLabel](nCol, nRow); - if (floatCurrLabelCount>floatMaxCount) - { - ucharLabelWithMaxPrior=nWhichLabel; - floatMaxCount=floatCurrLabelCount; - } - } - - fProbability= (float)floatMaxCount/(float)statisticsVolumeHeader.nNumSubjects; - if (fProbability>fThreshold) - return(ucharLabelWithMaxPrior); - else - { - fProbability=1.0-fProbability; - return(0); // index 0 is transparent index - } - } - - - - bool freeSlicePriors() - { - priorSlices.clear(); - return(true); - } - - - - -private: - CLabelLUT& labelLUT; - CStatisticsVolumeHeader& statisticsVolumeHeader; - TypeMapSparse2DMatrix priorSlices; // holds one slice of each labels prior label probability - int nCurrSliceNum; - - // --- used for labeling after priors are computed, holds one label's prior label probability volume - TypeVectorSparse2DMatrix vectorPriorSlices; - - -}; - - - -#endif - - - - - - - - - diff --git a/include/mri_ca_labelingParameters.h b/include/mri_ca_labelingParameters.h deleted file mode 100644 index b2005231d27..00000000000 --- a/include/mri_ca_labelingParameters.h +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file mri_ca_labelingParameters.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef LabelingParameters_h -#define LabelingParameters_h - -using namespace std ; - -#include -#include -#include -#include -#include "mri_ca_configFile.h" -#include "mri_ca_measure.h" -#include "mri_ca_util.h" -#include "mri_ca_trainingParameters.h" - - -class CLabelingParameters -{ - -public: - void read() - { // init the data members to be empty - strStatisticsVolumeHeaderPath.erase(); - arr2DstrSubjectsToLabel.clear(); - - // get the values from the config file - labelingConfigFile.get(strLabelLUT, "GeneralLabelingParameters", "LabelLUT"); - labelingConfigFile.get(strLabeledVolumeSourceType, "GeneralLabelingParameters", "LabeledVolumeSourceType"); - if (strLabeledVolumeSourceType=="CMA") - { - enumLabeledVolumeSourceType=enumCMA; - } - else if (strLabeledVolumeSourceType=="NMRAutoFixer") - { - enumLabeledVolumeSourceType=enumNMRAutoFixer; - } - else if (strLabeledVolumeSourceType=="Killiany") - { - enumLabeledVolumeSourceType=enumKilliany; - } - else - { - enumLabeledVolumeSourceType=enumUnknown; - }; - labelingConfigFile.get(strStatisticsVolumeHeaderPath, "GeneralLabelingParameters", "StatisticsVolumeHeaderPath"); - labelingConfigFile.get(nNumberOfBlocks, "GeneralLabelingParameters", "nNumberOfBlocks"); - if (nNumberOfBlocks<=0) - { - cout << "Error: nNumberOfBlocks must be a positive integer\n"; - exit(1); - } - - labelingConfigFile.get(arr2DstrSubjectsToLabel, "SubjectsToLabel", ""); - } - - void write(bool bEchoToStdOut=false) - { - labelingConfigFile.writeSection("GeneralLabelingParameters", bEchoToStdOut); - labelingConfigFile.write(strLabelLUT, "LabelLUT",bEchoToStdOut); - labelingConfigFile.write(strLabeledVolumeSourceType, "LabeledVolumeSourceType",bEchoToStdOut); - labelingConfigFile.write(strStatisticsVolumeHeaderPath, "StatisticsVolumeHeaderPath",bEchoToStdOut); - labelingConfigFile.write(nNumberOfBlocks, "nNumberOfBlocks",bEchoToStdOut); - labelingConfigFile.writeSection("SubjectsToLabel", bEchoToStdOut); - labelingConfigFile.write(arr2DstrSubjectsToLabel, "",bEchoToStdOut); - } - - // default dtor, copy , assign OK - CLabelingParameters(string strFilepath, int nProt=0) - { - labelingConfigFile.init(strFilepath, nProt); - strStatisticsVolumeHeaderPath.erase(); - arr2DstrSubjectsToLabel.clear(); - } - - -public: - - LabeledVolumeSourceType enumLabeledVolumeSourceType; - string strLabeledVolumeSourceType; - string strStatisticsVolumeHeaderPath; - TypeMatrixString arr2DstrSubjectsToLabel; - string strLabelLUT; - int nNumberOfBlocks; - //-- - CConfigFile labelingConfigFile; - -private: - CLabelingParameters() - {}; // disable default ctor -}; - -#endif diff --git a/include/mri_ca_measMapper.h b/include/mri_ca_measMapper.h deleted file mode 100644 index ac26cda57c6..00000000000 --- a/include/mri_ca_measMapper.h +++ /dev/null @@ -1,502 +0,0 @@ -/** - * @file mri_ca_measMapper.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef MeasMapper_h -#define MeasMapper_h - -#include -#include -#include -#include -#include - - -#include "mri_ca_measure.h" -#include "mri_ca_util.h" -#include "mri_ca_sparse2DGausDistMatrix.h" -#include "mri_ca_labelLUT.h" -#include "mri_ca_measureVolume.h" -#include "mri_ca_configFile.h" -#include "mri_ca_trainingParameters.h" -#include "mri_ca_statisticsVolumeHeader.h" -#include -#include -extern "C" -{ -#include "mri.h" -} - -using namespace std; - - -typedef vector TypeVectorMeasureVolume; -typedef map TypeMapSparse2DGausDistMatrix; -typedef vector TypeVectorSparse2DGausDistMatrix; - -class CMeas2DensMapper -{ - - - -public: - - - CMeas2DensMapper(CLabelLUT& labelNewLUT, CStatisticsVolumeHeader& newStatisticsVolumeHeader) : labelLUT(labelNewLUT), statisticsVolumeHeader(newStatisticsVolumeHeader) - {}; - - bool setNumberOfMeasures(int nNumOfMeasures) - { - CMeasureVolume newMeasureVolume; - newMeasureVolume.pVolume=NULL; - newMeasureVolume.strMeasureFileDir=""; - newMeasureVolume.measureType=CMeasureVolume::Unknown; - - measureVolumes.clear(); - for (int i=0; i> to update it if the file exists - CSparse2DGausDistMatrix zeroDensityMatrix(statisticsVolumeHeader.nXDIM,statisticsVolumeHeader.nYDIM,statisticsVolumeHeader.nNumMeasures); - - for (int nWhichSlice=0; nWhichSlice> vectorDensitySlices[nWhichSlice]; - ifs.close(); - } - else - { - bLoadedVolumeOK=false; - } - } - return(bLoadedVolumeOK); - } - - - void formMeasureVector(int nNiX,int nNiY,int nNiZ, TypeVectorFloat& vectorMeasurement) - { - vectorMeasurement.clear(); - int nMaxMeasureNum=measureVolumes.size(); - for (int nWhichMeasure=0; nWhichMeasure intensity %g has density %g\n", nTiX, nTiY, nTiZ,fMean, fVariance, measure[0], fDensity); - cout << cstrMsg; - - } - return(fDensity); - } - - // interpolate the density at the given talairach point for the measure given by the given native index point using the - // measures loaded and for the label loaded with loadMeasureDensityVolume() - float density(int nNiX,int nNiY,int nNiZ, float fTiX, float fTiY, float fTiZ, const TypeMatrixFloat& vectorCanonicalPointsForInterpolation, bool bDebugMeanVariance=false) - { - bool bDebug=false; - // get the measurement vector - TypeVectorFloat vectorMeasurement; - formMeasureVector(nNiX,nNiY,nNiZ,vectorMeasurement); - - if (bDebugMeanVariance) - { - char cstrMsg[500]; - sprintf(cstrMsg,"Point (%d,%d,%d) has its density interpolated from these voxels:\n", nNiX, nNiY, nNiZ); - cout << cstrMsg; - } - - // compute the value at each of the 8 strongly connected locations - TypeVectorFloat vectorValueAtTriplets; - for (int i=0; i<(int)vectorCanonicalPointsForInterpolation.size(); i++) - { - vectorValueAtTriplets.push_back(density(vectorMeasurement, - vectorCanonicalPointsForInterpolation[i][0], - vectorCanonicalPointsForInterpolation[i][1], - vectorCanonicalPointsForInterpolation[i][2], bDebugMeanVariance)); - - } -#if 0 - if (((nNiX==153) && (nNiY==131)) || - ((nNiX==89) && (nNiY==116)) || - ((nNiX==69) && (nNiY==32)) || - ((nNiX==124) && (nNiY==133)) ) - { - cout << "vectorValueAtTriplets=\n"; - printType(vectorValueAtTriplets); - bDebug=true; - } - -#endif - - - - - // interpolate these 8 strongly connected locations to get the value for the current floating point lcoation in talairach space - float fDensity=statisticsVolumeHeader.interpolateLinear(fTiX,fTiY,fTiZ,vectorCanonicalPointsForInterpolation,vectorValueAtTriplets, bDebug); - if (bDebugMeanVariance) - { - char cstrMsg[500]; - sprintf(cstrMsg,"Overall interpolated conditional density is %g\n", fDensity); - cout << cstrMsg; - } - - return(fDensity); - - } - - bool freeMeasureDensityVolume() - { - vectorDensitySlices.clear(); - return(true); - } - - // ==============================End For Baysian Classifie========================================================================== - - // NOTE: uses the number of measures defined in statisticsVolumeHeader to avoid forcing the user of this library to call - //setNumberOfMeasures first, plus the value is stored in the statistics volume header file anyway - bool loadSliceMeasureDensities(int nSliceNumber, int nWidth, int nHeight) - { - mapDensitySlices.clear(); - nCurrSliceNum=nSliceNumber; - // iterate over all slice numbers in labelLUT - TypeMapLUT::iterator it; - - for (it=labelLUT.getMapLUT().begin(); it!=labelLUT.getMapLUT().end(); it++) - { - // form the filename - char strFilename[500]; - int nWhichLabel=it->first; - sprintf(strFilename,"%s/Density-Slc%03d-Lab%03d.spmat",statisticsVolumeHeader.strStatisticsVolumeDirPath.c_str(),nCurrSliceNum,nWhichLabel); - - // load the sparse matrix - // create an initially zero prior and then use >> to update it if the file exists - CSparse2DGausDistMatrix zeroDensityMatrix(nWidth,nHeight,statisticsVolumeHeader.nNumMeasures); - - mapDensitySlices.insert(TypeMapSparse2DGausDistMatrix::value_type(nWhichLabel, zeroDensityMatrix)); - fstream ifs; - ifs.open(strFilename,ios::in | ios::nocreate); - if (ifs.good()) - { - ifs >> mapDensitySlices[nWhichLabel]; - ifs.close(); - } - } - return(true); - } - - - - bool writeSliceMeasureDensities() - { - - // loop over all slicePriors - TypeMapSparse2DGausDistMatrix::iterator it; - for (it=mapDensitySlices.begin(); it!=mapDensitySlices.end(); it++) - { - // form the filename - char strFilename[500]; - int nWhichLabel=it->first; - sprintf(strFilename,"%s/Density-Slc%03d-Lab%03d.spmat",statisticsVolumeHeader.strStatisticsVolumeDirPath.c_str(),nCurrSliceNum,nWhichLabel); - - fstream ofs; - ofs.open(strFilename,ios::out); - // write the sparse matrix out to disk - ofs << mapDensitySlices[nWhichLabel]; - ofs.close(); - } - - return(true); - } - - - - - - bool freeSliceMeasureDensities() - { - mapDensitySlices.clear(); - return(true); - } - - - - - TypeVectorFloat averageMeasureVectorAtPoints(TypeVectorNativeIndexPoints& vectorNativeIndexPoints) - { - TypeVectorFloat vectorAverageMeasure; - vectorAverageMeasure.clear(); - int nMaxMeasureNum=measureVolumes.size(); - for (int nWhichMeasure=0; nWhichMeasurefirst; - measureVector=averageMeasureVectorAtPoints(it->second.vectorNativeIndexPoints); - mapDensitySlices[nLabel].insertMeasure(measureVector,nTiX,nTiY,it->second.fFractionalArea); - } - } - }; - - return(true); - - } - - bool makeTestLabelConditionalDensitySlices() - { - unsigned char ucharLabel=1; - TypeVectorFloat vectFloatMeasureMean; - TypeMatrixFloat matrixFloatMeasureVariance; - float floatNewNumMeasuresEntered=100.0; - int nMaxMeasureNum=measureVolumes.size(); - - for (int x=0; x -extern "C" -{ + + #include "mri.h" -} + using namespace std; diff --git a/include/mri_ca_sparse3DMatrix.h b/include/mri_ca_sparse3DMatrix.h deleted file mode 100644 index 4accea6956b..00000000000 --- a/include/mri_ca_sparse3DMatrix.h +++ /dev/null @@ -1,317 +0,0 @@ -/** - * @file mri_ca_sparse3DMatrix.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef sparse3DMatrix_h -#define sparse3DMatrix_h - -#include -#include -#include -#include - -using namespace std; - - -/* - - Main Design Goals for Sparse Matrix: - 1 Must use zero bytes for zero-valued entries - 2 Want to minimize garbage collection thus no reallocating of arrays - - 3 Want access to be as fast as possible - 4 Next want insertions to be as fast as possible - - 5 Want to be able to insert new values at any point in the list - NOTE: Key values will not change in value - - Answer: - Use the STL map container because it meets goals 1,2,3 (logarithmic time based on number of nonzero entries in the Z direction) - That is have a map for each Z value (x*y maps are needed) - Goal 4 (log time insertion), 5 is satisfied - - Next Design goals: - write out the sparse matrix in binary form which takes little space on disk and can be read in quickly. - write out in an ascii form which can be loaded by matlab: see SparseLib++ from NIST for some code which does this - Cant use their library because they dont allow new non-zero entries to be inserted into the sparse matrix - - - - -*/ - -typedef map mapType; -typedef mapType* mapTypePtr; - -typedef unsigned long ulong; -typedef unsigned short ushort; -/* STL map methods -map -mymapType::iterator it; -insertion: - myMap[a key]=a value; - insert(mymapType::value_type(a key, a value) - -accessing values: - if myMap.find(a key)!=myMap.end() then - (myMap.find(a key))->fist=the key - (myMap.find(a key))->second=the value -Info: - size() - empty() - clear() -*/ -class CSparse3DMatrix -{ -public: - - /* - CSparse3DMatrix() - { - nXMAX=0; - nYMAX=0; - nZMAX=0; - } - */ - - CSparse3DMatrix(ushort nXDim, ushort nYDim, ushort nZDim) - { - nXMAX=nXDim; - nYMAX=nYDim; - nZMAX=nZDim; // only the first two dimensions must remain fixed - //arrMap=new mapType[nXMAX][nYMAX]; // wont work b/c it returns mapType (*)[nYMax] - - // Dynamic 2D array allocation - // allocate row arrays - arrMap=new mapTypePtr[nXMAX]; // returns mapTypePtr[nXMAX] - for (ushort x=0; x=0) && (x>=0) - { - if ( (it=arrMap[x][y].find(z)) != arrMap[x][y].end()) - { - nValue=++arrMap[x][y][z]; - } - else - { - nValue=arrMap[x][y][z]=1; - } - - - if (z+1>nZMAX) - { - nZMAX=z+1; - } - } - return nValue; - - } - - - // retrieve values at specific location - ulong operator()(ushort x, ushort y, ushort z) - { - ulong nValue=0; - mapType::iterator it; - - if ((x<=nXMAX-1) && (y<=nYMAX-1)) // && (y>=0) && (x>=0) - { - if ( (it=arrMap[x][y].find(z)) != arrMap[x][y].end()) - { - nValue=arrMap[x][y][z]; - } - } - return nValue; - } - - - - -private: - ushort nXMAX, nYMAX, nZMAX; - mapType** arrMap; - - friend istream& operator>>(istream&,CSparse3DMatrix&); - friend ostream& operator<<(ostream&,CSparse3DMatrix&); - friend ostream& print(ostream&, CSparse3DMatrix&); - -}; - - -/* -on Linux / intel 686: -Size of pointer=4 - -Size of short=2 -Size of u-short=2 -Size of int=4 -Size of unsigned int=4 -Size of long int=4 -Size of float=4 -Size of double =8 - */ - - - - - - -istream& operator>>(istream& is, CSparse3DMatrix& mat) -{ - // Read in from the stream as binary data - is.read(&mat.nXMAX, sizeof(mat.nXMAX)); - is.read(&mat.nYMAX, sizeof(mat.nYMAX)); - is.read(&mat.nZMAX, sizeof(mat.nZMAX)); - - // Dynamic 2D array allocation - // allocate row arrays - mat.arrMap=new mapTypePtr[mat.nXMAX]; // returns mapTypePtr[nXMAX] - for (ushort x=0; xfirst), sizeof(it->first)); - os.write((unsigned char *)&(it->second), sizeof(it->second)); - } - - } - return os; -} - -ostream& print(ostream& os, CSparse3DMatrix& mat) -{ - // write out to the stream as binary data - os << "Dimensions: (x,y,z) = (" << mat.nXMAX << ", " << mat.nYMAX << ", " << mat.nZMAX << ") \n"; - - - mapType::iterator it; - ushort x,y; - for (x=0; xfirst << ", " << it->second << "} "; - } - os << "\n"; - - } - return os; -} - - - -/* -// a PriorDist holds the probability of a label at a given location -class CPriorDist -{ - - probability(x,y,z) - - - - public: - - - -} - - -// now define a collection (vector) of prior distributions -class CPriorDists -{ - -} - -*/ - - -#endif - - diff --git a/include/mri_ca_util.h b/include/mri_ca_util.h index 2b3e20d61ff..4132fdfeb5e 100644 --- a/include/mri_ca_util.h +++ b/include/mri_ca_util.h @@ -36,11 +36,11 @@ #include #include -extern "C" -{ + + #include "mri.h" -} + using namespace std ; diff --git a/include/mri_transform.h b/include/mri_transform.h deleted file mode 100644 index de5d6cb278f..00000000000 --- a/include/mri_transform.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file mri_transform.h - * @brief transform utils - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#ifndef mri_transform_h -#define mri_transform_h - -/* need to set the size of the volume - and its resolution */ -void trans_SetBounds ( float ifStartX, float ifEndX, - float ifStartY, float ifEndY, - float ifStartZ, float ifEndZ ); - -void trans_SetResolution ( float ifSizeX, float ifSizeY, float ifSizeZ ); - -/* converts ras coords to - voxel coords and back */ -void trans_RASToVoxel -( double irX, double irY, double irZ, /* incoming ras coords */ - double *onX, double *onY, double *onZ ); /* outgoing voxel coords */ -void trans_VoxelToRAS -( double inX, double inY, double inZ, /* incoming voxel coords */ - double *orX, double *orY, double *orZ ); /* outgoing RAS coords */ -void trans_RASToVoxelIndex -( double irX, double irY, double irZ, /* incoming ras coords */ - int *onX, int *onY, int *onZ ); /* outgoing voxel coords */ -void trans_VoxelIndexToRAS ( int inVoxX, int inVoxY, int inVoxZ, - double *orRASX, double *orRASY, double *orRASZ ) ; - -#endif diff --git a/include/mriclass.h b/include/mriclass.h index cece420c0da..a6b1dfde944 100644 --- a/include/mriclass.h +++ b/include/mriclass.h @@ -28,9 +28,7 @@ #define MRICLASS_H #include "classify.h" -#include "backprop.h" #include "gclass.h" -#include "artmap.h" #include "mri.h" #include "rbf.h" @@ -108,8 +106,6 @@ RBF_PARMS ; typedef union { - BACKPROP *bp ; - ARTMAP *artmap ; GCLASSIFY *gc ; RBF *rbf ; } CL_UNION ; @@ -145,19 +141,19 @@ int MRInormalizePriors(MRI *mri_priors) ; int MRICupdateStatistics(MRIC *mric, int round, MRI *mri_src, MRI *mri_wm, MRI_REGION *box) ; int MRICcomputeStatistics(MRIC *mric, int round) ; -char *MRICclassName(MRIC *mric, int round, int classno) ; +const char *MRICclassName(MRIC *mric, int round, int classno) ; int MRICdump(FILE *fp, MRIC *mric) ; -char *MRICfeatureName(MRIC *mric, int round, int feature_number) ; +const char *MRICfeatureName(MRIC *mric, int round, int feature_number) ; int MRICfeatureCode(MRIC *mric, int round, int feature_number) ; int MRICfeatureNumberCode(int feature_number) ; int MRICfeatureNumber(MRIC *mric, int round, int feature_code) ; -char *MRICfeatureNumberToName(int feature_number) ; +const char *MRICfeatureNumberToName(int feature_number) ; int MRICexamineTrainingSet(MRIC *mric, char *file_name, int round) ; -int MRICbuildScatterPlot(MRIC *mric, int class, MATRIX *m_scatter, +int MRICbuildScatterPlot(MRIC *mric, int classnum, MATRIX *m_scatter, char *training_file_name) ; int MRICsetRegionSize(MRIC *mric, int rwidth, int rheight, int rdepth) ; int MRICresetRegionSize(MRIC *mric) ; -extern char *class_names[] ; +extern const char *class_names[] ; #endif diff --git a/include/mris_expand.h b/include/mris_expand.h deleted file mode 100644 index d14c4e6b2c9..00000000000 --- a/include/mris_expand.h +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @file mris_expand.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef _MRIS_EXPAND_H -#define _MRIS_EXPAND_H - -#define MAXVERTICES 10000 -#define MAXFACES 10000 - -#define TRUE 1 -#define FALSE 0 - -#define SQR(x) ((x)*(x)) - -/* FUNCTION PROTOTYPES */ - -static void write_geometry(char *fname) ; -static void read_geometry(char *fname); -static void compute_normals(void); -static void normal_face(int f,float *n); -static void expand_geometry(float mm); - -/* TYPE DEFINITIONS */ - -typedef struct ss_vertex_type_ -{ - float x,y,z; - float nx,ny,nz; - float xb,yb,zb; - float nxb,nyb,nzb; - float ox,oy,oz; - float dx,dy,dz; - float mx,my,mz; - float nc,onc,snc; - float thickness; - int vnum; - int v[10]; - int fnum; - int f[10]; -} -ss_vertex_type; - -#endif diff --git a/include/mrisbiorthogonalwavelets.h b/include/mrisbiorthogonalwavelets.h deleted file mode 100644 index 526093474fa..00000000000 --- a/include/mrisbiorthogonalwavelets.h +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file mrisbiorthogonalwavelets.c - * @brief Routines for biothogonal wavelets transformation. - * - * References: - * P. Schroder and W. Sweldens. Spherical wavelets: Texture processing. - * In Rendering Techniques '95. Springer Verlag, 1995. - * P. Schroder and W. Sweldens. Spherical wavelets: Efficiently representing - * functions on the sphere. Computer Graphics Proceedings (SIGGRAPH 95), - * pages 161-172, 1995. - */ -/* - * Original Author: Peng Yu - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.2 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef MRISBIORTHOGONALWAVELETS_H -#define MRISBIORTHOGONALWAVELETS_H - -#include -#include -#include -#include -#include -#include -#include -#include "mri.h" -#include "mrisurf.h" -#include "icosahedron.h" -#include "const.h" -#include "diag.h" -#include "error.h" -#include "macros.h" -#include "proto.h" -#include "timer.h" -#include "mrinorm.h" -#include "cma.h" -#include "version.h" -#include "error.h" -#include "matrix.h" - -static MRI_SURFACE *wavelet_analysis_curv(MRI_SURFACE *mris_out, int order) ; -static MRI_SURFACE *wavelet_analysis_vec(MRI_SURFACE *mris_out, int order); -static MRI_SURFACE *wavelet_synthesis_curv(MRI_SURFACE *mris_out, int order) ; -static MRI_SURFACE *wavelet_synthesis_vec(MRI_SURFACE *mris_out, int order); - -#endif diff --git a/include/mrisurf.h b/include/mrisurf.h index 4b77751039a..010125ab859 100644 --- a/include/mrisurf.h +++ b/include/mrisurf.h @@ -27,7 +27,7 @@ -#include "minc_volume_io.h" +#include "minc.h" #include "const.h" #include "matrix.h" #include "dmatrix.h" @@ -495,10 +495,7 @@ typedef struct vertex_type_ #undef ELTX #undef SEP -#if defined(__cplusplus) - // C++ requires const members be initialized - vertex_type_() : dist(nullptr), dist_orig(nullptr), x(0), y(0), z(0), origx(0), origy(0), origz(0) {} -#endif + vertex_type_() : dist(nullptr), dist_orig(nullptr), x(0), y(0), z(0), origx(0), origy(0), origz(0) {} } vertex_type, VERTEX ; @@ -1123,10 +1120,8 @@ typedef struct INTEGRATION_PARMS double stressthresh ; int explode_flag ; -#ifdef __cplusplus INTEGRATION_PARMS() : fp(NULL) {} INTEGRATION_PARMS(FILE* file) : fp(file) {} -#endif } INTEGRATION_PARMS ; @@ -1614,7 +1609,7 @@ MRI_SP *MRISPclone(MRI_SP *mrisp_src) ; MRI_SP *MRISPalloc(float scale, int nfuncs) ; int MRISPfree(MRI_SP **pmrisp) ; MRI_SP *MRISPread(char *fname) ; -int MRISPwrite(MRI_SP *mrisp, char *fname) ; +int MRISPwrite(MRI_SP *mrisp, const char *fname) ; int MRISwriteArea(MRI_SURFACE *mris,const char *sname) ; int MRISwriteMarked(MRI_SURFACE *mris,const char *sname) ; @@ -1999,7 +1994,7 @@ MRIS* MRISextractMarkedVertices(MRIS *mris); MRIS* MRISremoveRippedSurfaceElements(MRIS *mris); MRI_SURFACE *MRIScorrectTopology(MRI_SURFACE *mris, MRI *mri, - MRI *mri_wm, int nsmooth, TOPOLOGY_PARMS *parms, char *defectbasename); + MRI *mri_wm, int nsmooth, TOPOLOGY_PARMS *parms, const char *defectbasename); int MRISsmoothOnSphere(MRIS* mris, int niters); int mrisCountIntersectingFaces(MRIS *mris, int*flist , int nfaces); @@ -2211,8 +2206,8 @@ int MRISorigAreaToCurv(MRI_SURFACE *mris) ; int MRISareaToCurv(MRI_SURFACE *mris) ; int MRISnormalize(MRI_SURFACE *mris, int dof, int which) ; -int MRIScopyMRI(MRIS *Surf, MRI *Src, int Frame, char *Field); -MRI *MRIcopyMRIS(MRI *mri, MRIS *surf, int Frame, char *Field); +int MRIScopyMRI(MRIS *Surf, MRI *Src, int Frame, const char *Field); +MRI *MRIcopyMRIS(MRI *mri, MRIS *surf, int Frame, const char *Field); MRI *MRISsmoothMRI(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MRI *Targ); MRI *MRISsmoothMRIFast(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MRI *Targ); @@ -2452,7 +2447,7 @@ void cprints( ); void cprintd( - char* apch_left, + const char* apch_left, int a_right ); @@ -2474,7 +2469,7 @@ short VECTOR_elementIndex_find( short MRIS_vertexProgress_print( MRIS* apmris, int avertex, - char* apch_message + const char* apch_message ); int FACE_vertexIndexAtMask_find( @@ -2752,11 +2747,11 @@ char* MRISexportVertexRipflags(MRIS* mris) ; // Edges are implicit (MRI_EDGE is more than just an edge), and are created by telling each of the end vertices that they are neighbors. // Faces get associated with three edges associated with three vertices (VERTICES_PER_FACE is 3) // -#define mrisCheckVertexVertexTopology(_MRIS) true // mrisCheckVertexVertexTopologyWkr(__FILE__,__LINE__,_MRIS,false) -#define mrisCheckVertexFaceTopology(_MRIS) true // mrisCheckVertexFaceTopologyWkr (__FILE__,__LINE__,_MRIS,false) bool mrisCheckVertexVertexTopologyWkr(const char* file, int line, MRIS const * mris, bool always); bool mrisCheckVertexFaceTopologyWkr (const char* file, int line, MRIS const * mris, bool always); - // includes a mrisCheckVertexVertexTopology check +inline static bool returnTrue() { return true; }; +#define mrisCheckVertexFaceTopology(_MRIS) returnTrue() // mrisCheckVertexFaceTopologyWkr (__FILE__,__LINE__,_MRIS,false) +#define mrisCheckVertexVertexTopology(_MRIS) returnTrue() // mrisCheckVertexVertexTopologyWkr(__FILE__,__LINE__,_MRIS,false) // Vertices // diff --git a/include/mrisurf_base.h b/include/mrisurf_base.h index 2e4523bf1b1..88e29f940bf 100644 --- a/include/mrisurf_base.h +++ b/include/mrisurf_base.h @@ -76,7 +76,7 @@ extern int fix_vertex_area; #include "error.h" #include "fio.h" #include "fnv_hash.h" -#include "gifti_local.h" +#include "gifti.h" #include "icosahedron.h" #include "machine.h" #include "macros.h" @@ -92,7 +92,7 @@ extern int fix_vertex_area; #include "tags.h" #include "talairachex.h" #include "timer.h" -#include "topology/topo_parms.h" +#include "topo_parms.h" #include "transform.h" #include "tritri.h" #include "utils.h" @@ -208,7 +208,6 @@ static int project_point_onto_sphere(float cx, float cy, float cz, float radius, #define MAX_NBHD_VERTICES 20000 // must fit in short because VERTEX.vnum etc are short /*---------------------------- STRUCTURES -------------------------*/ - /*---------------------------- CONSTANTS -------------------------*/ #define D_DIST 0.1 // sampling distance along tangent plane for computing derivatives diff --git a/include/mrisurf_metricProperties.h b/include/mrisurf_metricProperties.h index 64a73f5bad3..5b2619d98de 100644 --- a/include/mrisurf_metricProperties.h +++ b/include/mrisurf_metricProperties.h @@ -114,7 +114,7 @@ int mrisMarkIntersections(MRIS *mris); #define BORDER_VERTEX TRIANGLE_VERTEX /* part of a triangle! */ #define USED_VERTEX 5 /* used in the final tessellation */ -void mrisDumpFace(MRIS *mris, int fno, FILE *fp); +void mrisDumpFace(MRIS const * mris, int fno, FILE *fp); int MRIScomputeAllDistances (MRIS *mris); diff --git a/include/mrisutils.h b/include/mrisutils.h index 079de481003..afe0d97d3f5 100644 --- a/include/mrisutils.h +++ b/include/mrisutils.h @@ -117,13 +117,13 @@ int MRISscanner2Tkr(MRIS *mris); int MRIStkr2Scanner(MRIS *mris); int ComputeMRISvolumeTH3(char *subject, char *hemi, int DoMask, char *outfile); -LABEL2SURF *L2Salloc(int nsurfs, char *subject); +LABEL2SURF *L2Salloc(int nsurfs, const char *subject); int L2Sinit(LABEL2SURF *l2s); int L2SaddPoint(LABEL2SURF *l2s, double col, double row, double slice, int PointType, int Operation); int L2SaddVoxel(LABEL2SURF *l2s, double col, double row, double slice, int nsegs, int Operation); int L2Sfree(LABEL2SURF **pl2s); int L2SimportLabel(LABEL2SURF *l2s, LABEL *label, int surfno); -int L2Stest(char *subject); +int L2Stest(const char *subject); int MRISeulerNoSeg(MRI_SURFACE *mris, MRI *surfseg, int segno, int *pnvertices, int *pnfaces, int *pnedges, int *pv0); diff --git a/include/mthread.h b/include/mthread.h deleted file mode 100644 index 38d2163a39c..00000000000 --- a/include/mthread.h +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file mthread.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)mthread.h 1.2 - 3/24/94 -*/ -/*------------------------------------------------------------------------ - File Name: mthread.h - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: prototypes for machine-specific functions that are - required by the multi-threader. These functions should - be implemented separately on each platform. - -------------------------------------------------------------------------*/ -#ifndef MACH_THREAD_H -#define MACH_THREAD_H - -#ifdef ANSI -int MachThreadInit(int nthreads, int stacksize, int npriorities) ; -int MachThreadStart(char *name, void (*func)(int iTid, void *parm), int iTid, - void *parm, int priority) ; -int MachThreadYield(int iTid) ; -int MachThreadKill(int iTid) ; -int MachThreadSleep(int iTid, long lUsec) ; -int MachThreadSuspend(int iTid) ; -int MachThreadResume(int iTid) ; -int MachThreadGetTid(void) ; -void MachThreadExit(int status) ; - -#else - -int MachThreadInit() ; -int MachThreadStart() ; -int MachThreadYield() ; -int MachThreadKill() ; -int MachThreadSleep() ; -int MachThreadSuspend() ; -int MachThreadResume() ; -int MachThreadGetTid() ; -void MachThreadExit() ; - -#endif - -#endif diff --git a/include/numerics.h b/include/numerics.h index 4568f334143..56f2d021302 100644 --- a/include/numerics.h +++ b/include/numerics.h @@ -25,11 +25,6 @@ #ifndef NUMERICS_H_ #define NUMERICS_H_ -#ifdef __cplusplus -extern "C" -{ -#endif - #include "matrix.h" @@ -189,8 +184,4 @@ extern "C" double sc_cdf_chisq_Q(double x, double nu); double sc_cdf_chisq_Qinv(double Q, double nu); -#ifdef __cplusplus -} -#endif - #endif /*NUMERICS_H_*/ diff --git a/include/omp_support.h b/include/omp_support.h deleted file mode 100644 index ca660f6ca5a..00000000000 --- a/include/omp_support.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#ifndef HAVE_OPENMP - -#define OMP_FOR_BEGIN -#define OMP_FOR_END - -#else - -#include "romp_support.h" - -#define OMP_PFOR_BEGIN -#define OMP_PFOR_END - -#endif diff --git a/include/path.h b/include/path.h index 1605a06529d..6bf9bb81fa9 100644 --- a/include/path.h +++ b/include/path.h @@ -27,7 +27,6 @@ #ifndef PATHS_INCLUDED #define PATHS_INCLUDED -#define _GNU_SOURCE #include #ifdef Darwin // Mac OS X doesnt have gnulib, so it doesn't have getline, diff --git a/include/pbm.h b/include/pbm.h deleted file mode 100644 index c8ff545a970..00000000000 --- a/include/pbm.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file pbm.h - * @brief header file for libpbm portable bitmap library - * - */ - -#ifndef _PBM_H_ -#define _PBM_H_ - -#include "pbmplus.h" - -typedef unsigned char bit; -#define PBM_WHITE 0 -#define PBM_BLACK 1 - - -/* Magic constants. */ - -#define PBM_MAGIC1 'P' -#define PBM_MAGIC2 '1' -#define RPBM_MAGIC2 '4' -#define PBM_FORMAT (PBM_MAGIC1 * 256 + PBM_MAGIC2) -#define RPBM_FORMAT (PBM_MAGIC1 * 256 + RPBM_MAGIC2) -#define PBM_TYPE PBM_FORMAT - - -/* Macro for turning a format number into a type number. */ - -#define PBM_FORMAT_TYPE(f) ((f) == PBM_FORMAT || (f) == RPBM_FORMAT ? PBM_TYPE : -1) - - -/* Declarations of routines. */ - -void pbm_init ARGS(( int* argcP, char* argv[] )); - -#define pbm_allocarray( cols, rows ) ((bit**) pm_allocarray( cols, rows, sizeof(bit) )) -#define pbm_allocrow( cols ) ((bit*) pm_allocrow( cols, sizeof(bit) )) -#define pbm_freearray( bits, rows ) pm_freearray( (char**) bits, rows ) -#define pbm_freerow( bitrow ) pm_freerow( (char*) bitrow ) - -bit** pbm_readpbm ARGS(( FILE* file, int* colsP, int* rowsP )); -void pbm_readpbminit ARGS(( FILE* file, int* colsP, int* rowsP, int* formatP )); -void pbm_readpbmrow ARGS(( FILE* file, bit* bitrow, int cols, int format )); -char* pm_read_unknown_size ARGS(( FILE* file, long* buf )); - -void pbm_writepbm ARGS(( FILE* file, bit** bits, int cols, int rows, int forceplain )); -void pbm_writepbminit ARGS(( FILE* file, int cols, int rows, int forceplain )); -void pbm_writepbmrow ARGS(( FILE* file, bit* bitrow, int cols, int forceplain )); - -#endif /*_PBM_H_*/ diff --git a/include/pbmplus.h b/include/pbmplus.h deleted file mode 100644 index a9de6f533d4..00000000000 --- a/include/pbmplus.h +++ /dev/null @@ -1,221 +0,0 @@ -/** - * @file pbmplus.h - * @brief header file for PBM, PGM, PPM, and PNM - * - */ -/* - * CVS Revision Info: - * $Author: mreuter $ - * $Date: 2009/03/04 19:20:36 $ - * $Revision: 1.6 $ - * -** Copyright (C) 1988, 1989, 1991 by Jef Poskanzer. -** -** Permission to use, copy, modify, and distribute this software and its -** documentation for any purpose and without fee is hereby granted, provided -** that the above copyright notice appear in all copies and that both that -** copyright notice and this permission notice appear in supporting -** documentation. This software is provided "as is" without express or -** implied warranty. -*/ - -#ifndef _PBMPLUS_H_ -#define _PBMPLUS_H_ - -#include -#include -#include - -#if defined(USG) || defined(SVR4) -#define SYSV -#endif -#if ! ( defined(BSD) || defined(SYSV) || defined(MSDOS) ) -/* CONFIGURE: If your system is >= 4.2BSD, set the BSD option; if you're a -** System V site, set the SYSV option; and if you're IBM-compatible, set -** MSDOS. If your compiler is ANSI C, you're probably better off setting -** SYSV - all it affects is string handling. -*/ -#define BSD -/* #define SYSV */ -/* #define MSDOS */ -#endif - -/* CONFIGURE: If you want to enable writing "raw" files, set this option. -** "Raw" files are smaller, and much faster to read and write, but you -** must have a filesystem that allows all 256 ASCII characters to be read -** and written. You will no longer be able to mail P?M files without -** using uuencode or the equivalent, or running the files through pnmnoraw. -** Note that reading "raw" files works whether writing is enabled or not. -*/ -#define PBMPLUS_RAWBITS - -/* CONFIGURE: PGM can store gray values as either bytes or shorts. For most -** applications, bytes will be big enough, and the memory savings can be -** substantial. However, if you need more than 8 bits of grayscale resolution, -** then define this symbol. -*/ -/* #define PGM_BIGGRAYS */ - -/* CONFIGURE: Normally, PPM handles a pixel as a struct of three grays. -** If grays are stored in bytes, that's 24 bits per color pixel; if -** grays are stored as shorts, that's 48 bits per color pixel. PPM -** can also be configured to pack the three grays into a single longword, -** 10 bits each, 30 bits per pixel. -** -** If you have configured PGM with the PGM_BIGGRAYS option, AND you don't -** need more than 10 bits for each color component, AND you care more about -** memory use than speed, then this option might be a win. Under these -** circumstances it will make some of the programs use 1.5 times less space, -** but all of the programs will run about 1.4 times slower. -** -** If you are not using PGM_BIGGRAYS, then this option is useless -- it -** doesn't save any space, but it still slows things down. -*/ -/* #define PPM_PACKCOLORS */ - -/* CONFIGURE: uncomment this to enable debugging checks. */ -/* #define DEBUG */ - -#if __GLIBC__ >= 2 - -#include -#include /* random is defined here. */ - -#else /*__GLIBC__*/ - -#ifdef SYSV - -#include - -#define index(s,c) strchr(s,c) -#define rindex(s,c) strrchr(s,c) -#define srandom(s) srand(s) -#define random rand -#define bzero(dst,len) memset(dst,0,len) -#define bcopy(src,dst,len) memcpy(dst,src,len) -#define bcmp memcmp -extern void srand(); -extern int rand(); - -#else /*SYSV*/ -#ifdef __hpux -#define srandom(s) srand(s) -#define random rand -#else - -#include -#ifndef Windows_NT -extern void srandom(); -extern long random(); -#endif - -#endif /*__hpux*/ -#endif /*SYSV*/ -#endif /*__GLIBC__*/ - -extern int atoi(); -extern void exit(); -extern long time(); -/* vicka extern int write();*/ - -/* CONFIGURE: On some systems, malloc.h doesn't declare these, so we have -** to do it. On other systems, for example HP/UX, it declares them -** incompatibly. And some systems, for example Dynix, don't have a -** malloc.h at all. A sad situation. If you have compilation problems -** that point here, feel free to tweak or remove these declarations. -*/ -#ifndef Darwin -#include -#else -#include "proto.h" -#endif -/* extern char* malloc(); */ -/* extern char* realloc(); */ -/* extern char* calloc(); */ - -/* CONFIGURE: Some systems don't have vfprintf(), which we need for the -** error-reporting routines. If you compile and get a link error about -** this routine, uncomment the first define, which gives you a vfprintf -** that uses the theoretically non-portable but fairly common routine -** _doprnt(). If you then get a link error about _doprnt, or -** message-printing doesn't look like it's working, try the second -** define instead. -*/ -/* #define NEED_VFPRINTF1 */ -/* #define NEED_VFPRINTF2 */ - -/* End of configurable definitions. */ - - -#undef max -#define max(a,b) ((a) > (b) ? (a) : (b)) -#undef min -#define min(a,b) ((a) < (b) ? (a) : (b)) -#undef abs -#define abs(a) ((a) >= 0 ? (a) : -(a)) -#undef odd -#define odd(n) ((n) & 1) - - -/* Definitions to make PBMPLUS work with either ANSI C or C Classic. */ - -#if __STDC__ -#define ARGS(alist) alist -#else /*__STDC__*/ -#define ARGS(alist) () -#define const -#endif /*__STDC__*/ - - -/* Initialization. */ - -void pm_init ARGS(( int* argcP, char* argv[] )); - - -/* Variable-sized arrays definitions. */ - -char** pm_allocarray ARGS(( int cols, int rows, int size )); -char* pm_allocrow ARGS(( int cols, int size )); -void pm_freearray ARGS(( char** its, int rows )); -void pm_freerow ARGS(( char* itrow )); - - -/* Case-insensitive keyword matcher. */ - -int pm_keymatch ARGS(( char* str, char* keyword, int minchars )); - - -/* Log base two hacks. */ - -int pm_maxvaltobits ARGS(( int maxval )); -int pm_bitstomaxval ARGS(( int bits )); - - -/* Error handling definitions. */ - -void pm_message ARGS(( char*, ... )); -void pm_error ARGS(( char*, ... )); /* doesn't return */ -void pm_perror ARGS(( char* reason )); /* doesn't return */ -void pm_usage ARGS(( char* usage )); /* doesn't return */ - - -/* File open/close that handles "-" as stdin and checks errors. */ - -FILE* pm_openr ARGS((const char* name )); -FILE* pm_openw ARGS((const char* name )); -void pm_close ARGS(( FILE* f )); - - -/* Endian I/O. */ - -int pm_readbigshort ARGS(( FILE* in, short* sP )); -int pm_writebigshort ARGS(( FILE* out, short s )); -int pm_readbiglong ARGS(( FILE* in, long* lP )); -int pm_writebiglong ARGS(( FILE* out, long l )); -int pm_readlittleshort ARGS(( FILE* in, short* sP )); -int pm_writelittleshort ARGS(( FILE* out, short s )); -int pm_readlittlelong ARGS(( FILE* in, long* lP )); -int pm_writelittlelong ARGS(( FILE* out, long l )); - - -#endif /*_PBMPLUS_H_*/ diff --git a/include/pdf.h b/include/pdf.h index 04dc50b7fcf..444b038d2de 100644 --- a/include/pdf.h +++ b/include/pdf.h @@ -23,15 +23,9 @@ * */ - - #ifndef PDF_INC #define PDF_INC -#if defined(__cplusplus) -extern "C" { -#endif - unsigned long PDFtodSeed(void); double PDFgaussian(void); double PDFerlang(int order); @@ -39,9 +33,4 @@ int PDFloadCDF(char *fname, double **xcdf, double **cdf, int *ncdf); double PDFsampleCDF(double *xcdf, double *cdf, int ncdf); int PDFsearchOrderedTable(double u, double *y, int ny); - -#if defined(__cplusplus) -}; -#endif - #endif //#ifndef PDF_INC diff --git a/include/pgm.h b/include/pgm.h deleted file mode 100644 index 5167ba0762c..00000000000 --- a/include/pgm.h +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file pgm.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* pgm.h - header file for libpgm portable graymap library -*/ - -#ifndef _PGM_H_ -#define _PGM_H_ - -#include "pbm.h" - -#ifdef PGM_BIGGRAYS -typedef unsigned short gray; -#define PGM_MAXMAXVAL 65535 -#else /*PGM_BIGGRAYS*/ -typedef unsigned char gray; -#define PGM_MAXMAXVAL 255 -#endif /*PGM_BIGGRAYS*/ - - -/* Magic constants. */ - -#define PGM_MAGIC1 'P' -#define PGM_MAGIC2 '2' -#define RPGM_MAGIC2 '5' -#define PGM_FORMAT (PGM_MAGIC1 * 256 + PGM_MAGIC2) -#define RPGM_FORMAT (PGM_MAGIC1 * 256 + RPGM_MAGIC2) -#define PGM_TYPE PGM_FORMAT - - -/* Macro for turning a format number into a type number. */ - -#define PGM_FORMAT_TYPE(f) ((f) == PGM_FORMAT || (f) == RPGM_FORMAT ? PGM_TYPE : PBM_FORMAT_TYPE(f)) - - -/* Declarations of routines. */ - -void pgm_init ARGS(( int* argcP, char* argv[] )); - -#define pgm_allocarray( cols, rows ) ((gray**) pm_allocarray( cols, rows, sizeof(gray) )) -#define pgm_allocrow( cols ) ((gray*) pm_allocrow( cols, sizeof(gray) )) -#define pgm_freearray( grays, rows ) pm_freearray( (char**) grays, rows ) -#define pgm_freerow( grayrow ) pm_freerow( (char*) grayrow ) - -gray** pgm_readpgm ARGS(( FILE* file, int* colsP, int* rowsP, gray* maxvalP )); -void pgm_readpgminit ARGS(( FILE* file, int* colsP, int* rowsP, gray* maxvalP, int* formatP )); -void pgm_readpgmrow ARGS(( FILE* file, gray* grayrow, int cols, gray maxval, int format )); - -void pgm_writepgm ARGS(( FILE* file, gray** grays, int cols, int rows, gray maxval, int forceplain )); -void pgm_writepgminit ARGS(( FILE* file, int cols, int rows, gray maxval, int forceplain )); -void pgm_writepgmrow ARGS(( FILE* file, gray* grayrow, int cols, gray maxval, int forceplain )); - -extern gray pgm_pbmmaxval; -/* This is the maxval used when a PGM program reads a PBM file. Normally -** it is 1; however, for some programs, a larger value gives better results -*/ - -#endif /*_PGM_H_*/ diff --git a/include/pixrect/bw2var.h b/include/pixrect/bw2var.h deleted file mode 100644 index 29fb75ef020..00000000000 --- a/include/pixrect/bw2var.h +++ /dev/null @@ -1,40 +0,0 @@ -/* @(#)bw2var.h 1.11 88/02/08 SMI */ - -/* - * Copyright (c) 1986 by Sun Microsystems, Inc. - */ - -#ifndef bw2var_DEFINED -#define bw2var_DEFINED - -/* - * bw2 -- monochrome frame buffer - */ - -/* standard resolution */ -#define BW2SIZEX 1152 -#define BW2SIZEY 900 -#define BW2BYTES (BW2SIZEX*BW2SIZEY/8) - -#define BW2SQUARESIZEX 1024 -#define BW2SQUARESIZEY 1024 -#define BW2SQUAREBYTES (BW2SQUARESIZEX*BW2SQUARESIZEY/8) - -/* high resolution (bw2h) */ -#define BW2HSIZEX 1600 -#define BW2HSIZEY 1280 -#define BW2HBYTES (BW2HSIZEX*BW2HSIZEY/8) - -#define BW2HSQUARESIZEX 1440 -#define BW2HSQUARESIZEY 1440 -#define BW2HSQUAREBYTES (BW2HSQUARESIZEX*BW2HSQUARESIZEY/8) - - -extern struct pixrectops bw2_ops; - -#ifndef KERNEL -struct pixrect *bw2_make(); -int bw2_destroy(); -#endif - -#endif bw2var_DEFINED diff --git a/include/pixrect/cg12_var.h b/include/pixrect/cg12_var.h deleted file mode 100644 index 05543de36e5..00000000000 --- a/include/pixrect/cg12_var.h +++ /dev/null @@ -1,138 +0,0 @@ -/* @(#)cg12_var.h 1.12 of 5/9/91 SMI */ - -/* Copyright 1990 by Sun Microsystems, Inc. */ - -/* Sun Color Graphics board 12 (CG12) */ - -#ifndef cg12_var_DEFINED -#define cg12_var_DEFINED - -#include -#include -#include -#include -#include -#include -#include /* colormapseg */ - -#define CG12_NFBS 6 /* number of frame buffers in a CG12 */ - -/* description of single CG12 frame buffer */ - -struct cg12fb -{ - short group; /* plane group implemented */ - short depth; /* depth, bits */ - struct mprp_data mprp; /* memory pixrect data */ -}; - -/* CG12 Pixrect private data */ - -struct cg12_data -{ - /* first make it look like a gp device */ - - struct cg2fb *cgpr_va; /* backward source compatible */ - caddr_t gp_shmem; /* pointer to shared memory */ - int cgpr_fd; /* primary flag */ - int cgpr_planes; /* color bit plane mask reg */ - struct pr_pos cgpr_offset; /* pixrect offset */ - short cg2_index; /* cg2 board index */ - char minordev; /* true minor dev to stuff into GP */ - int gbufflag; /* gbuffer flag */ - int ioctl_fd; /* the fd to talk to the driver with */ - int ncmd; /* length of cmdver array */ - u_char *cmdver; /* version #'s for each command */ - int flags; /* misc options */ - int linebytes; /* bytes per line (pixel mode) */ - int fbtype; /* which cg is bound */ - - /* then make it look like a memory device with multiple plane groups */ - - struct mprp_data mprp; /* memory pixrect simulator */ - int cg12_flags; /* misc. flags */ - int planes; /* current group and mask */ - int fd; /* file descriptor */ - short active; /* active fb no. */ - - /* finally get some cg12 specific portions in */ - - struct cg12_ctl_sp *ctl_sp; - struct cg12fb fb[CG12_NFBS]; /* frame buffer info */ - struct fb_wid_dbl_info wid_dbl_info; /* window id */ - int windowfd; -}; - -/* cg12 specific constants */ - -/* - There are 256 pixels of dither data. The framebuffer is being addressed - by an int ptr. The framebuffer is in 4 bits/pixel mode. Hence each - int points to 8 contiguous pixels. Hence the offset from the base of - the framebuffer is (num dith pixels + num solid pixels + num hollow - pixels)/8. See below. - - note, if the size of any of these sections is changed in the cg12 - microcode, then changes need to be propogated here too. */ - -#define CG12_FB_SIZE (CG12_WIDTH * CG12_HEIGHT) - -/* amount to offset from beginning of offscreen memory for dither data */ -#define CG12_DITHER_SIZE 256 - -/* amount to offset from beginning of offscreen memory for solid pattern data */ -#define CG12_SOLID_PAT_SIZE 32 - -/* amount to offset from beginning of offscreen memory for hollow pattern data */ -#define CG12_HOLLOW_PAT_SIZE 32 - -#define CG12_OFFSCREEN_START ((CG12_FB_SIZE + CG12_DITHER_SIZE + \ - CG12_SOLID_PAT_SIZE + CG12_HOLLOW_PAT_SIZE) >> 3) - -/* HACCESS value for 4 bits/pixel when loading offscreen VRAM */ - -#define CG12_OS_HACCESS 0x22 - -/* PLN_WR_MASK value for loading lower 4bits of each DPU offscreen VRAM */ - -#define CG12_OS_PLN_WR_MASK 0x000F0F0F - -/* useful macros */ - -#define cg12_d(pr) ((struct cg12_data *) ((pr)->pr_data)) - -#define CG12_PR_TO_MEM(src, mem) \ - if (src && src->pr_ops != &mem_ops) \ - { \ - (void) cg12_set_state(src); \ - mem.pr_ops = &mem_ops; \ - mem.pr_size = src->pr_size; \ - mem.pr_depth = src->pr_depth; \ - mem.pr_data = (char *) &cg12_d(src)->mprp; \ - src = &mem; \ - } - -extern struct pixrectops cg12_ops; - -int cg12_ioctl(); -int cg12_putcolormap(); -int cg12_putattributes(); -int cg12_rop(); - -#ifndef KERNEL -extern int gp1_rop(); - -int cg12_batchrop(); -int cg12_destroy(); -int cg12_get(); -int cg12_getattributes(); -int cg12_getcolormap(); -Pixrect *cg12_make(); -int cg12_put(); -Pixrect *cg12_region(); -int cg12_stencil(); -int cg12_vector(); - -#endif /* !KERNEL */ - -#endif /* cg12var_DEFINED */ diff --git a/include/pixrect/cg2reg.h b/include/pixrect/cg2reg.h deleted file mode 100644 index 94597df1570..00000000000 --- a/include/pixrect/cg2reg.h +++ /dev/null @@ -1,355 +0,0 @@ -/* @(#)cg2reg.h 1.11 88/02/08 SMI */ - -/* - * Copyright 1983, 1987 by Sun Microsystems, Inc. - */ - -#ifndef cg2reg_DEFINED -#define cg2reg_DEFINED - -/* - * cg2 -- color frame buffers with rasterop chips - * - * The frame buffer address space looks like this: - * - * 0x000000 plane mode memory - * 0x100000 pixel mode memory - * 0x200000 rop mode memory - * 0x300000 control registers - * 0x310000 color map - * - * To save on virtual address space, we don't map the plane or pixel mode - * memory (first two megabytes). However, when calling mmap the user has - * to add 2M to the desired offset anyway (goofy, huh?). - * - * The board can also be jumpered so the plane and pixel mode memory are - * not accessible at all, and the rop mode memory and control registers - * are decoded starting at address offset 0. - */ - -/* offset to and size of mapped part of frame buffer */ -#define CG2_MAPPED_OFFSET (sizeof (struct cg2memfb)) -#define CG2_MAPPED_SIZE (sizeof (struct cg2fb)) - -/* interrupt priority */ -#define CG2_INT_PRI 4 - -/* frame buffer resolution constants */ -#define CG2_WIDTH 1152 -#define CG2_HEIGHT 900 -#define CG2_SQUARE 1024 -#define CG2_DEPTH 8 - -/* - * Structure describing plane and pixel mode memory -- pretty useless - * since we don't map that part of the frame buffer. - */ -struct cg2memfb -{ - union bitplane { /* word mode memory */ - short word[CG2_HEIGHT][CG2_WIDTH/(8*sizeof(short))]; - short sword[CG2_SQUARE][CG2_SQUARE/(8*sizeof(short))]; - } memplane[8]; - union byteplane { /* pixel mode memory */ - u_char pixel[CG2_HEIGHT][CG2_WIDTH]; - u_char spixel[CG2_SQUARE][CG2_SQUARE]; - } pixplane; -}; - -/* control/status register */ -struct cg2statusreg -{ -u_int unused : - 2; /* reserved for future use */ -u_int fastread : - 1; /* has fast read feature */ -u_int id : - 1; /* has ID, extended status registers */ -u_int resolution : - 4; /* screen resolution */ -#define CG2_SCR_1152X900 0 -#define CG2_SCR_1024X1024 1 -#define CG2_SCR_1600X1280 2 -#define CG2_SCR_1440X1440 3 -unsigned retrace : - 1; /* rdonly: monitor in retrace */ -unsigned inpend : - 1; /* rdonly: interrupt pending */ -unsigned ropmode : - 3; /* Rasterop mode */ -unsigned inten : - 1; /* enab interrupt at end of retrace */ -unsigned update_cmap : - 1; - /* copy TTL cmap to ECL cmap next vert retrace*/ - /* silently disables writing to TTL cmap */ -unsigned video_enab : - 1; /* enab video DACs */ -}; - -/* extended status register */ -struct cg2_status2 -{ -u_int gpintreq : - 1; /* GP interrupt request */ -u_int gpintdis : - 1; /* GP interrupt disable */ -u_int unused : - 13; /* reserved for future use */ -u_int gpbus : - 1; /* GP bus enabled (read only) */ -}; - -/* double buffering control register */ -struct dblbufreg -{ -u_int display_b : - 1; /* Display memory set B or A. */ - /* Synchronized to start of vertical retrace. */ -u_int read_b : - 1; /* Read memory set B or A. */ -u_int nowrite_b : - 1; /* Do not update memory set B on writes. */ -u_int nowrite_a : - 1; /* Do not update memory set A on writes. */ -u_int read_ecmap : - 1;/* ECL to TTL cmap transfer direction. */ - /* Synchronized to start of Vertical retrace. */ -u_int fast_read : - 1; /* Return invalid data but fast Dtack on read */ -u_int wait : - 1; /* Write a '1' to set. Bit will remain */ - /* high until a full vertical retrace period has */ - /* elapsed. The bit clears itself. */ -u_int update_ecmap : - 1; -u_int reserved : - 8; -}; - -/* zoom/pan registers; Sun-2 color board only */ -struct cg2_zoom -{ - union { /*----- word pan register */ - unsigned short reg; /* hi 16 of 20 bit pix addr */ - /* pix addr = CG2_WIDTH*y+x */ - char pad[4096]; - } wordpan; - union { /*----- zoom and line offset register */ - struct - { -unsigned unused : - 8; -unsigned lineoff : - 4; /* y offset into zoomed pixel */ -unsigned pixzoom : - 4; /* zoomed pixel size - 1 */ - } - reg; - short word; - char pad[4096]; - } zoom; - union { /*----- pixel pan register */ - struct - { -unsigned unused : - 8; -unsigned lorigin : - 4; /* lo 4 bits of pix addr */ -unsigned pixeloff : - 4; /* zoomed pixel x offset/4 */ - } - reg; - short word; - char pad[4096]; - } pixpan; - union { /*----- variable zoom register */ - /* reset zoom after line no */ - unsigned short reg; /* line number 0..1024/4 */ - char pad[4096]; - } varzoom; -}; - -/* misc. control registers; Sun-3 color board etc. */ -struct cg2_nozoom -{ - union { /*----- double buffering register */ - struct dblbufreg reg; - short word; - char pad[4096]; - } dblbuf; - union { /*----- dma window origin register */ - unsigned short reg; - char pad [4096]; - } dmabase; - union { /*----- dma window width register */ - unsigned short reg; /* reg * 16 specifies width */ - char pad [4096]; /* of dma window. 8 bit. */ - } dmawidth; - union { /*----- frame count register */ - unsigned short reg; /* 8 bit. Read-only. */ - /* Returns frame number mod 256. */ - char pad[4096]; - } framecnt; -}; - -/* structure describing mapped part of frame buffer */ -struct cg2fb -{ - union { /* ROP mode memory */ - union bitplane ropplane[8]; /* word mode memory with ROP */ - union byteplane roppixel; /* pixel mode memory with ROP */ - } ropio; - union { /* rasterop unit control */ - struct memropc ropregs; /* normal register access */ - struct - { - char pad[2048]; /* for pixmode src reg prime */ - struct memropc ropregs; /* byte xfer loads alternate */ - } - prime; /* src register bits */ - char pad[4096]; - } ropcontrol[9]; - union { /*----- status register */ - struct cg2statusreg reg; - short word; - char pad[4096]; - } status; - union { /*----- per plane mask register */ - unsigned short reg; /* 8 bits 1bit -> wr to plane*/ - char pad[4096]; - } ppmask; - union { - struct cg2_zoom zoom; - struct cg2_nozoom nozoom; - } misc; - union { /*----- interrupt vector register */ - unsigned short reg; /* line number 0..1024/4 */ - char pad[32]; - } intrptvec; - union { /* board ID */ - u_short reg; - char pad[16]; - } id; - union { /* extended status */ - struct cg2_status2 reg; - u_short word; - char pad[16]; - } status2; - union { /* auxiliary ropmode register */ - u_short reg; - char pad[4032]; - } ropmode; - u_short redmap[256]; /* shadow color maps */ - u_short greenmap[256]; - u_short bluemap[256]; -}; - -/* - * ROPMODE PARALLEL LD_DST LD_SRC Description - * ON ON */ -#define PRWWRD 0 /* parallel 8 plane, read write, wrdmode */ -#define SRWPIX 1 /* single pixel, read write, pixmode */ -#define PWWWRD 2 /* parallel 8 plane, write write, wrdmode */ -#define SWWPIX 3 /* single pixel, write write, pixmode */ -#define PRRWRD 4 /* parallel 8 plane, read read, wrdmode */ -#define PRWPIX 5 /* parallel16 pixel, read write, pixmode */ -#define PWRWRD 6 /* parallel 8 plane, write read, wrdmode */ -#define PWWPIX 7 /* parallel16 pixel, write write, pixmode */ - -/* - * ROP control unit numbers - */ -#define CG2_ROP0 0 /* rasterop unit for bit plane 0 */ -#define CG2_ROP1 1 /* rasterop unit for bit plane 1 */ -#define CG2_ROP2 2 -#define CG2_ROP3 3 -#define CG2_ROP4 4 -#define CG2_ROP5 5 -#define CG2_ROP6 6 -#define CG2_ROP7 7 -#define CG2_ALLROP 8 /* writes to all units enabled by PPMASK */ -/* reads from plane zero */ - -#define CG_SRC 0xCC -#define CG_DEST 0xAA -#define CG_MASK 0xf0 -#define CG_NOTMASK 0x0f -#define CGOP_NEEDS_MASK(op) ( (((op)>>4)^(op)) & CG_NOTMASK) - -/* - *----------- Defines for accessing the rasterop units - */ -#define cg2_setrsource(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_source1 = (val)) -#define cg2_setrsource_pix(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].prime.ropregs.mrc_source1 = (val)) -#define cg2_setlsource(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_source2 = (val)) -#define cg2_setlsource_pix(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].prime.ropregs.mrc_source2 = (val)) -#define cg2_setpattern(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_pattern = (val)) -#define cg2_setlmask(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_mask1 = (val)) -#define cg2_setrmask(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_mask2 = (val)) -#define cg2_setshift(fb, ropunit, shft, dir) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_shift = \ - (shft)|((dir)<<8) ) -#define cg2_setfunction(fb, ropunit, val) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_op = (val)) -#define cg2_setwidth(fb, ropunit, w, count) \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_width = (w)); \ - ((fb)->ropcontrol[(ropunit)].ropregs.mrc_opcount = (count)) - -/* - *----------- Defines for accessing the zoom and pan registers - */ -#define cg2_setzoom(fb, pixsize) \ - ((fb)->misc.zoom.zoom.reg.pixzoom = (pixsize)-1) -#define cg2_setpanoffset(fb, xoff, yoff) \ - ((fb)->misc.zoom.pixpan.reg.pixeloff = (xoff)>>2; \ - (fb)->misc.zoom.zoom.reg.lineoff = (yoff)) -#define cg2_setpanorigin(fb, x, y) \ - ((y) = ((fb)->misc.zoom.status.reg.resolution == 1) ? \ - (y)*CG2_SQUARE+(x) : (y)*CG2_WIDTH+(x); \ - (fb)->misc.zoom.pixpan.reg.lorigin = (y)&0xf; \ - (fb)->misc.zoom.wordpan.reg = (y)>>4) -#define cg2_setzoomstop(fb, y) \ - ((fb)->misc.zoom.varzoom.reg = (y)>>2) - -/* - * Defines that facilitate addressing the frame buffer - */ - -#define cg2_pixaddr(fb, x, y) \ - (((fb)->status.reg.resolution) ? \ - &(fb)->pixplane.spixel[(y)][(x)] : \ - &(fb)->pixplane.pixel[(y)][(x)] ) -#define cg2_wordaddr(fb, plane, x, y) \ - (((fb)->status.reg.resolution) ? \ - &(fb)->memplane[(plane)].sword[(y)][(x)>>4] : \ - &(fb)->memplane[(plane)].word[(y)][(x)>>4]) -#define cg2_roppixaddr(fb, x, y) \ - (((fb)->status.reg.resolution) ? \ - &(fb)->ropio.roppixel.spixel[(y)][(x)] : \ - &(fb)->ropio.roppixel.pixel[(y)][(x)]) -#define cg2_ropwordaddr(fb, plane, x, y) \ - (((fb)->status.reg.resolution) ? \ - &(fb)->ropio.ropplane[(plane)].sword[(y)][(x)>>4]:\ - &(fb)->ropio.ropplane[(plane)].word[(y)][(x)>>4]) -#define cg2_width(fb ) \ - ( ((fb)->status.reg.resolution) ? CG2_SQUARE : CG2_WIDTH ) -#define cg2_height(fb ) \ - ( ((fb)->status.reg.resolution) ? CG2_SQUARE : CG2_HEIGHT ) -#define cg2_linebytes(fb, mode) \ - ( ((fb)->status.reg.resolution) \ - ? ( ((mode)&1)?CG2_SQUARE:CG2_SQUARE/8 ) \ - : ( ((mode)&1)?CG2_WIDTH:CG2_WIDTH/8 )) - -#define cg2_prskew(x) ((x) & 15) - -#define cg2_touch(a) ((a)=0) - -#endif cg2reg_DEFINED diff --git a/include/pixrect/cg2var.h b/include/pixrect/cg2var.h deleted file mode 100644 index 6398cc16c55..00000000000 --- a/include/pixrect/cg2var.h +++ /dev/null @@ -1,89 +0,0 @@ -/* @(#)cg2var.h 1.10 88/02/08 SMI */ - -/* - * Copyright 1983, 1987 by Sun Microsystems, Inc. - */ - -#ifndef cg2var_DEFINED -#define cg2var_DEFINED - -/* FBIOSATTR device specific array indices */ -#define FB_ATTR_CG2_FLAGS 0 /* attribute flags word */ -#define FB_ATTR_CG2_FLAGS_SUN3 1 /* bit set for Sun-3 color board */ -#define FB_ATTR_CG2_FLAGS_PRFLAGS 2 /* bit set if PRFLAGS valid */ - -#define FB_ATTR_CG2_BUFFERS 1 /* # of buffers */ -#define FB_ATTR_CG2_PRFLAGS 2 /* same as struct cg2pr flags */ - -struct cg2pr -{ - struct cg2fb *cgpr_va; /* mapped color board */ - caddr_t gp_shmem; /* pointer to shared memory */ - int cgpr_fd; /* primary flag */ - int cgpr_planes; /* color bit plane mask reg */ - struct pr_pos cgpr_offset; /* pixrect offset */ - short cg2_index; /* cg2 board index */ - char minordev; /* true minor dev to stuff into GP */ - int gbufflag; /* gbuffer flag */ - int ioctl_fd; /* the fd to talk to the driver with */ - int ncmd; /* length of cmdver array */ - u_char *cmdver; /* version #'s for each command */ - - int flags; /* misc options */ -#define CG2D_STDRES 1 /* standard (1152 x 900) resolution */ -#define CG2D_FASTREAD 2 /* has fast read feature */ -#define CG2D_ROPMODE 4 /* has aux. ropmode register */ -#define CG2D_32BIT 8 /* has 32 bit bus */ -#define CG2D_DBLBUF 16 /* has double buffering */ -#define CG2D_WINDMA 32 /* has window DMA */ -#define CG2D_ZOOM 256 /* has struct cg2_zoom */ -#define CG2D_NOZOOM 512 /* has struct cg2_nozoom */ -#define CG2D_ID 1024 /* has ID, extended status registers */ -#define CG2D_GP2 (1<<29) /* GP is GP2 */ -#define CG2D_GB (1<<30) /* GB attached */ -#define CG2D_GP (1<<31) /* GP pixrect -- must be sign bit! */ - int linebytes; /* bytes per line (pixel mode) */ -}; - -#define cg2_d(pr) ((struct cg2pr *)(pr)->pr_data) -#define cg2_fbfrompr(pr) (((struct cg2pr *)(pr)->pr_data)->cgpr_va) - -#define cg2_ropword(cgd, plane, ax, ay) \ - (cg2_ropwordaddr((cgd)->cgpr_va, (plane), \ - (cgd)->cgpr_offset.x+(ax),(cgd)->cgpr_offset.y+(ay)) ) -#define cg2_pixel(cgd, ax, ay) \ - (cg2_pixaddr((cgd)->cgpr_va, \ - (cgd)->cgpr_offset.x+(ax),(cgd)->cgpr_offset.y+(ay)) ) -#define cg2_roppixel(cgd, ax, ay) \ - (cg2_roppixaddr((cgd)->cgpr_va, \ - (cgd)->cgpr_offset.x+(ax),(cgd)->cgpr_offset.y+(ay)) ) - -#define cg2_prd_skew(cgd, ax) \ - (((cgd)->cgpr_offset.x+(ax)) & 15) - -/* GP sync macro */ -#define GP1_PRD_SYNC(prd, error) _STMT( \ - if ((prd)->flags < 0 && gp1_sync((prd)->gp_shmem, (prd)->ioctl_fd)) \ - { error; }) - -/* ops vector and functions */ -extern struct pixrectops cg2_ops; - -int cg2_rop(); -int cg2_putcolormap(); -int cg2_putattributes(); - -#ifndef KERNEL -int cg2_stencil(); -int cg2_batchrop(); -Pixrect *cg2_make(); -int cg2_destroy(); -int cg2_get(); -int cg2_put(); -int cg2_vector(); -Pixrect *cg2_region(); -int cg2_getcolormap(); -int cg2_getattributes(); -#endif !KERNEL - -#endif cg2var_DEFINED diff --git a/include/pixrect/cg3var.h b/include/pixrect/cg3var.h deleted file mode 100644 index 5156a3167d9..00000000000 --- a/include/pixrect/cg3var.h +++ /dev/null @@ -1,51 +0,0 @@ -/* @(#)cg3var.h 1.2 89/05/19 SMI */ - -/* - * Copyright 1989 by Sun Microsystems, Inc. - */ - -#ifndef cg3var_DEFINED -#define cg3var_DEFINED - -/* - * cg3 -- color memory frame buffer - */ - -/* - * On architectures where cg4s have been implemented we need a nice big - * mmap offset to avoid the cg4 compatible simulated overlay/enable planes. - * On e.g. the 386i might as well start at zero. - */ -#if defined(mc68000) || defined(sparc) -#define CG3_MMAP_OFFSET 0x04000000 /* 8K x 8K */ -#else -#define CG3_MMAP_OFFSET 0 -#endif - -/* - * In the kernel we just use a memory pixrect so we don't - * need any of this stuff. - */ -#ifndef KERNEL -#include - -/* pixrect private data */ -struct cg3_data -{ - struct mprp_data mprp; /* memory pixrect simulator */ - int fd; /* file descriptor */ -}; - -#define cg3_d(pr) ((struct cg3_data *) (pr)->pr_data) - -/* pixrect ops vector */ -extern struct pixrectops cg3_ops; - -Pixrect *cg3_make(); -int cg3_destroy(); -Pixrect *cg3_region(); -int cg3_putcolormap(); -int cg3_getcolormap(); -#endif !KERNEL - -#endif !cg3var_DEFINED diff --git a/include/pixrect/cg4var.h b/include/pixrect/cg4var.h deleted file mode 100644 index 79fe1759625..00000000000 --- a/include/pixrect/cg4var.h +++ /dev/null @@ -1,61 +0,0 @@ -/* @(#)cg4var.h 1.8 89/03/14 SMI */ - -/* - * Copyright 1986 by Sun Microsystems, Inc. - */ - -#ifndef cg4var_DEFINED -#define cg4var_DEFINED - -/* - * cg4 -- color memory frame buffer - */ - -/* FBIOSATTR device specific array indices */ -#define FB_ATTR_CG4_SETOWNER_CMD 0 /* 1 indicates PID is valid */ -#define FB_ATTR_CG4_SETOWNER_PID 1 /* new owner of device */ - -#include - -#define CG4_NFBS 3 /* number of frame buffers in a cg4 */ - -/* description of single frame buffer */ -struct cg4fb -{ - short group; /* plane group implemented */ - short depth; /* depth, bits */ - struct mprp_data mprp; /* memory pixrect data */ -}; - -/* pixrect private data */ -struct cg4_data -{ - struct mprp_data mprp; /* memory pixrect simulator */ - int flags; /* misc. flags */ -#define CG4_PRIMARY 1 /* primary pixrect */ -#define CG4_OVERLAY_CMAP 2 /* overlay has colormap */ - int planes; /* current group and mask */ - int fd; /* file descriptor */ - short active; /* active fb no. */ - struct cg4fb fb[CG4_NFBS]; /* frame buffer info */ -}; - -/* useful macros */ -#define cg4_d(pr) ((struct cg4_data *) ((pr)->pr_data)) - -/* pixrect ops vector */ -extern struct pixrectops cg4_ops; - -int cg4_putcolormap(); -int cg4_putattributes(); -int cg4_ioctl(); - -#ifndef KERNEL -Pixrect *cg4_make(); -int cg4_destroy(); -Pixrect *cg4_region(); -int cg4_getcolormap(); -int cg4_getattributes(); -#endif !KERNEL - -#endif !cg4var_DEFINED diff --git a/include/pixrect/cg8var.h b/include/pixrect/cg8var.h deleted file mode 100644 index 422daad07eb..00000000000 --- a/include/pixrect/cg8var.h +++ /dev/null @@ -1,181 +0,0 @@ -/* @(#)cg8var.h 1.19 of 7/1/91 SMI */ - -/* - * Copyright 1988 by Sun Microsystems, Inc. - */ - -#ifndef cg8var_DEFINED -#define cg8var_DEFINED - -#include /* Define _IOR and _IOW */ -#include /* Definition for struct rect */ -#include -#include /* Needed by sbusdev/cg8reg.h. */ -#ifdef sun4 -#include -#endif -#include - -/* FBIOSATTR device specific array indices, copied from cg4var.h */ -#define FB_ATTR_CG8_SETOWNER_CMD 0 /* 1 indicates PID is valid */ -#define FB_ATTR_CG8_SETOWNER_PID 1 /* new owner of device */ - - -#define CG8_NFBS 8 - -#define CG8_PRIMARY 0x01 /* Mark the PRIMARY Pixrect */ -#define CG8_OVERLAY_CMAP 0x02 /* Overlay CMAP to be changed */ -#define CG8_24BIT_CMAP 0x04 /* 24 Bit CMAP to be changed */ -#define CG8_KERNEL_UPDATE 0x08 /* kernel vs. user ioctl */ -/* 0x10 & 0x20 are dbl buf in cg9 */ -#define CG8_SLEEPING 0x40 /* Denote if wake_up is necessary */ -#define CG8_COLOR_OVERLAY 0x80 /* view overlay & enable as 2 bits */ -#define CG8_UPDATE_PENDING 0x100 -#define CG8_PIP_PRESENT 0x200 /* PIP is present. */ -#define CG8_STOP_PIP 0x400 /* Stop PIP when accessing this pln. grp. */ -#define CG8_EIGHT_BIT_PRESENT 0x800 /* There is an 8-bit frame buffer. */ - -struct cg8_data -{ - struct mprp_data mprp; /* memory pixrect simulator */ - int flags; /* misc. flags */ - int planes; /* current group and mask */ - int fd; /* file descriptor */ - short active; /* active fb no. */ - int num_fbs; /* number of frame buffers in "fb. */ - struct cg4fb fb[CG8_NFBS]; /* frame buffer info */ - int windowfd; /* if 8-bit indexed pw */ - struct colormapseg cms; /* if 8-bit indexed pr */ - int real_windowfd; /* if 8-bit indexed pw */ -}; - -#define cg8_d(pr) ((struct cg8_data *)((pr)->pr_data)) - -#define CG8_PR_TO_MEM(src, mem) \ - if (src && src->pr_ops != &mem_ops) \ - { \ - mem.pr_ops = &mem_ops; \ - mem.pr_size = src->pr_size; \ - mem.pr_depth = src->pr_depth; \ - mem.pr_data = (char *) &cg8_d(src)->mprp; \ - src = &mem; \ - } - -#define CG8_PR_TO_MEM32(pr, mem32_pr, mem32_pr_data) \ - if (pr && pr->pr_ops != &mem_ops) \ - { \ - mem32_pr.pr_ops = &mem32_ops; \ - mem32_pr.pr_size = pr->pr_size; \ - mem32_pr.pr_depth = pr->pr_depth; \ - mem32_pr_data.mprp = cg8_d(pr)->mprp; \ - mem32_pr_data.plane_group = cg8_d(pr)->fb[cg8_d(pr)->active].group;\ - mem32_pr_data.fd = cg8_d(pr)->fd; \ - mem32_pr_data.windowfd = cg8_d(pr)->windowfd; \ - mem32_pr_data.cms = cg8_d(pr)->cms; \ - mem32_pr.pr_data = (char *) &mem32_pr_data; \ - pr = &mem32_pr; \ - } - - -extern struct pixrectops cg8_ops; - -int cg8_putcolormap(); -int cg8_putattributes(); -int cg8_ioctl(); - -#ifndef KERNEL - -Pixrect *cg8_make(); -int cg8_destroy(); -Pixrect *cg8_region(); -int cg8_getcolormap(); -int cg8_getattributes(); -int cg8_vector(); -int cg8_get(); -int cg8_put(); -int cg8_rop(); - -#endif !KERNEL - -#ifndef pipio_DEFINED - -#define pipio_DEFINED - -/* IOCTL definitions for the SBus True Card PIP - * - */ - -/* First unused ioctl number is 43.*/ - -/* EEPROM Write Byte operation control information: - */ -typedef struct -{ - int address; /* Address in EEPROM to write to. */ - int value; /* Value to write (in low-order 8 bits.) */ -} -EEPROM_Write_Byte; - -/* Frame buffer and memory mapping information ioctl: - */ -typedef struct Fb_Description -{ /* Frame buffer description: */ - short group; /* ... Sun "plane group" of frame buffer. */ - short width; /* ... width of frame buffer. */ - short height; /* ... height of frame buffer. */ - short depth; /* ... depth of frame buffer. */ - u_int linebytes; /* ... # of bytes per scan line for fb. */ - u_int mmap_size; /* ... size of mapping for frame buffer. */ - u_int mmap_offset; /* ... offset for memory map of fb. */ -} -Fb_Description; - -#define PIP_NFBS 10 /* # of frame buffer descriptions in Pipio_Fb_Info. */ -#define FB_NPGS 12 /* # of plane groups possible. */ - -typedef struct Pipio_Fb_Info -{ /* Frame buffer info record: */ - int frame_buffer_count; /* ... # of fbs supported. */ - u_int total_mmap_size; /* ... memory map size of all fbs */ - Fb_Description fb_descriptions[PIP_NFBS]; /* ... individual fb descriptions */ -} -Pipio_Fb_Info; - -/* Frame buffer emulation ioctl: - */ -typedef struct Pipio_Emulation -{ /* Emulation control layout: */ - u_char plane_groups[FB_NPGS]; /* ... plane groups to enable. */ - u_short timing; /* ... timing/size regimen. */ -} -Pipio_Emulation; -#define NATIVE_TIMING 0 /* Provide standard (default) timing. */ -#define NTSC_TIMING 1 /* Provide NTSC timing. */ -#define PAL_TIMING 2 /* Provide PAL timing. */ - -/* I/O controls used by Sunview Pixrect library routines. - */ -#define PIPIO_G_FB_INFO _IOR(X, 1, Pipio_Fb_Info) /* Get info about fbs. */ -#define PIPIO_G_EMULATION_MODE _IOR(X, 3, Pipio_Emulation) -/* Return current emulation mode. */ -#define PIPIO_S_EMULATION_MODE _IOW(X, 4, Pipio_Emulation) -/* Set the device being emulated. */ -#define PIPIO_G_PIP_ON_OFF _IOR(X, 5, int) -/* Get the value of the pip on bit. */ -#define PIPIO_S_PIP_ON_OFF _IOW(X, 7, int) /* Set or clear pip on bit. */ -#define PIPIO_G_PIP_ON_OFF_RESUME _IOR(X, 9, int) -/* Resume (pop) pip operations, return new status. */ -#define PIPIO_G_PIP_ON_OFF_SUSPEND _IOR(X, 10, int) -/* Get pip status, & suspend pip ops.*/ - -#define PIPIO_G_CURSOR_COLOR_FREEZE _IOR(X, 40, int) -/* Get setting of cursor color frozen switch. */ -#define PIPIO_S_CURSOR_COLOR_FREEZE _IOW(X, 41, int) -/* Set cursor color frozen switch. */ -#define PIPIO_S_MAP_SLOT _IOW(X, 42, int) /* Map SBus slot at offset 0x900000. */ -#define PIPIO_G_TEST _IOR(X, 43, int) /* For testing purposes. */ -#define PIPIO_S_TEST _IOW(X, 44, int) /* For testing purposes. */ - -#endif pipio_DEFINED - -#endif cg8var_DEFINED diff --git a/include/pixrect/cg9var.h b/include/pixrect/cg9var.h deleted file mode 100644 index 983a2c9db0e..00000000000 --- a/include/pixrect/cg9var.h +++ /dev/null @@ -1,93 +0,0 @@ -/* @(#)cg9var.h 1.10 90/03/22 SMI */ - -/* Copyright (c) 1989 by Sun Microsystems, Inc. */ - -/* - * CG9 Header File - * Describe "Private Data" of CG9 Pixrect, also external - * references to pixrect operation - */ - -#ifndef cg9var_DEFINED -#define cg9var_DEFINED - -#include -#include -#include /* colormapseg */ - -/* description of single CG9 frame buffer */ - -struct cg9fb -{ - short group; /* plane group implemented */ - short depth; /* depth, bits */ - struct mprp_data mprp; /* memory pixrect data */ -}; - -#define CG_TYPE 3 /* for dev_specific stamp of fb.type */ -#define CG_SIZE 4 /* for dev_specific stamp of fb size */ -#define CG9_NFBS 3 /* number of frame buffers in a CG9 */ - -/* CG9 Pixrect private data */ - -struct cg9_data -{ - struct mprp_data mprp; /* memory pixrect simulator */ - int flags; /* misc. flags */ - int planes; /* current group and mask */ - int fd; /* file descriptor */ - short active; /* active fb no. */ - struct cg9_control_sp *ctrl_sp; - struct cg9fb fb[CG9_NFBS]; /* frame buffer info */ - int windowfd; /* if 8-bit indexed pw */ - struct colormapseg cms; /* if 8-bit indexed pr */ - int real_windowfd; /* for dblbuf hack */ -}; - -/* useful macros */ -#define cg9_d(pr) ((struct cg9_data *) ((pr)->pr_data)) - -#define CG9_PR_TO_MEM(src, mem) \ - if (src && src->pr_ops != &mem_ops) \ - { \ - mem.pr_ops = &mem_ops; \ - mem.pr_size = src->pr_size; \ - mem.pr_depth = src->pr_depth; \ - mem.pr_data = (char *) &cg9_d(src)->mprp; \ - src = &mem; \ - } - -#define CG9_PR_TO_MEM32(pr, mem32_pr, mem32_pr_data) \ - if (pr && pr->pr_ops != &mem_ops) \ - { \ - mem32_pr.pr_ops = &mem32_ops; \ - mem32_pr.pr_size = pr->pr_size; \ - mem32_pr.pr_depth = pr->pr_depth; \ - mem32_pr_data.mprp = cg9_d(pr)->mprp; \ - mem32_pr_data.plane_group = cg9_d(pr)->fb[cg9_d(pr)->active].group;\ - mem32_pr_data.fd = cg9_d(pr)->fd; \ - mem32_pr_data.windowfd = cg9_d(pr)->windowfd; \ - mem32_pr_data.cms = cg9_d(pr)->cms; \ - mem32_pr.pr_data = (char *) &mem32_pr_data; \ - pr = &mem32_pr; \ - } - -extern struct pixrectops cg9_ops; -int cg9_putcolormap(); -int cg9_putattributes(); -int cg9_rop(); -int cg9_ioctl(); - -#ifndef KERNEL -Pixrect *cg9_make(); -int cg9_destroy(); -Pixrect *cg9_region(); -int cg9_getcolormap(); -int cg9_getattributes(); -int cg9_vector(); -int cg9_get(); -int cg9_put(); - -#endif !KERNEL - -#endif cg9var_DEFINED diff --git a/include/pixrect/gp1cmds.h b/include/pixrect/gp1cmds.h deleted file mode 100644 index 5af14ca5a10..00000000000 --- a/include/pixrect/gp1cmds.h +++ /dev/null @@ -1,421 +0,0 @@ -/* @(#)gp1cmds.h 1.28 91/05/31 SMI */ - -/* - * Copyright 1986-1990 by Sun Microsystems, Inc. - */ - -#ifndef gp1cmds_DEFINED -#define gp1cmds_DEFINED - -/* GP low level command set */ - -#define GP1_EOCL (0 << 8) -#define GP1_USE_CONTEXT (1 << 8) -#define GP1_PR_VEC (2 << 8) -#define GP1_PR_ROP_NF (3 << 8) -#define GP1_PR_ROP_FF (4 << 8) - -#define GP1_PR_PGON_SOL (5 << 8) -#define GP1_SET_ZBUF (6 << 8) -#define GP1_SET_HIDDEN_SURF (7 << 8) -#define GP1_SET_MAT_NUM (8 << 8) -#define GP1_MUL_POINT_FLT_2D (9 << 8) - -#define GP1_MUL_POINT_FLT_3D (10 << 8) -#define GP1_XF_PGON_FLT_3D (11 << 8) -#define GP1_XF_PGON_FLT_2D (12 << 8) - -#define GP1_SET_CLIP_LIST (15 << 8) -#define GP1_SET_FB_NUM (16 << 8) -#define GP1_SET_VWP_3D (17 << 8) -#define GP1_SET_VWP_2D (18 << 8) -#define GP1_SET_ROP (19 << 8) - -#define GP1_SET_CLIP_PLANES (20 << 8) -#define GP1_MUL_POINT_INT_2D (21 << 8) -#define GP1_MUL_POINT_INT_3D (22 << 8) -#define GP1_SET_FB_PLANES (23 << 8) -#define GP1_SET_MAT_3D (24 << 8) - -#define GP1_SET_MAT_OFFSET (26 << 8) -#define GP1_SET_COLOR (28 << 8) -#define GP1_SET_MAT_2D (29 << 8) - -#define GP1_XF_PGON_INT_3D (30 << 8) -#define GP1_COPY_MAT (31 << 8) -#define GP1_MUL_MAT_2D (32 << 8) -#define GP1_MUL_MAT_3D (33 << 8) -#define GP1_GET_MAT_2D (34 << 8) - -#define GP1_GET_MAT_3D (35 << 8) -#define GP1_PROC_LINE_FLT_3D (36 << 8) -#define GP1_PROC_PGON_FLT_3D (37 << 8) -#define GP1_PROC_PGON_FLT_2D (38 << 8) - -#define GP2_NOP (39 << 8) - -#define GP1_PR_LINE (40 << 8) -#define GP1_PR_POLYLINE (41 << 8) -#define GP1_SET_LINE_TEX (42 << 8) -#define GP1_SET_LINE_WIDTH (43 << 8) -#define GP1_CGI_LINE (44 << 8) - -#define GP1_XF_LINE_FLT_2D (45 << 8) -#define GP1_XF_LINE_FLT_3D (46 << 8) -#define GP1_XF_LINE_INT_3D (47 << 8) -#define GP1_PR_PGON_TEX (48 << 8) - -#define GP1_PR_ROP_TEX (50 << 8) -#define GP1_SET_PGON_TEX_BLK (51 << 8) -#define GP1_SET_PGON_TEX (52 << 8) -#define GP1_SET_PGON_TEX_ORG_SCR (53 << 8) -#define GP1_SET_PGON_TEX_ORG_XF_2D (54 << 8) - -#define GP1_SET_PGON_TEX_ORG_XF_3D (55 << 8) -#define GP1_XF_LINE_INT_2D (57 << 8) -#define GP1_XF_PGON_INT_2D (58 << 8) -#define GP1_PROC_PGON_INT_2D (59 << 8) - -#define GP1_PROC_LINE_FLT_2D (60 << 8) -#define GP1_PROC_LINE_INT_2D (61 << 8) -#define GP1_PROC_LINE_INT_3D (62 << 8) -#define GP1_PROC_PGON_INT_3D (63 << 8) -#define GP1_SET_PICK_ID (64 << 8) -#define GP1_SET_PICK_WINDOW (65 << 8) -#define GP1_GET_PICK (66 << 8) -#define GP1_SET_PICK (67 << 8) -#define GP1_CLEAR_PICK (68 << 8) - -#define GP1_XF_POINT_INT_2D (69 << 8) -#define GP1_XF_POINT_INT_3D (70 << 8) -#define GP1_XF_POINT_FLT_2D (71 << 8) -#define GP1_XF_POINT_FLT_3D (72 << 8) - -#define GP1_CLEAR_CONTEXT (73 << 8) -#define GP1_SET_DEPTH_CUE (74 << 8) -#define GP1_SET_DEPTH_CUE_COLORS (75 << 8) -#define GP2_SET_DEPTH_CUE_PARAMETERS (76 << 8) - -/* number of commands defined so far */ -#define GP1_NCMDS 76 - -/* - * Commands that exist only on the GP2 start here. - * True except for some minor exceptions. - * (Leave a little gap for gp1 expansion.) - */ - -#define GP2_SET_RGB_COLOR (80 << 8) -#define GP2_PROC_PGON_FLT_3D_RGB (81 << 8) -#define GP2_PROC_PGON_INT_3D_RGB (82 << 8) -#define GP2_XF_PGON_FLT_3D_RGB (83 << 8) -#define GP2_XF_PGON_INT_3D_RGB (84 << 8) -#define GP2_SET_LIGHT (85 << 8) -#define GP2_SET_LIGHT_MATRIX (86 << 8) -#define GP2_SET_REFLECTANCE (87 << 8) -#define GP2_SET_EYE (88 << 8) - -#define GP2_SET_TRANSPARENCY (89 << 8) -#define GP2_SET_DITHER (90 << 8) -#define GP2_SET_LIGHT_OPTIONS (91 << 8) - -#define GP2_XF_SHADE_LINE_FLT_3D (99 << 8) - -#define GP2_XF_RECT_INT_2D (100 << 8) -#define GP2_XF_RECT_FLT_2D (101 << 8) -#define GP2_SET_TEXT_TYPE (102 << 8) -#define GP2_SET_TEXT_PRECISION (103 << 8) -#define GP2_SET_TEXT_PATH (104 << 8) -#define GP2_SET_FONT (105 << 8) -#define GP2_SET_TEXT_EXPANSION (106 << 8) -#define GP2_SET_TEXT_SPACING (107 << 8) -#define GP2_SET_TEXT_MAP (108 << 8) -#define GP2_LOAD_FONT (109 << 8) -#define GP2_SET_TEXT_ATTRIBUTES (110 << 8) -#define GP2_TEXT_INT_2D (111 << 8) -#define GP2_TEXT_FLT_2D (112 << 8) -#define GP2_TEXT_INT_3D (113 << 8) -#define GP2_TEXT_FLT_3D (114 << 8) -#define GP2_SET_TEXT_MAT_NUM (115 << 8) -#define GP2_SET_CMAP_OFFSET (116 << 8) -#define GP2_XF_TRISTRIP_FLT_3D_RGB (117 << 8) - -/* number of gp2 commands defined so far. */ -#define GP2_NCMDS 117 - -/* - * Commands that exist only on the GP3 (cgtwelve) - * start here. - * - */ - -#define GP3_SET_DB_PLANES_RGB (98 << 8) -#define GP3_SET_FB_PLANES_RGB (100 << 8) -#define GP3_SET_ANTI_ALIAS (102 << 8) /* 0x66 */ - -#define GP3_PR_ROP24_FF (118 << 8) -#define GP3_PR_ROP24_NF (119 << 8) -#define GP3_PR_ROP24_TEX (120 << 8) -#define GP3_PR_ROP24_BATCH (121 << 8) -#define GP3_PR_VEC24 (122 << 8) - -#define GP3_TRISTAR_FLT_3D_RGB (125 << 8) - -/* number of gp3 commands defined so far. */ -#define GP3_NCMDS 125 - - -/* Constants for option field of commands */ -#define GP1_FREEBLKS 0x80 /* for EOCL */ - -#define GP1_NOHIDDENSURF 0 /* for SET_HIDDENSURF */ -#define GP1_ZBHIDDENSURF 1 /* depth buffer polygons */ -#define GP1_ZBLINES 2 /* depth buffer lines */ -#define GP1_ZBMARKERS 4 /* depth buffer markers */ -#define GP1_ZBALL 7 /* depth buffer all primitives */ - -#define GP1_SHADE_CONSTANT 0 /* for XF_POLYGON */ -#define GP1_SHADE_GOURAUD 1 -#define GP1_SHADE_TEX 2 - -#define GP1_CLIP_PLANE_LEFT 0x20 /* for SET_CLIP_PLANES */ -#define GP1_CLIP_PLANE_RIGHT 0x10 -#define GP1_CLIP_PLANE_BOTTOM 0x8 -#define GP1_CLIP_PLANE_TOP 0x4 -#define GP1_CLIP_PLANE_HITHER 0x2 -#define GP1_CLIP_PLANE_YON 0x1 -#define GP1_CLIP_PLANES_2D 0x3C -#define GP1_CLIP_PLANES_3D 0x3F - -#define GP1_PICK_OFF 0 /* for SET_PICK and CLEAR_PICK */ -#define GP1_PICK_DRAW 1 -#define GP1_PICK_NODRAW 2 - -#define GP1_MARKER_LINE 0 -#define GP1_MARKER_POLY 1 -#define GP1_MARKER_CIRC 2 -#define GP1_MARKER_FILL_CIRC 3 - -#define GP1_MARKER_PHIGS_DOT 4 -#define GP1_MARKER_PHIGS_1 4 -#define GP1_MARKER_PHIGS_PLUS 5 -#define GP1_MARKER_PHIGS_2 5 -#define GP1_MARKER_PHIGS_STAR 6 -#define GP1_MARKER_PHIGS_3 6 -#define GP1_MARKER_PHIGS_CIRCLE 7 -#define GP1_MARKER_PHIGS_4 7 -#define GP1_MARKER_PHIGS_CROSS 8 -#define GP1_MARKER_PHIGS_5 8 -#define GP1_MARKER_PHIGS_SQUARE 9 -#define GP1_MARKER_PHIGS_6 9 -#define GP1_MARKER_PHIGS_BOW_NE 10 -#define GP1_MARKER_PHIGS_7 10 -#define GP1_MARKER_PHIGS_BOW_NW 11 -#define GP1_MARKER_PHIGS_8 11 -#define GP1_MARKER_PHIGS(i) (GP1_MARKER_FILL_CIRC + i) - - -#define GP1_DEPTH_CUE_OFF 0 /* for GP1_SET_DEPTH_CUE */ -#define GP1_DEPTH_CUE_ON 1 - - -#define GP2_SET_CMAP_DEFAULT 0 -#define GP2_SET_CMAP_ZERO 1 - -#define GP2_INDEX_COLOR 0 /* For GP2_XF_PGON_XXX_3D_RGB */ -#define GP2_RGB_COLOR_TRIPLE 1 /* GP1_SET_DEPTH_CUE_COLORS */ -#define GP2_RGB_COLOR_PACK 2 /* and GP2_SET_RGB_COLOR */ -#define GP2_VERTEX_NORMALS 4 -#define GP2_POLYGON_NORMAL 8 - -/* For GP2_SET_RGB_COLOR */ -#define GP3_SET_BACK_COLOR 128 /* 0x80 */ - -/* For GP2_XF_TRISTRIP_FLT_3D_RGB */ -/* #define GP2_VERTEX_NORMALS 4 same as above */ -#define GP2_FACET_NORMALS 8 -#define GP2_STRIP_NORMAL 16 -#define GP3_FACET_COLORS 32 - -/* For GP1_SET_ZBUF */ -#define GP2_SET_Z 0 /* a 1 will work the same */ -#define GP2_SET_I 2 -#define GP2_SET_ZI 3 -#define GP3_SET_I_DITH 6 /* will dither if dithering is on */ -#define GP3_SET_ZI_DITH 7 - - - -/* Light source types or states */ - -#define GP2_LIGHT_AMBIENT 0 /* 0x00 */ -#define GP2_LIGHT_DIRECTIONAL 1 /* 0x01 */ -#define GP2_LIGHT_POSITIONAL 2 /* 0x02 */ -#define GP2_LIGHT_SPOT 4 /* 0x04 */ - -#define GP2_FRONT_PROPERTIES 0 /* 0x00 */ -#define GP2_BACK_PROPERTIES 1 /* 0x01 */ - -#define GP2_NO_FACE_REJ 0 /* 0x00 */ -#define GP2_BACK_FACE_REJ 1 /* 0x01 */ -#define GP2_FRONT_FACE_REJ 2 /* 0x02 */ - -#define GP2_FACE_REJECTION 0 /* 0x00 */ -#define GP2_BACK_FACE_SHADE 1 /* 0x01 */ -#define GP2_COPY_PNORM_TO_VNORM 2 /* 0x02 */ -#define GP2_GENERATE_PNORMAL 4 /* 0x04 */ -#define GP2_LIGHT_ON 8 /* 0x08 */ -#define GP3_LIGHT_FRONT 9 /* 0x09 */ -#define GP3_LIGHT_BACK 10 /* 0x0a */ -#define GP2_LIGHT_OFF 16 /* 0x10 */ -#define GP2_IGNORE_FLAG 32 /* 0x20 */ - -#define GP2_IGNORE_VERTEX_NORMAL 33 /* 0x21 */ -#define GP2_IGNORE_VERTEX_COLOR 34 /* 0x22 */ -#define GP2_IGNORE_VERTEX_DATA 35 /* 0x23 */ -#define GP2_IGNORE_LIGHTING 20 /* 0x14 */ -#define GP2_IGNORE_FRONT_FACE 0 /* 0x00 */ -#define GP2_IGNORE_BACK_FACE 1 /* 0x01 */ - -#define GP2_EYE_DIRECTIONAL 0 /* 0x00 */ -#define GP2_EYE_POSITIONAL 1 /* 0x01 */ - -/* For use in conjunction with GP2_SET_LIGHT_OPTIONS - with the GP2_GENERATE_NORMAL option where you can have - (ON or OFF) OR'd with (LEFTHAND or RIGHTHAND) to specify - by which rule the application would like normals generated. - This option is only available through the GP3. */ - -#define GP3_USE_LEFTHAND_RULE 1 /* 0x01 */ -#define GP3_USE_RIGHTHAND_RULE 2 /* 0x02 */ - -/* For use with all XF_PGON commands - * - * "or"ing this bit into a polygon command will cause quads to be split into - * two triangles for increased performance. Note that this will cause concave - * quads to be drawn incorrectly. - */ -#define GP2_DIVIDE_QUADS 0x40 - -/* Constants for text commands */ -#define GP2_TEXT_CLEAR_FONT 0 -#define GP2_TEXT_FONT0 0 -#define GP2_TEXT_FONT1 1 -#define GP2_TEXT_FONT2 2 -#define GP2_TEXT_FONT3 3 -#define GP2_TEXT_FONT4 4 -#define GP2_TEXT_FONT5 5 -#define GP2_TEXT_FONT6 6 -#define GP2_TEXT_FONT7 7 -#define GP2_TEXT_RIGHT 0 -#define GP2_TEXT_LEFT 1 -#define GP2_TEXT_UP 2 -#define GP2_TEXT_DOWN 3 -#define GP2_TEXT_STRING 0 -#define GP2_TEXT_CHAR 1 -#define GP2_TEXT_STROKE 2 -#define GP2_TEXT_VECTOR 0 -#define GP2_TEXT_FILLED 1 -#define GP2_TEXT_SPLINE 2 - -/* Constants for size limits on commands */ - -/* maximum # of 16 bit texture words for PR_PGON_TEX, PR_ROP_TEX* */ -#define GP1_MAXPRTEXSHORTS 2048 - -/* limits for PR_LINE, PR_POLYLINE */ -#define GP1_MAX_BRUSH_WIDTH 181 /* sqrt(32767) */ -#define GP1_MAX_PAT_SEGS 16 - -/* Constant to indicate version information is available - in 3.2FCS and later releases of the pixrect library */ -#define GP1_VERSION_QUERY 1 - - -/* Old command names still available for compatibility */ - -#define GP1_USEFRAME (1 << 8) -#define GP1_PRVEC (2 << 8) -#define GP1_PRROPNF (3 << 8) -#define GP1_PRROPFF (4 << 8) -#define GP1_PRPOLYSOL (5 << 8) -#define GP1_SETZBUF (6 << 8) -#define GP1_SETHIDDENSURF (7 << 8) -#define GP1_SELECTMATRIX (8 << 8) -#define GP1_XFORMPT_2D (9 << 8) -#define GP1_XFORMPT_3D (10 << 8) -#define GP1_XFPOLYGON_3D (11 << 8) -#define GP1_XFPOLYGON_2D (12 << 8) -#define GP1_CORENDCVEC_3D (13 << 8) -#define GP1_CGIVEC (14 << 8) -#define GP1_SETCLPLST (15 << 8) -#define GP1_SETFBINDX (16 << 8) -#define GP1_SETVWP_3D (17 << 8) -#define GP1_SETVWP_2D (18 << 8) -#define GP1_SETROP (19 << 8) -#define GP1_SETCLIPPLANES (20 << 8) -#define GP1_SETPIXPLANES (23 << 8) -#define GP1_SET_MATRIX_3D (24 << 8) -#define GP1_XFVEC_3D (25 << 8) -#define GP1_XFVEC_2D (27 << 8) -#define GP1_SETCOLOR (28 << 8) -#define GP1_SET_MATRIX_2D (29 << 8) -#define GP1_CORENDCPOLY_3D (30 << 8) -#define GP1_MATMUL_2D (32 << 8) -#define GP1_MATMUL_3D (33 << 8) -#define GP1_GETMATRIX_2D (34 << 8) -#define GP1_GETMATRIX_3D (35 << 8) -#define GP1_COREWLDVECNDC_3D (36 << 8) -#define GP1_COREWLDPOLYNDC_3D (37 << 8) -#define GP1_SET_EF_TEX (39 << 8) - -/* - * Macros for 32 bit accesses to GP shared memory. - * - * "p" is a pointer and "a" is a float or int argument. - */ - -#define GP1_PUT_S(p, a) (*p++ = a) -#define GP1_GET_S(p, a) (a = *p++) - -#ifdef mc68000 - -#define GP1_PUT_F(p, a) (* (float *) (p) = (a), \ - (p) += sizeof (float) / sizeof *(p)) -#define GP1_PUT_I(p, a) (* (int *) (p) = (a), \ - (p) += sizeof (int) / sizeof *(p)) -#define GP1_GET_F(p, a) ((a) = * (float *) (p), \ - (p) += sizeof (float) / sizeof *(p)) -#define GP1_GET_I(p, a) ((a) = * (int *) (p), \ - (p) += sizeof (int) / sizeof *(p)) - -#else mc68000 - -#define GP1_PUT_F(p, a) (((short *) (p))[0] = ((short *)&(a))[0], \ - ((short *) (p))[1] = ((short *) &(a))[1] , \ - (p) += sizeof (float) / sizeof *(p)) - -#define GP1_PUT_I(p, a) (((short *) (p))[0] = ((short *)&(a))[0], \ - ((short *) (p))[1] = ((short *) &(a))[1], \ - (p) += sizeof (int) / sizeof *(p)) - -#define GP1_GET_F(p, a) (((short *) &(a))[0] = ((short *)(p))[0], \ - ((short *) &(a))[1] = ((short *) (p))[1], \ - (p) += sizeof (float) / sizeof *(p)) - -#define GP1_GET_I(p, a) (((short *) &(a))[0] = ((short *)(p))[0], \ - ((short *) &(a))[1] = ((short *) (p))[1], \ - (p) += sizeof (int) / sizeof *(p)) - -#endif mc68000 - - -/* The names of these macros have been changed to avoid - * conflict with the pixwin calls - */ -#define gp1_pw_width(p) ((p)->pw_clipdata->pwcd_prmulti->pr_size.x) -#define gp1_pw_height(p) ((p)->pw_clipdata->pwcd_prmulti->pr_size.y) -#define gp1_pw_offset_X(p) (gp1_d((p)->pw_clipdata->pwcd_prmulti)->cgpr_offset.x) -#define gp1_pw_offset_Y(p) (gp1_d((p)->pw_clipdata->pwcd_prmulti)->cgpr_offset.y) - -#endif gp1cmds_DEFINED diff --git a/include/pixrect/gp1reg.h b/include/pixrect/gp1reg.h deleted file mode 100644 index 68c4d85a2de..00000000000 --- a/include/pixrect/gp1reg.h +++ /dev/null @@ -1,160 +0,0 @@ -/* @(#)gp1reg.h 1.11 89/03/14 SMI */ - -/* - * Copyright 1985, 1987 by Sun Microsystems, Inc. - */ - -#ifndef _sundev_gp1reg_h -#define _sundev_gp1reg_h - -#define GP1_SIZE 65536 -#define GP1_SHMEM_SIZE 32768 -#define GP1_SHMEM_OFFSET 32768 -#define GP2_SHMEM_SIZE 0x20000 - -#define GP2_SIZE 262144 - -#define GP1_BLOCK_SHORTS 512 -#define GP1_BLOCKS 32 -#define GP1_CONTROL_BLOCKS 1 -#define GP1_POST_BLOCKS 23 -#define GP1_STATIC_BLOCKS 8 - -#define GP1_POST_SLOTS 256 - -/* GP1 board layout */ -struct gp1 -{ - union gp1_reg { - struct gp1reg - { - short gpr_ident; - union { - short status; - short control; - } gpr_csr; - short gpr_ucode_addr; - short gpr_ucode_data; - } - reg; - struct gp2reg - { - short ident; -short : - 16; - u_int xp_addr; - u_int xp_data_h; - u_int xp_data_l; - u_int rp_addr; - u_int rp_data; - u_int pp_addr; - u_int pp_data_h; - u_int pp_data_l; - u_int status; - u_int control; - u_int pp_addr2; - } - reg2; - u_short ureg[16384]; - } reg; - struct gp1_shmem - { - u_short host_count; - u_short gp_count; - u_char ver_flag; - u_char alloc_sem; - u_short host_alloc_h; - u_short host_alloc_l; - u_short gp_alloc_h; - u_short gp_alloc_l; - u_char flag2; - u_char post_sem; - u_short post_buf[GP1_POST_SLOTS]; - u_char block_owners[GP1_BLOCKS]; - u_short fill280[228]; - u_short ver_release; - u_short ver_serial; - u_short fill510[2]; - u_short post[GP1_POST_BLOCKS][GP1_BLOCK_SHORTS]; - u_short stat[GP1_STATIC_BLOCKS][GP1_BLOCK_SHORTS]; - } - shmem; -}; - -/* convert block number to bit mask, owner array index */ -#define GP1_ALLOC_BIT(blk) ((u_long) 0x80000000 >> (blk)) -#define GP1_OWNER_INDEX(blk) (GP1_BLOCKS - 1 - (blk)) - -/* register offsets and bit definitions */ - -#define GP1_BOARD_IDENT_REG 0 -#define GP1_ID_MASK 0xfe -#define GP1_ID_VALUE 0xea - -#define GP1_CONTROL_REG 1 -#define GP1_CR_CLRIF 0x8000 -#define GP1_CR_IENBLE 0x0300 -#define GP1_CR_INT_TOGGLE 0x0300 -#define GP1_CR_INT_DISABLE 0x0200 -#define GP1_CR_INT_ENABLE 0x0100 -#define GP1_CR_INT_NOCHANGE 0x0000 -#define GP1_CR_RESET 0x0040 -#define GP1_CR_VP_CONTROL 0x0038 -#define GP1_CR_VP_STRT0 0x0020 -#define GP1_CR_VP_HLT 0x0010 -#define GP1_CR_VP_CONT 0x0008 -#define GP1_CR_PP_CONTROL 0x0007 -#define GP1_CR_PP_STRT0 0x0004 -#define GP1_CR_PP_HLT 0x0002 -#define GP1_CR_PP_CONT 0x0001 - -#define GP1_STATUS_REG 1 -#define GP1_SR_IFLG 0x8000 -#define GP1_SR_IEN 0x4000 -#define GP1_SR_RESET 0x0400 -#define GP1_SR_VP_STATE 0x0200 -#define GP1_SR_PP_STATE 0x0100 -#define GP1_SR_VP_STATUS 0x00F0 -#define GP1_SR_PP_STATUS 0x000F - -#define GP1_UCODE_ADDR_REG 2 -#define GP1_UCODE_DATA_REG 3 - - -/* GP2 definitions */ -#define GP2_ID_MASK 0xff -#define GP2_ID_VALUE 0xec - -/* GP2 control register bits (active low) */ -#define GP2_CR_XP_RST 0x40000000 -#define GP2_CR_XP_HLT 0x20000000 -#define GP2_CR_RP_RST 0x10000000 -#define GP2_CR_RP_HLT 0x08000000 -#define GP2_CR_PP_RST 0x02000000 -#define GP2_CR_PP_HLT 0x01000000 - -/* GP2 status register message shifts */ -#define GP2_SR_XPMSG_SHIFT 16 -#define GP2_SR_RPMSG_SHIFT 8 -#define GP2_SR_PPMSG_SHIFT 0 - - -/* shared memory offsets */ -#define GP1CB_HOST_COUNT 0 /* host command count */ -#define GP1CB_GP_COUNT 1 /* GP command count */ -#define GP1CB_ALLOC_SEM 2 /* buffer allocation semaphore */ -#define GP1CB_HOST_ALLOC_H 3 /* host block allocation bit vector */ -#define GP1CB_HOST_ALLOC_L 4 /* high/low */ -#define GP1CB_GP_ALLOC_H 5 /* GP block allocation bit vector */ -#define GP1CB_GP_ALLOC_L 6 /* high/low */ -#define GP1CB_POST_SEM 7 /* command posting semaphore */ -#define GP1CB_POST_BUF 8 /* command posting buffer, 256 words */ -#define GP1CB_BLOCK_OWNERS 264 /* minor device number for owner */ -/* of each block -- reverse order! */ - -#define GP1CB_VER_FLAG 2 /* version info is valid if */ -/* high byte is 1 */ -#define GP1CB_VER_RELEASE 508 /* major/minor release numbers */ -#define GP1CB_VER_SERIAL 509 /* serial number/version flag */ - -#endif /* _sundev_gp1reg_h */ diff --git a/include/pixrect/gp1var.h b/include/pixrect/gp1var.h deleted file mode 100644 index 23f877c020d..00000000000 --- a/include/pixrect/gp1var.h +++ /dev/null @@ -1,113 +0,0 @@ -/* @(#)gp1var.h 1.13 89/05/30 SMI */ - -/* - * Copyright 1985, 1987 by Sun Microsystems, Inc. - */ - -#ifndef gp1var_DEFINED -#define gp1var_DEFINED - -/* - * The same pixrect data structure is now used for both cg2 - * and gp1 pixrects. - */ -#include -#include -#include - - -struct gp1pr -{ - struct cg2fb *cgpr_va; /* backward source compatible */ - caddr_t gp_shmem; /* pointer to shared memory */ - int cgpr_fd; /* primary flag */ - int cgpr_planes; /* color bit plane mask reg */ - struct pr_pos cgpr_offset; /* pixrect offset */ - short cg2_index; /* cg2 board index */ - char minordev; /* true minor dev to stuff into GP */ - int gbufflag; /* gbuffer flag */ - int ioctl_fd; /* the fd to talk to the driver with */ - int ncmd; /* length of cmdver array */ - u_char *cmdver; /* version #'s for each command */ - int flags; /* misc options */ - int linebytes; /* bytes per line (pixel mode) */ - int fbtype; /* which cg is bound */ - union { - struct cg2pr cg2pr; - struct cg9_data cg9pr; - } cgpr; -}; - -#define gp1_d(pr) ((struct gp1pr *) (pr)->pr_data) -#define gp1_fbfrompr(pr) (gp1_d(pr)->cgpr.cg2pr.cgpr_va) -#define GP1_COPY_TO_CG2(gp_data, cg2_data) { \ - (cg2_data)->gp_shmem = (gp_data)->gp_shmem; \ - (cg2_data)->cg2_index = (gp_data)->cg2_index; \ - (cg2_data)->gbufflag = (gp_data)->gbufflag; \ - (cg2_data)->minordev = (gp_data)->minordev; \ - (cg2_data)->cmdver = (gp_data)->cmdver; \ - (cg2_data)->ncmd = (gp_data)->ncmd; \ - (cg2_data)->ioctl_fd = (gp_data)->ioctl_fd; \ - (cg2_data)->flags = (gp_data)->flags; \ -} - -#define GP1_COPY_FROM_CG2(cg2_data, gp_data) { \ - (gp_data)->cgpr_fd = (cg2_data)->cgpr_fd; \ - (gp_data)->cgpr_planes = (cg2_data)->cgpr_planes; \ - (gp_data)->cgpr_offset = (cg2_data)->cgpr_offset; \ - (gp_data)->cgpr_va = (cg2_data)->cgpr_va; \ - (gp_data)->flags = (cg2_data)->flags; \ - (gp_data)->linebytes = (cg2_data)->linebytes; \ -} - -#define GP1_COPY_TOTAL(srcdata, destdata) { \ - (destdata)->gp_shmem = (srcdata)->gp_shmem; \ - (destdata)->cgpr_fd = (srcdata)->cgpr_fd; \ - (destdata)->cgpr_va = (srcdata)->cgpr_va; \ - (destdata)->cgpr_planes = (srcdata)->cgpr_planes; \ - (destdata)->cgpr_offset = (srcdata)->cgpr_offset; \ - (destdata)->cg2_index = (srcdata)->cg2_index; \ - (destdata)->minordev = (srcdata)->minordev; \ - (destdata)->gbufflag = (srcdata)->gbufflag; \ - (destdata)->ioctl_fd = (srcdata)->ioctl_fd; \ - (destdata)->ncmd = (srcdata)->ncmd; \ - (destdata)->cmdver = (srcdata)->cmdver; \ - (destdata)->flags = (srcdata)->flags; \ - (destdata)->linebytes = (srcdata)->linebytes; \ -} - -struct gp1_version -{ - u_char majrel; - u_char minrel; - u_char serialnum; - u_char flags; -}; - -#ifndef KERNEL -Pixrect *gp1_make(); - -extern struct pixrectops gp1_ops; - -int gp1_rop(); -int gp1_vector(); -int gp1_destroy(); -int gp1_put(); -int gp1_get(); -int gp1_putattributes(); -int gp1_putcolormap(); -int gp1_getattributes(); -int gp1_getcolormap(); -int gp1_ioctl(); -Pixrect *gp1_region(); -int gp1_batchrop(); -int gp1_stencil(); -int gp1_polypoint(); - -#endif !KERNEL - -#define GP1IO_SATTR _IOW(G, 101, struct fbgattr) -#define GP1IO_SCMAP _IO(G, 102) -#define GP_SHMEMSIZE 5 - -#endif gp1var_DEFINED diff --git a/include/pixrect/gt_fbi.h b/include/pixrect/gt_fbi.h deleted file mode 100644 index 398f808eb64..00000000000 --- a/include/pixrect/gt_fbi.h +++ /dev/null @@ -1,944 +0,0 @@ -/* @(#)gt_fbi.h 1.4 91/05/31 SMI */ -#ifndef gt_fbi_DEFINED -#define gt_fbi_DEFINED - -/* - * Copyright 1989, Sun Microsystems, Inc. - */ - -/* Hawk FB Input control space register definitions */ - -/* Copy destination address register */ -#define HKPF_CDA_ADDR 0x00100000 /* Copy destination */ -#define HKPF_CDA_MASK 0x00FFFFFF -#define HKPF_CDA_PG_MASK 0x00C00000 /* Plane group */ -#define HKPF_CDA_PG_IMAGE 0x00000000 -#define HKPF_CDA_PG_DEPTH 0x00400000 -#define HKPF_CDA_PG_WINDOW 0x00800000 -#define HKPF_CDA_PG_IMAGE_DEPTH 0x00C00000 -#define HKPF_CDA_Y_MASK 0x003FF800 -#define HKPF_CDA_X_MASK 0x000007FF -#define HKPF_CDA_XY_MASK 0x003FFFFF -#define HKPF_CDA_Y_SHIFT 11 -#define HKPF_CDA_X_SHIFT 0 - -/* Fill destination address register */ -/* Note: COPY_LEFT must be 0 in copy/fill direction register! */ -#define HKPF_FDA_ADDR 0x00100004 /* Fill source */ -#define HKPF_FDA_MASK 0x00FFFFFF -#define HKPF_FDA_PG_MASK 0x00C00000 /* Plane group */ -#define HKPF_FDA_PG_IMAGE 0x00000000 -#define HKPF_FDA_PG_DEPTH 0x00400000 -#define HKPF_FDA_PG_WINDOW 0x00800000 -/* Image_depth is illegal */ -#define HKPF_FDA_Y_MASK 0x003FF800 -#define HKPF_FDA_X_MASK 0x000007FF -#define HKPF_FDA_XY_MASK 0x003FFFFF -#define HKPF_FDA_Y_SHIFT 11 -#define HKPF_FDA_X_SHIFT 0 -/* View clip registers */ -#define HKPP_VCX_ADDR 0x0020008C -#define HKPP_VCX_MASK 0x07FF07FF /* Mask, then shift */ -#define HKPP_VCY_ADDR 0x00200094 -#define HKPP_VCY_MASK 0x07FF07FF -#define HKPP_VCXY_MASK 0x000007FF -#define HKPP_VCX_LEFT_SHIFT 16 -#define HKPP_VCX_RIGHT_SHIFT 0 -#define HKPP_VCY_TOP_SHIFT 16 -#define HKPP_VCY_BOTTOM_SHIFT 0 - -/* Pick aperture registers */ -#define HKPP_PAX_ADDR 0x00200098 /* X left and right */ -#define HKPP_PAX_MASK 0x07FF07FF -#define HKPP_PAY_ADDR 0x002000A4 /* Y top and bottom */ -#define HKPP_PAY_MASK 0x07FF07FF -#define HKPP_PAF_ADDR 0x002000A8 /* Front */ -#define HKPP_PAB_ADDR 0x002000B0 /* Back */ -#define HKPP_PAXY_MASK 0x000007FF -#define HKPP_PAX_LEFT_SHIFT 16 -#define HKPP_PAX_RIGHT_SHIFT 0 -#define HKPP_PAY_TOP_SHIFT 16 -#define HKPP_PAY_BOTTOM_SHIFT 0 -#define HKPP_PAZ_MASK 0x00FFFFFF /* Front or back */ - -/* Pick control register */ -#define HKPP_PC_ADDR 0x002000C4 -#define HKPP_PC_MASK 0x00000007 -#define HKPP_PC_PICK_ENA 0x00000004 -#define HKPP_PC_PICK_WHL_RENDER 0x00000002 -#define HKPP_PC_PICK_3D_APER 0x00000001 - -/* Frame buffer width register */ -#define HKPP_FBW_ADDR 0x002000C8 -#define HKPP_FBW_MASK 0x00000003 -#define HKPP_FBW_1280 0x00000000 /* 1280 (x 1024) */ -#define HKPP_FBW_1920 0x00000001 /* 1920 (x 1035) */ -#define HKPP_FBW_960 0x00000002 /* 960 (x 680) */ -#define HKPP_FBW_960STEREO 0x00000003 /* 960 (x 680) Stereo */ - -/* Stereo write enable */ -#define HKPP_SWE_ADDR 0x002000D0 -#define HKPP_SWE_MASK 0x00000003 -#define HKPP_SWE_MONO 0x00000000 /* 0 = mono */ -#define HKPP_SWE_STEREO 0x00000001 /* 1 = stereo */ -#define HKPP_SWE_RIGHT 0x00000010 /* 2 = right eye */ - - -/* Interleave test register */ -#define HKPP_IT_ADDR 0x002000E0 -#define HKPP_IT_MASK 0x0000000F -#define HKPP_IT_BANK_ID 0x00000007 -#define HKPP_IT_TEST_ENABLE 0x00000008 - -/* Screen door transparency matrix (Note start address not on even boundary) */ -#define HKPP_SDTM_ADDR 0x00200104 /* 20 registers +0x04 apart */ -#define HKPP_SDTM_ADDR_MASK 0x0000007C -#define HKPP_SDTM_MASK 0x0000FFFF -#define HKPP_SDTM_COLUMNS 20 /* Width of screen door transp matrix */ -#define HKPP_SDTM_BITS 16 /* Number of bits for sdtm word */ - -/* Screen door transparency enable */ -#define HKPP_SDTE_ADDR 0x00200180 -#define HKPP_SDTE_MASK 0x00000001 -#define HKPP_SDTE_ENA 0x00000001 /* Use screen door pattern */ - -/* Buffer select register */ -#define HKPP_BS_ADDR 0x00200204 -#define HKPP_BS_MASK 0x0000003F -#define HKPP_BS_I_WRITE_A 0x00000001 /* Write image A */ -#define HKPP_BS_I_WRITE_B 0x00000002 /* (Both may be on) */ -#define HKPP_BS_I_READ_B 0x00000004 /* 0 = read image A */ -#define HKPP_BS_O_WRITE_A 0x00000001 /* Write overlay A */ -#define HKPP_BS_O_WRITE_B 0x00000002 /* Both may be on */ -#define HKPP_BS_O_READ_B 0x00000004 /* 0 = read overlay A */ - -/* Fast clear control register */ -#define HKPP_FCC_ADDR 0x00200210 -#define HKPP_FCC_MASK 0x00000003 -#define HKPP_FCC_NORMAL 0x00000000 -#define HKPP_FCC_INITIALIZE 0x00000002 -#define HKPP_FCC_FILL 0x00000003 - -/* Current window ID register */ -#define HKPP_CWID_ADDR 0x00200400 -#define HKPP_CWID_MASK 0x000003FF - -/* Window ID control register */ -#define HKPP_WIDC_ADDR 0x00200404 -#define HKPP_WIDC_MASK 0x800003FF -#define HKPP_WIDC_REPLACE_WID 0x80000000 /* Enable WID replace mode */ -#define HKPP_WIDC_WID_MASK 0x000003FF -/* A "1" means the bit is compared */ - -/* Window Background register */ -#define HKPP_WBG_ADDR 0x00200408 -/* No mask. 32 bits of alpha, blue, green and red. */ - -/* Constant Z source */ -#define HKPP_CZS_ADDR 0x0020040C -#define HKPP_CZS_MASK 0x00FFFFFF - -/* Z control */ -#define HKPP_ZC_ADDR 0x00200410 -#define HKPP_ZC_MASK 0x0000000F -#define HKPP_ZC_WID_EXT 0x00000001 /* WID extension clip enable */ -#define HKPP_ZC_CONST_Z 0x00000002 /* Constant Z enable */ -#define HKPP_ZC_WRITE_ENA 0x00000004 /* Z write enable */ -#define HKPP_ZC_COMPARE 0x00000008 /* HSR enable (compare) */ - -/* Image write mask register */ -#define HKPP_IWM_ADDR 0x00200414 -/* No mask. 32 bits of alpha, blue, green and red. */ - -/* Window write mask register */ -#define HKPP_WWM_ADDR 0x00200418 -#define HKPP_WWM_MASK 0x00001FFF -#define HKPP_WWM_FC 0x00001000 /* Fast clear */ -#define HKPP_WWM_CD 0x00000800 /* Cursor data */ -#define HKPP_WWM_CE 0x00000400 /* Cursor enable */ -#define HKPP_WWM_WID 0x000003FF /* Window ID planes */ - -/* Byte mode channel select */ -#define HKPP_BMCS_ADDR 0x0020041C -#define HKPP_BMCS_MASK 0x00000003 -#define HKPP_BMCS_ALPHA_OV 0x00000000 -#define HKPP_BMCS_BLUE 0x00000001 -#define HKPP_BMCS_GREEN 0x00000002 -#define HKPP_BMCS_RED 0x00000003 - -/* Byte mode write mask register */ -#define HKPP_BMWM_ADDR 0x00200420 -#define HKPP_BMWM_MASK 0x000000FF -/* ROP/Blend operation register */ -#define HKPP_RBO_ADDR 0x00200424 -#define HKPP_RBO_MASK 0x0000001F -#define HKPP_RBO_BLEND 0x00000010 /* Enable blending (not ROP) */ -#define HKPP_RBO_ROP_MASK 0x0000000F -/* ROP definitions */ -#define HKPP_ROP_ZERO 0x00 -#define HKPP_ROP_NSRC_AND_NDST 0x01 -#define HKPP_ROP_NSRC_AND_DST 0x02 -#define HKPP_ROP_NSRC 0x03 -#define HKPP_ROP_SRC_AND_NDST 0x04 -#define HKPP_ROP_NDST 0x05 -#define HKPP_ROP_SRC_XOR_DST 0x06 -#define HKPP_ROP_NSRC_OR_NDST 0x07 -#define HKPP_ROP_SRC_AND_DST 0x08 -#define HKPP_ROP_NSRC_XOR_DST 0x09 -#define HKPP_ROP_DST 0x0A -#define HKPP_ROP_NSRC_OR_DST 0x0B -#define HKPP_ROP_SRC 0x0C /* Direct write */ -#define HKPP_ROP_SRC_OR_NDST 0x0D -#define HKPP_ROP_SRC_OR_DST 0x0E -#define HKPP_ROP_ONE 0x0F - -/* Mpg and fcs control register */ -#define HKPP_MPG_ADDR 0x00200434 -#define HKPP_MPG_MASK 0x000000FF -#define HKPP_MPG_FCS_MASK 0x00000007 -#define HKPP_MPG_FCS_DISABLE 0x00000004 -#define HKPP_MPG_WRITE_EN_MASK 0x000000F8 -#define HKPP_MPG_WRITE_RGB 0x000000E0 -#define HKPP_MPG_WRITE_OV 0x00000010 -#define HKPP_MPG_WRITE_Z 0x00000008 - -/* Stencil mask */ -#define HKPF_SM_ADDR 0x00200C00 /* All 32 bits */ - -/* Stencil foreground color */ -#define HKPF_SFC_ADDR 0x00200C04 /* All 32 bits */ - -/* Stencil background color */ -#define HKPF_SBC_ADDR 0x00200C08 /* All 32 bits */ - -/* Stencil transparency flag */ -#define HKPF_STF_ADDR 0x00200C0C -#define HKPF_STF_MASK 0x00000001 -#define HKPF_STF_TRANSPARENT 0x00000001 /* Transparent */ -#define HKPF_STF_USE_BG 0x00000000 /* Use background color */ - -/* Copy/fill direction/size register */ -#define HKPF_CFDS_ADDR 0x00200C10 -#define HKPF_CFDS_MASK 0x803FFFFF -#define HKPF_CFDS_COPY_LEFT 0x80000000 /* Copy right to left */ -#define HKPF_CFDS_COPY_HEIGHT_MASK 0x003FF800 /* Pixel count up and down */ -#define HKPF_CFDS_COPY_WIDTH_MASK 0x000007FF /* Pixel count across */ -#define HKPF_CFDS_XY_MASK 0x003FFFFF -#define HKPF_CFDS_COPY_HEIGHT_SHIFT 11 -#define HKPF_CFDS_COPY_WIDTH_SHIFT 0 - -/* Copy source address registers */ -#define HKPF_CSA_ADDR 0x00200C14 /* Copy source */ -#define HKPF_CSA_MASK 0x00FFFFFF -#define HKPF_CSA_PG_MASK 0x00C00000 /* Plane group */ -#define HKPF_CSA_PG_IMAGE 0x00000000 -#define HKPF_CSA_PG_DEPTH 0x00400000 -#define HKPF_CSA_PG_WINDOW 0x00800000 -#define HKPF_CSA_PG_IMAGE_DEPTH 0x00C00000 -#define HKPF_CSA_Y_MASK 0x003FF800 -#define HKPF_CSA_X_MASK 0x000007FF -#define HKPF_CSA_XY_MASK 0x003FFFFF -#define HKPF_CSA_Y_SHIFT 11 -#define HKPF_CSA_X_SHIFT 0 - - -/* Every hardware is defined in two ways - 1. The bitwise definition - of the register (reg) and 2. the whole register as a word (wd). -*/ - -/* PF Copy destination address reg - RW * - * gg values : 00 - image plngrp - * 01 - depth plngrp - * 10 - window plngrp - * 11 - image &depth in parallel - */ -typedef struct -{ -unsigned : - 8; -unsigned gg: - 2; /* copy destination plngrp */ -unsigned start_y: - 11; -unsigned start_x: - 11; -} -H_fbi_cp_dst_reg_bit; - -typedef union { - H_fbi_cp_dst_reg_bit reg; - u_int wd; -} H_fbi_cp_dst_reg; - - -/* PF fill destination address reg - RW * - * gg values : 00 - image plngrp - * 01 - depth plngrp - * 10 - window plngrp - * 11 - ILLEGAL - */ -typedef struct -{ -unsigned : - 8; -unsigned gg: - 2; /* fill destination plngrp */ -unsigned start_y: - 11; -unsigned start_x: - 11; -} -H_fbi_fl_dst_reg_bit; - -typedef union { - H_fbi_fl_dst_reg_bit reg; - u_int wd; -} H_fbi_fl_dst_reg; - - -/* PP View Clip X bounds reg - RW - specifies VP LtoR */ -typedef struct -{ -unsigned : - 5; -unsigned l_bound: - 11; -unsigned : - 5; -unsigned r_bound: - 11; -} -H_fbi_vwclp_x_reg_bit; - -typedef union { - H_fbi_vwclp_x_reg_bit reg; - u_int wd; -} H_fbi_vwclp_x_reg; - - -/* PP View Clip Y bounds reg - RW - specifies VP top to bot */ -typedef struct -{ -unsigned : - 5; -unsigned t_bound: - 11; -unsigned : - 5; -unsigned b_bound: - 11; -} -H_fbi_vwclp_y_reg_bit; - -typedef union { - H_fbi_vwclp_y_reg_bit reg; - u_int wd; -} H_fbi_vwclp_y_reg; - - -/* PP Pick aperture X bounds reg - RW */ -typedef struct -{ -unsigned r_bound: - 11; -unsigned : - 5; -unsigned l_bound: - 11; -unsigned : - 5; -} -H_fbi_pick_x_reg_bit; - -typedef union { - H_fbi_pick_x_reg_bit reg; - u_int wd; -} H_fbi_pick_x_reg; - - -/* PP Pick aperture Y bounds reg - RW */ -typedef struct -{ -unsigned b_bound: - 11; -unsigned : - 5; -unsigned t_bound: - 11; -unsigned : - 5; -} -H_fbi_pick_y_reg_bit; - -typedef union { - H_fbi_pick_y_reg_bit reg; - u_int wd; -} H_fbi_pick_y_reg; - - -/* PP Pick aperture front bounds reg - RW */ -typedef struct -{ -unsigned f_bound: - 24; -unsigned : - 8; -} -H_fbi_pick_f_reg_bit; - -typedef union { - H_fbi_pick_f_reg_bit reg; - u_int wd; -} H_fbi_pick_f_reg; - - -/* PP Pick aperture back bounds reg - RW */ -typedef struct -{ -unsigned b_bound: - 24; -unsigned : - 8; -} -H_fbi_pick_b_reg_bit; - -typedef union { - H_fbi_pick_b_reg_bit reg; - u_int wd; -} H_fbi_pick_b_reg; - -/* PP Pick control reg - RW */ -typedef struct -{ -unsigned ap: - 1; -unsigned ren_pic: - 1; -unsigned pic_on: - 1; -unsigned : - 29; -} -H_fbi_pick_ctrl_reg_bit; - -typedef union { - H_fbi_pick_ctrl_reg_bit reg; - u_int wd; -} H_fbi_pick_ctrl_reg; - -/* PP FB width reg - RW */ -typedef struct -{ -unsigned : - 29; -unsigned width: - 2; -} -H_fbi_fb_width_reg_bit; - -typedef union { - H_fbi_fb_width_reg_bit reg; - u_int wd; -} H_fbi_fb_width_reg; - - -/* PP Stereo Control reg - RW */ -typedef struct -{ -unsigned : - 29; -unsigned st_on: - 2; /* Duplicate write enable:0-mono - * 1-stereo */ -} -H_fbi_stereo_reg_bit; - -typedef union { - H_fbi_stereo_reg_bit reg; - u_int wd; -} H_fbi_stereo_reg; - -/* PP buffer select reg - RW */ -typedef struct -{ -unsigned : - 26; -unsigned ao_read_b: - 1; /* alpha/overlay: read buf B */ -unsigned ao_write_b: - 1; /* write buffer B */ -unsigned ao_write_a: - 1; /* write buffer A */ -unsigned rgb_read_b: - 1; /* RGB:read buffer B */ -unsigned rgb_write_b: - 1; /* write buffer B */ -unsigned rgb_write_a: - 1; /* write buffer A */ -} -H_fbi_buf_sel_reg_bit; - -typedef union { - H_fbi_buf_sel_reg_bit reg; - u_int wd; -} H_fbi_buf_sel_reg; - - -/* PP Fast Clear Control reg RW */ -typedef struct -{ -unsigned fcc_ctrl: - 3; -unsigned : - 29; -} -H_fbi_fcc_ctrl_reg_bit; - -typedef union { - H_fbi_fcc_ctrl_reg_bit reg; - u_int wd; -} H_fbi_fcc_ctrl_reg; - - -/* PP current window id reg - RW */ -typedef struct -{ -unsigned : - 22; -unsigned cwid: - 10; -} -H_fbi_cur_wid_reg_bit; - -typedef union { - H_fbi_cur_wid_reg_bit reg; - u_int wd; -} H_fbi_cur_wid_reg; - -/* PP current WID control reg - RW */ -typedef struct -{ -unsigned wid_repl: - 1; /* enable WID replace mode */ -unsigned : - 21; -unsigned wid_m: - 10; /* WID mask bits */ -} -H_fbi_wid_mask_reg_bit; - -typedef union { - H_fbi_wid_mask_reg_bit reg; - u_int wd; -} H_fbi_wid_mask_reg; - - -/* PP Constant Z source reg */ -typedef struct -{ -unsigned z_src: - 24; -unsigned : - 8; -} -H_fbi_con_z_reg_bit; - -typedef union { - H_fbi_con_z_reg_bit reg; - u_int wd; -} H_fbi_con_z_reg; - -/* PP Z Control reg - see documentation for this*/ -typedef struct -{ -unsigned x_bit: - 1; -unsigned c_bit: - 1; -unsigned w_bit: - 1; -unsigned h_bit: - 1; -unsigned : - 28; -} -H_fbi_z_ctrl_reg_bit; - -typedef union { - H_fbi_z_ctrl_reg_bit reg; - u_int wd; -} H_fbi_z_ctrl_reg; - - -/* PP Image write mask reg - RW */ -typedef struct -{ -unsigned alpha_over: - 8; -unsigned blue: - 8; -unsigned green: - 8; -unsigned red: - 8; -} -H_fbi_im_wmask_reg_bit; - -typedef union { - H_fbi_im_wmask_reg_bit reg; - u_int wd; -} H_fbi_im_wmask_reg; - -/* PP window write mask reg - RW */ -typedef struct -{ -unsigned : - 19; /* unused */ -unsigned fast_clr: - 1; /* fast clear planes */ -unsigned crs_data: - 1; /* cursor data */ -unsigned crs_ena: - 1; /* cursor enable */ -unsigned wid: - 10; /* WID planes */ -} -H_fbi_win_wmask_reg_bit; - -typedef union { - H_fbi_win_wmask_reg_bit reg; - u_int wd; -} H_fbi_win_wmask_reg; - -/* PP byte mode channel select reg - RW . - * 0-alpha/overlay 1-blue 2-green 3-red - */ -typedef struct -{ -unsigned : - 20; -unsigned bmode: - 2; -} -H_fbi_byte_mode_reg_bit; - -typedef union { - H_fbi_byte_mode_reg_bit reg; - u_int wd; -} H_fbi_byte_mode_reg; - -/* PP byte mode write mask reg - RW . - * 0-alpha/overlay 1-blue 2-green 3-red - */ -typedef struct -{ -unsigned : - 24; -unsigned bmask: - 8; -} -H_fbi_byte_wmask_reg_bit; - -typedef union { - H_fbi_byte_wmask_reg_bit reg; - u_int wd; -} H_fbi_byte_wmask_reg; - -/* PP ROP/Blend reg - RW. - * Bit 4 must be 0 for state set 0. - */ -typedef struct -{ -unsigned : - 27; -unsigned bl_or_rop: - 1; -unsigned brop: - 4; -} -H_fbi_rop_reg_bit; - -typedef union { - H_fbi_rop_reg_bit reg; - u_int wd; -} H_fbi_rop_reg; - -typedef struct -{ -unsigned : - 24; -unsigned mpg_set: - 8; -} -H_fbi_mpg_reg_bit; - -typedef union { - H_fbi_mpg_reg_bit reg; - u_int wd; -} H_fbi_mpg_reg; - -/* PP Stencil mask RW */ -typedef struct -{ -unsigned mask: - 32; -} -H_fbi_sten_mask_reg_bit; - -typedef union { - H_fbi_sten_mask_reg_bit reg; - u_int wd; -} H_fbi_sten_mask_reg; - -/* PF Foreground color - RW */ -/* Image planes */ -typedef struct -{ -unsigned alpha_over: - 8; -unsigned blue: - 8; -unsigned green: - 8; -unsigned red: - 8; -} -H_fbi_im_sten_fg_reg_bit; - -typedef union { - H_fbi_im_sten_fg_reg_bit reg; - u_int wd; -} H_fbi_im_sten_fg_reg; - -/* depth planes */ -typedef struct -{ -unsigned : - 8; -unsigned depth: - 24; -} -H_fbi_dep_sten_fg_reg_bit; - -typedef union { - H_fbi_dep_sten_fg_reg_bit reg; - u_int wd; -} H_fbi_dep_sten_fg_reg; - -/* window id planes */ -typedef struct -{ -unsigned : - 12; -unsigned fc: - 4; -unsigned : - 4; -unsigned curs_data: - 1; -unsigned cur_enab: - 1; -unsigned wid_pl: - 10; -} -H_fbi_wid_sten_fg_reg_bit; - -typedef union { - H_fbi_wid_sten_fg_reg_bit reg; - u_int wd; -} H_fbi_wid_sten_fg_reg; - -typedef union { - H_fbi_im_sten_fg_reg_bit fg_im; - H_fbi_dep_sten_fg_reg_bit fg_dep; - H_fbi_wid_sten_fg_reg_bit fg_wid; - u_int wd; -} H_fbi_sten_fg_reg; - -/* PF Stencil background color */ -/* Image planes */ -typedef struct -{ -unsigned alpha_over: - 8; -unsigned blue: - 8; -unsigned green: - 8; -unsigned red: - 8; -} -H_fbi_im_sten_bg_reg_bit; - -typedef union { - H_fbi_im_sten_bg_reg_bit reg; - u_int wd; -} H_fbi_im_sten_bg_reg; - -/* depth planes */ -typedef struct -{ -unsigned : - 8; -unsigned depth: - 24; -} -H_fbi_dep_sten_bg_reg_bit; - -typedef union { - H_fbi_dep_sten_bg_reg_bit reg; - u_int wd; -} H_fbi_dep_sten_bg_reg; - -/* window id planes */ -typedef struct -{ -unsigned : - 12; -unsigned fc: - 4; -unsigned : - 4; -unsigned curs_data: - 1; -unsigned cur_enab: - 1; -unsigned wid_pl: - 10; -} -H_fbi_wid_sten_bg_reg_bit; - -typedef union { - H_fbi_wid_sten_bg_reg_bit reg; - u_int wd; -} H_fbi_wid_sten_bg_reg; - -typedef union { - H_fbi_im_sten_bg_reg_bit bg_im; - H_fbi_dep_sten_bg_reg_bit bg_dep; - H_fbi_wid_sten_bg_reg_bit bg_wid; - u_int wd -} H_fbi_sten_bg_reg; - - - -/* PF Stencil Transparency flag - RW */ -typedef struct -{ -unsigned : - 31; -unsigned stransp: - 1; /* stencil transparency */ -} -H_fbi_sten_transp_reg_bit; - -typedef union { - H_fbi_sten_transp_reg_bit reg; - u_int wd; -} H_fbi_sten_transp_reg; - -/* PF Copy source address reg - RW * - * gg values : 00 - image plngrp - * 01 - depth plngrp - * 10 - window plngrp - * 11 - image &depth in parallel - */ -typedef struct -{ -unsigned : - 8; -unsigned gg: - 2; /* copy src plngrp */ -unsigned start_y: - 11; -unsigned start_x: - 11; -} -H_fbi_cp_src_reg_bit; - -typedef union { - H_fbi_cp_src_reg_bit reg; - u_int wd; -} H_fbi_cp_src_reg; - - -/* PF Copy/fill dir/size reg - RW * - * D- copy direction - * 0 - outer loop top to bot, inner loop L to R; start@upper L - * 1 - outer loop bot to top, inner loop R to L; start@lower R - * D=0 for fills. - */ -typedef struct -{ -unsigned dir: - 1; /* fill dir */ -unsigned : - 9; -unsigned hgt: - 11; -unsigned wdt: - 11; -} -H_fbi_dir_sz_reg_bit; - -typedef union { - H_fbi_dir_sz_reg_bit reg; - u_int wd; -} H_fbi_dir_sz_reg; - -/* FBI registers defined as a structure - from a pixrect view point */ - -typedef struct -{ - H_fbi_cp_dst_reg copy_dst; - H_fbi_fl_dst_reg fill_dst; -} -H_fbi_go; - - -typedef struct -{ -#define HPAD0 0x8c - u_char pad0[HPAD0]; - H_fbi_vwclp_x_reg vwclp_x; -#define HPAD1 0x4 - u_char pad1[HPAD1]; - H_fbi_vwclp_y_reg vwclp_y; -#define HPAD2 0x30 - u_char pad2[HPAD2]; - H_fbi_fb_width_reg fb_wid; -#define HPAD3 0x138 - u_char pad3[HPAD3]; - H_fbi_buf_sel_reg buf_sel; - H_fbi_stereo_reg stereo; -#define HPAD4 0x1f4 - u_char pad4[HPAD4]; - H_fbi_cur_wid_reg cur_wid; - H_fbi_wid_mask_reg wid_mask; -#define HPAD5 0x4 - u_char pad5[HPAD5]; - H_fbi_con_z_reg con_z; - H_fbi_z_ctrl_reg z_ctrl; - H_fbi_im_wmask_reg i_wmask; - H_fbi_win_wmask_reg w_wmask; - H_fbi_byte_mode_reg b_mode; - H_fbi_byte_wmask_reg b_wmask; - H_fbi_rop_reg rop; -#define HPAD6 0x0c - u_char pad6[HPAD6]; - H_fbi_mpg_reg mpg_set; -#define HPAD7 0x7c8 - u_char pad7[HPAD7]; - H_fbi_sten_mask_reg sten_mask; - H_fbi_sten_fg_reg fg_col; - H_fbi_sten_bg_reg bg_col; - H_fbi_sten_transp_reg transp_flag; - H_fbi_dir_sz_reg dir_size; - H_fbi_cp_src_reg copy_src; - - -} -H_fbi; - - -#endif /* !gt_fbi_DEFINED */ diff --git a/include/pixrect/gt_rp.h b/include/pixrect/gt_rp.h deleted file mode 100644 index ffba1d96f0c..00000000000 --- a/include/pixrect/gt_rp.h +++ /dev/null @@ -1,116 +0,0 @@ -/* @(#)gt_rp.h 1.2 91/03/17 SMI */ -#ifndef gt_rp_DEFINED -#define gt_rp_DEFINED - -/* - * @(#)gt_rp.h 1.4 90/08/14 Copyright 1989, Sun Microsystems, Inc. - */ - - -/* - * RP Control Space Hardware registers - most of the registers here - * are used only by diagnostic and Initialisation. - */ -/* Host Frame Buffer Address Space */ -#define HKPBM_HFBAS_ADDR 0x00090000 -#define HKPBM_HFBAS_MASK 0x00000007 -#define HKPBM_HFBAS_ST_IMAGE 0x00000000 /* Stencil image */ -#define HKPBM_HFBAS_ST_DEPTH 0x00000001 /* Stencil depth */ -#define HKPBM_HFBAS_ST_WINDOW 0x00000002 /* Stencil window */ -#define HKPBM_HFBAS_CURSOR_BYTE 0x00000003 /* Cursor, image-byte */ -#define HKPBM_HFBAS_IMAGE 0x00000004 /* Pixel image */ -#define HKPBM_HFBAS_DEPTH 0x00000005 /* Pixel depth */ -#define HKPBM_HFBAS_WINDOW 0x00000006 /* Pixel window */ -#define HKPBM_HFBAS_IMAGE_DEPTH 0x00000007 /* Pixel image/depth */ - -/* Host control and status register for PBM */ -#define HKPBM_HCS_ADDR 0x00090004 -#define HKPBM_HCS_WRITE_MASK 0x00000011 /* Writable bits in register */ -#define HKPBM_HCS_HFBSS 0x00000001 /* Host FB state set */ -#define HKPBM_HCS_VR 0x00000002 /* Vertical retrace */ -#define HKPBM_HCS_RPST 0x00000008 /* RP stalled */ -#define HKPBM_HCS_HSRP 0x00000010 /* Host stalling RP */ -#define HKPBM_HCS_PBB 0x00000020 /* Pixel formatter busy */ -#define HKPBM_HCS_PFB 0x00000040 /* Pixel bus busy */ - -/* Host FB Address Space reg - RW*/ -typedef struct -{ -unsigned : - 29; /* not used*/ -unsigned as: - 3; /* Access mode and plane group */ -} -H_rp_as_reg_bit; - -typedef union { - H_rp_as_reg_bit reg; - unsigned int wd; -} H_rp_as_reg; - - -/* Host PBM control space reg - RW. - * Note on RP - it can be stalled by FE or Host or RP Semaphore or - * by wait for vertical retrace - */ -typedef struct -{ -unsigned : - 25; /* not used*/ -unsigned pf_busy: - 1; /* Pixel bus busy? RO */ -unsigned pb_busy: - 1; /* Pixel formatter busy? RO */ -unsigned host_stall: - 1; /* Host stalling RP? RW*/ -unsigned H_rp_stall: - 1; /* RP stalled? RO */ -unsigned : - 1; /* not used */ -unsigned v_retrace: - 1; /* Vertical retrace? RO */ -unsigned fb_stateset: - 1; /* Host FB stateset. RW */ -} -H_rp_csr_reg_bit; - -typedef union { - H_rp_csr_reg_bit reg; - unsigned int wd; -} H_rp_csr_reg; - -/* RP registers defined as a structure - from a pixrect view point */ - -typedef struct -{ - H_rp_as_reg as_reg; /* 0 */ - H_rp_csr_reg csr_reg; /* 1 */ -} -H_rp; - -/* This is the register to control the front end hold */ - -#define HKFE_HOLD_REQ 0x1 /* Request for FE hold */ -#define HKFE_HOLD_ACK 0x2 /* FE acks hold */ - -typedef struct -{ -unsigned : - 30; /* not used*/ -unsigned fe_hold: - 2; /* Front end hold/ack bits */ -} -H_fe_hold_reg_bit; - -typedef union { - H_fe_hold_reg_bit reg; - unsigned int wd; -} H_fe_hold_reg; - -typedef struct -{ - H_fe_hold_reg fe_hold_reg; /* 0 */ -} -H_fe_hold; - -#endif /* gt_rp_DEFINED */ diff --git a/include/pixrect/gtvar.h b/include/pixrect/gtvar.h deleted file mode 100644 index 6cd68f30117..00000000000 --- a/include/pixrect/gtvar.h +++ /dev/null @@ -1,330 +0,0 @@ -/* @(#)gtvar.h 1.9 91/08/16 SMI */ - -/* Copyright (c) 1989 by Sun Microsystems, Inc. */ - -/* - * GT Header File - * Describe "Private Data" of GT Pixrect, also external - * references to pixrect operation, and some macros. - */ -#ifndef gtvar_DEFINED -#define gtvar_DEFINED -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define TRUE 1 -#define GT_NFBS 6 /* number of frame buffers in hawk */ -#define GT_DEPTH_24 32 -#define GT_DEPTH_WID 32 -#define GT_DEPTH_8 8 -#define GT_DEPTH_1 1 -#define GT_OVERLAY_SHIFT24 24 -#define GT_IMAGE_LINEBYTES 8192 -#define GT_OVERLAY_LINEBYTES 2048 -#define GT_BYTES_PER_WORD 4 -#define GT_SRC1_PIX_PER_WORD 32 -#define GT_SRC1_PIX_PER_BYTE 8 -#define GT_STEN_FAC 4 /* In sten mode addr incr= 4*(#pixels)*/ -#define GT_STEN_INCR 128 /* addr incr for u_long =4*32 */ -#define GT_COPY_HACK 15 -#define GT_DBL_BUF_OFF 0x0 -#define GT_DBL_BUF_ON 0x1 -#define GT_DBL_FORE 2 /* Just like PW_DBL_FORE in pw_dbl.h */ -#define GT_DBL_BACK 3 -#define GT_DBL_BOTH 4 -#define GT_DBL_NONE 5 -#define GT_DISP_STEREO 0x1 /* Display/monitor is stereo */ - - - -#define FALSE 0 -/* description of single GT frame buffer */ -struct gt_fb -{ - int group; - int depth; - struct mprp_data mprp; - int state; -}; - -/* GT Pixrect private data */ -struct gt_data -{ - struct mprp_data mprp; /* memory pixrect simulator */ - int flag; /* multi purpose flag */ - int planes; /* current group and mask */ - int fd; /* file descriptor */ - int buf; /* selected buffer */ - struct gt_fb fb[GT_NFBS]; /* frame buffer info */ - short active; /* active fb no. */ - short wid_part; /* Partition of wids bet I/O */ - struct fb_wid_dbl_info wid8; /* for 8bit windows */ - struct fb_wid_dbl_info wid24; /* for 24bit windows */ - int clut_id; /* CLUT attached to pr */ - int mpg_fcs; /* FCS and enabling writes */ - int windowfd; /* Inherit from egret - for SV !*/ - H_rp *gt_rp; /* RP control space */ - H_fbi_go *gt_fbi_go; /* FBI "go" regs" */ - H_fbi *gt_fbi; /* FB input section */ - H_fe_hold *gt_fe_h; /* FE hold register section */ - short gt_fe_frozen; /* Flag indicating FE is dead */ - short gt_fe_timeout; /* Get from environment var - - * Default 15 secs - */ - short gt_stereo; /* default mono = 0 */ -}; - -int gt_putcolormap(); -int gt_putattributes(); -int gt_rop(); -int gt_ioctl(); - -#ifndef KERNEL -extern struct pixrectops gtp_ops; - -Pixrect *gt_make(); -int gt_destroy(); -Pixrect *gt_region(); -int gt_getcolormap(); -int gt_getattributes(); -int gt_vector(); -int gt_get(); -int gt_put(); -int gt_stencil(); -int gt_batchrop(); -#endif !KERNEL - - -/* Hawk Macros */ -int gt_dummy_extern; - -#define gt_d(pr) ((struct gt_data *) ((pr)->pr_data)) - -#define gt_waitidle(rp, timeout) \ - { \ - int spin; \ - int cnt = 0; \ - while ((rp)->csr_reg.wd & HKPBM_HCS_PFB) { \ - /* spin a bit, give other bus accesses some space */ \ - for (spin=0; spin < cnt; spin++) { \ - /* \ - * Some busy work using an external variable to \ - * ensure optimizers will not take out loop. \ - */ \ - gt_dummy_extern = spin; \ - } \ - \ - if (cnt++ > 2000000) { \ - /* \ - * Only get here if major problem with GT system. \ - * Slow the loop, reduce CPU usage. \ - */ \ - if (cnt > 2000 + timeout) { \ - /* very dead, abort */ \ - while ((rp)->csr_reg.wd & HKPBM_HCS_PFB); \ - } \ - } \ - } \ - } - -#define gt_set_as_reg(rp, as) \ - (rp)->as_reg.wd = (as); - -#define gt_get_as_reg(rp, as) \ - (as) = (rp)->as_reg.wd; - -#define gt_set_buf_reg(fbi, buf) \ - (fbi)->buf_sel.wd = (buf); - -#define gt_get_buf_reg(fbi, buf) \ - (buf) = (fbi)->buf_sel.wd; - -#define gt_set_sten_mask(fbi, mask) \ - (fbi)->sten_mask.wd = (mask); - -#define gt_set_vwclip(fbi, xmin, xmax) \ - (fbi)->vwclp_x.wd = (HKPP_VCX_MASK & ((xmin) << HKPP_VCX_LEFT_SHIFT) | (xmax)); - -#define gt_set_z_ctrl(fbi) \ - (fbi)->z_ctrl.wd = 0; - -#define gt_set_fcs_copy(fbi) \ - (fbi)->w_wmask.wd |= HKPP_WWM_FC; - -#define gt_set_sten_mode_col(rp, fbi, mo, col) \ - (fbi)->fg_col.wd = (col); \ - (rp)->as_reg.wd = (mo); - -#define gt_set_common_reg(dp, col, mo, orp, b_sel, w_mask) \ - { \ - struct gt_data *mgtd = gt_d((dp)); \ - H_rp *mrp = (H_rp *)mgtd->gt_rp; \ - H_fbi *mfbi = (H_fbi *)mgtd->gt_fbi; \ - \ - gt_waitidle(mrp, mgtd->gt_fe_timeout); \ - mrp->as_reg.wd = (mo); \ - mfbi->fg_col.wd = (col); \ - mfbi->bg_col.wd = (0); \ - mfbi->buf_sel.wd = (HKPP_BS_MASK &(b_sel)); \ - mfbi->rop.wd = (orp); \ - mfbi->mpg_set.wd = (HKPP_MPG_MASK & mgtd->mpg_fcs); \ - \ - switch (mo) { \ - case HKPBM_HFBAS_WINDOW : \ - mfbi->w_wmask.wd = (w_mask); \ - break; \ - case HKPBM_HFBAS_IMAGE: \ - case HKPBM_HFBAS_ST_IMAGE: \ - mfbi->i_wmask.wd = (w_mask); \ - break; \ - case HKPBM_HFBAS_CURSOR_BYTE: \ - mfbi->b_wmask.wd = (w_mask); \ - mfbi->i_wmask.wd = (w_mask)<i_wmask.wd = (w_mask); \ - mfbi->z_ctrl.wd = HKPP_ZC_WRITE_ENA; \ - break; \ - } \ - } - -#define gt_acc_fe_hold(fh) \ - (fh)->fe_hold_reg.wd |= HKFE_HOLD_REQ; - -#ifndef KERNEL -#define gt_wait_fe_hold(fh, frozen_flag, timeout) \ - { \ - int spin; \ - int cnt = 0; \ - if ((fh)->fe_hold_reg.wd & HKFE_HOLD_ACK) { \ - frozen_flag = FALSE; \ - } else { \ - while (!frozen_flag && \ - (!((fh)->fe_hold_reg.wd & HKFE_HOLD_ACK))) { \ - /* spin a bit, give bus accesses some space */ \ - for (spin = 0; spin < cnt; spin ++) { \ - /* \ - * Some busy work using an external \ - * variable to ensure optimizers will not \ - * take out loop. \ - */ \ - gt_dummy_extern = spin; \ - } \ - if (cnt++ > 2000) { \ - /* \ - * Get here if FE is having some problems. \ - * Slow the loop, reduce CPU usage. \ - */ \ - sleep (1); \ - if (cnt > 2000 + timeout) { \ - /* front end kaput */ \ - frozen_flag = TRUE; \ - printf("GT Hardware timeout (front end) \ - from gt_wait_fe_hold\n"); \ - } \ - } \ - } \ - } \ - } -#else -#define gt_wait_fe_hold(fh, frozen_flag, timeout) \ - { \ - int spin; \ - int cnt = 0; \ - if ((fh)->fe_hold_reg.wd & HKFE_HOLD_ACK) { \ - frozen_flag = FALSE; \ - } else { \ - while (!frozen_flag && \ - (!((fh)->fe_hold_reg.wd & HKFE_HOLD_ACK))) { \ - /* spin a bit, give bus accesses some space */ \ - for (spin = 0; spin < cnt; spin ++) { \ - /* \ - * Some busy work using an external \ - * variable to ensure optimizers will not \ - * take out loop. \ - */ \ - gt_dummy_extern = spin; \ - } \ - if (cnt++ > 2500) { \ - frozen_flag = TRUE; \ - } \ - } \ - } \ - } -#endif KERNEL - -#define gt_rel_fe_hold(fh) \ - (fh)->fe_hold_reg.wd &= ~HKFE_HOLD_REQ; - -#define gt_set_fill_regs(rp, fbi, fbi_g, fe_hold, wid, hgt, x0, y0, gg, frozen_flag, max_timeout) \ - { \ - \ - (rp)->csr_reg.wd = HKPBM_HCS_HSRP; \ - gt_acc_fe_hold(fe_hold); \ - gt_dummy_extern = fbi->i_wmask.wd; \ - (fbi)->dir_size.wd = ((HKPF_CFDS_COPY_WIDTH_MASK & (wid)) | \ - (HKPF_CFDS_COPY_HEIGHT_MASK & \ - ((hgt) << HKPF_CFDS_COPY_HEIGHT_SHIFT))); \ - gt_wait_fe_hold(fe_hold, frozen_flag, max_timeout); \ - (fbi_g)->fill_dst.wd = \ - ((HKPF_FDA_Y_MASK & ((y0) << HKPF_FDA_Y_SHIFT)) \ - | (HKPF_FDA_X_MASK & (x0))| (gg)); \ - (rp)->csr_reg.wd = 0; \ - } - -#define gt_set_copy_regs(rp, fbi, fbi_g, fe_hold, xs, ys, gg, wid, hgt, dir, xd, yd, frozen_flag, max_timeout) \ - { \ - \ - (rp)->csr_reg.wd = HKPBM_HCS_HSRP; \ - gt_acc_fe_hold(fe_hold); \ - gt_dummy_extern = fbi->i_wmask.wd; \ - (fbi)->copy_src.wd = ((HKPF_CSA_X_MASK & (xs)) | \ - (HKPF_CSA_Y_MASK & ((ys) << HKPF_CSA_Y_SHIFT)) | (gg)); \ - (fbi)->dir_size.wd = ((HKPF_CFDS_COPY_WIDTH_MASK & (wid)) | \ - (HKPF_CFDS_COPY_HEIGHT_MASK & \ - ((hgt) << HKPF_CFDS_COPY_HEIGHT_SHIFT)) | \ - ((dir) ? HKPF_CFDS_COPY_LEFT:0 )); \ - gt_wait_fe_hold(fe_hold, frozen_flag, max_timeout); \ - (fbi_g)->copy_dst.wd = ((HKPF_CDA_X_MASK & (xd)) | \ - (HKPF_CDA_Y_MASK & ((yd) << HKPF_CDA_Y_SHIFT)) | (gg)); \ - (rp)->csr_reg.wd = 0; \ - } - -#define gt_sten_rop_1(gt_a, mem_a, type, off, by_a, s_lb, val) \ - { \ - *(gt_a) = (*(mem_a) << (off)); \ - (gt_a) = (type *) PTR_ADD((gt_a), GT_IMAGE_LINEBYTES); \ - (mem_a) = (type *)(((int)(by_a) += (s_lb)) & (val)); \ - } - -#define gt_sten_rop_2(gt_a, mem_a) \ - { \ - *(gt_a) = *(mem_a)++; \ - (gt_a) = (u_long *)PTR_ADD((gt_a), GT_STEN_INCR); \ - } -#define gt_set_stereo(fbi, ster) \ - (fbi)->stereo.wd = (ster); - -#define gt_pr_to_mem(gtpr, mempr, op) \ - { \ - struct gt_data *prd = gt_d(gtpr); \ - \ - mempr = *gtpr; \ - mempr.pr_ops = &mem_ops; \ - if (PIX_ATTRGROUP(prd->planes) == PIXPG_8BIT_COLOR) { \ - gt_set_common_reg(gtpr, PIXOP_COLOR(op), \ - HKPBM_HFBAS_CURSOR_BYTE, HKPP_ROP_SRC, \ - prd->buf,(PIX_ALL_PLANES & (prd->planes))); \ - } else if (PIX_ATTRGROUP(prd->planes) == PIXPG_24BIT_COLOR) { \ - gt_set_common_reg(gtpr, PIXOP_COLOR(op), \ - HKPBM_HFBAS_IMAGE, HKPP_ROP_SRC, \ - prd->buf,(PIX_ALL_PLANES &(prd->planes))); \ - } \ - } -#endif gtvar_DEFINED diff --git a/include/pixrect/mem32_var.h b/include/pixrect/mem32_var.h deleted file mode 100644 index a7f75654437..00000000000 --- a/include/pixrect/mem32_var.h +++ /dev/null @@ -1,34 +0,0 @@ -/* @(#)mem32_var.h 1.2 90/07/27 SMI */ - -/* Copyright 1990 Sun Microsystems, Inc. */ - -/* pixrect data for 8 bit emulation in 24/32 bit memory pixrect */ - -#ifndef mem32var_DEFINED -#define mem32var_DEFINED - -#include -#include /* mprp */ -#include /* colormapseg */ - -#define MEM32_8BIT_CMAPSIZE 256 - -struct mprp32_data -{ - struct mprp_data mprp; - int plane_group; - int fd; - int windowfd; - struct colormapseg cms; -}; - -#define mprp32_d(pr) ((struct mprp32_data *) (pr)->pr_data) - -#ifndef KERNEL -extern - struct pixrectops mem32_ops; -int mem32_rop(); -int mem32_getcolormap(); -#endif /* !KERNEL */ - -#endif /* !mem32var_DEFINED */ diff --git a/include/pixrect/mem_rop_impl_ops.h b/include/pixrect/mem_rop_impl_ops.h deleted file mode 100644 index a1d6c831aab..00000000000 --- a/include/pixrect/mem_rop_impl_ops.h +++ /dev/null @@ -1,260 +0,0 @@ -/* @(#)mem_rop_impl_ops.h 1.4 88/02/08 SMI */ - -/* - * Copyright 1986 by Sun Microsystems, Inc. - */ - -#ifndef mem_rop_impl_ops_DEFINED -#define mem_rop_impl_ops_DEFINED - -/* - * rasterop function macros - */ - -/* - * unmasked rop - */ -#define OP_urop0(d,s) (0) -#define OP_urop1(d,s) (~((d) | (s))) -#define OP_urop2(d,s) ((d) & ~(s)) -#define OP_urop3(d,s) (~(s)) -#define OP_urop4(d,s) (~(d) & (s)) -#define OP_urop5(d,s) (~(d)) -#define OP_urop6(d,s) ((d) ^ (s)) -#define OP_urop7(d,s) (~((d) & (s))) -#define OP_urop8(d,s) ((d) & (s)) -#define OP_urop9(d,s) ((d) ^ ~(s)) -#define OP_uropA(d,s) (d) -#define OP_uropB(d,s) ((d) | ~(s)) -#define OP_uropC(d,s) (s) -#define OP_uropD(d,s) (~(d) | (s)) -#define OP_uropE(d,s) ((d) | (s)) -#define OP_uropF(d,s) (~0) - -/* - * masked rop - * - * correct mask: m = OP_mmsk(mask) - * perform rop: d = OP_mrop(dst, mask, src) - */ -#define OP_mmsk0(m) (~(m)) -#define OP_mrop0(d,m,s) ((d) & (m)) - -#define OP_mmsk1(m) (m) -#define OP_mrop1(d,m,s) ((d) ^ ((m) & ((d) | ~(s)))) - -#define OP_mmsk2(m) (~(m)) -#define OP_mrop2(d,m,s) ((d) & ((m) | ~(s))) - -#define OP_mmsk3(m) (m) -#define OP_mrop3(d,m,s) ((d) ^ ((m) & ((d) ^ ~(s)))) - -#define OP_mmsk4(m) (m) -#define OP_mrop4(d,m,s) ((d) ^ ((m) & ((d) | (s)))) - -#define OP_mmsk5(m) (m) -#define OP_mrop5(d,m,s) ((d) ^ (m)) - -#define OP_mmsk6(m) (m) -#define OP_mrop6(d,m,s) ((d) ^ ((m) & (s))) - -#define OP_mmsk7(m) (m) -#define OP_mrop7(d,m,s) ((d) ^ ((m) & (~(d) | (s)))) - -#define OP_mmsk8(m) (~(m)) -#define OP_mrop8(d,m,s) ((d) & ((m) | (s))) - -#define OP_mmsk9(m) (m) -#define OP_mrop9(d,m,s) ((d) ^ ((m) & ~(s))) - -#define OP_mmskA(m) (m) -#define OP_mropA(d,m,s) (d) - -#define OP_mmskB(m) (m) -#define OP_mropB(d,m,s) ((d) | ((m) & ~(s))) - -#define OP_mmskC(m) (m) -#define OP_mropC(d,m,s) ((d) ^ ((m) & ((d) ^ (s)))) - -#define OP_mmskD(m) (m) -#define OP_mropD(d,m,s) ((d) ^ ((m) & ~((d) & (s)))) - -#define OP_mmskE(m) (m) -#define OP_mropE(d,m,s) ((d) | ((m) & (s))) - -#define OP_mmskF(m) (m) -#define OP_mropF(d,m,s) ((d) | (m)) - - -/* - * unmasked fill - * - * generate fill constant: k = OP_ufgen(color) - * perform unmasked fill: d = OP_ufill(dst, constant) - */ -#define OP_ufgen0(c) (0) -#define OP_ufill0(d,k) (k) - -#define OP_ufgen1(c) (c) -#define OP_ufill1(d,k) (~((d) | (k))) - -#define OP_ufgen2(c) (~(c)) -#define OP_ufill2(d,k) ((d) & (k)) - -#define OP_ufgen3(c) (~(c)) -#define OP_ufill3(d,k) (k) - -#define OP_ufgen4(c) (c) -#define OP_ufill4(d,k) (~(d) & (k)) - -#define OP_ufgen5(c) (c) -#define OP_ufill5(d,k) (~(d)) - -#define OP_ufgen6(c) (c) -#define OP_ufill6(d,k) ((d) ^ (k)) - -#define OP_ufgen7(c) (c) -#define OP_ufill7(d,k) (~((d) & (k))) - -#define OP_ufgen8(c) (c) -#define OP_ufill8(d,k) ((d) & (k)) - -#define OP_ufgen9(c) (~(c)) -#define OP_ufill9(d,k) ((d) ^ (k)) - -#define OP_ufgenA(c) (c) -#define OP_ufillA(d,k) (d) - -#define OP_ufgenB(c) (~(c)) -#define OP_ufillB(d,k) ((d) | (k)) - -#define OP_ufgenC(c) (c) -#define OP_ufillC(d,k) (k) - -#define OP_ufgenD(c) (c) -#define OP_ufillD(d,k) (~(d) | (k)) - -#define OP_ufgenE(c) (c) -#define OP_ufillE(d,k) ((d) | (k)) - -#define OP_ufgenF(c) (~0) -#define OP_ufillF(d,k) (k) - - -/* - * masked fill - * - * generate fill constant: k = OP_mfgen(mask, color) - * generate mask for fill: m = OP_mfmsk(mask) - * perform masked fill: d = OP_mfill(dst, mask, constant) - */ -#define OP_mfgen0(m,c) (c) -#define OP_mfmsk0(m) (~(m)) -#define OP_mfill0(d,m,k) ((d) & (m)) - -#define OP_mfgen1(m,c) (~(c)) -#define OP_mfmsk1(m) (m) -#define OP_mfill1(d,m,k) ((d) ^ ((m) & ((d) | (k)))) - -#define OP_mfgen2(m,c) (~(m) | ~(c)) -#define OP_mfmsk2(m) (m) -#define OP_mfill2(d,m,k) ((d) & (k)) - -#define OP_mfgen3(m,c) ((m) & ~(c)) -#define OP_mfmsk3(m) (~(m)) -#define OP_mfill3(d,m,k) (((d) & (m)) | (k)) /* needs work */ - -#define OP_mfgen4(m,c) (c) -#define OP_mfmsk4(m) (m) -#define OP_mfill4(d,m,k) ((d) ^ ((m) & ((d) | (k)))) - -#define OP_mfgen5(m,c) (c) -#define OP_mfmsk5(m) (m) -#define OP_mfill5(d,m,k) ((d) ^ (m)) - -#define OP_mfgen6(m,c) ((m) & (c)) -#define OP_mfmsk6(m) (m) -#define OP_mfill6(d,m,k) ((d) ^ (k)) - -#define OP_mfgen7(m,c) (c) -#define OP_mfmsk7(m) (m) -#define OP_mfill7(d,m,k) ((d) ^ ((m) & (~(d) | (k)))) - -#define OP_mfgen8(m,c) (~(m) | (c)) -#define OP_mfmsk8(m) (m) -#define OP_mfill8(d,m,k) ((d) & (k)) - -#define OP_mfgen9(m,c) ((m) & ~(c)) -#define OP_mfmsk9(m) (m) -#define OP_mfill9(d,m,k) ((d) ^ (k)) - -#define OP_mfgenA(m,c) (c) -#define OP_mfmskA(m) (m) -#define OP_mfillA(d,m,k) (d) - -#define OP_mfgenB(m,c) ((m) & ~(c)) -#define OP_mfmskB(m) (m) -#define OP_mfillB(d,m,k) ((d) | (k)) - -#define OP_mfgenC(m,c) ((m) & (c)) -#define OP_mfmskC(m) (~(m)) -#define OP_mfillC(d,m,k) (((d) & (m)) | (k)) /* needs work */ - -#define OP_mfgenD(m,c) (~(c)) -#define OP_mfmskD(m) (m) -#define OP_mfillD(d,m,k) ((d) ^ ((m) & (~(d) | (k)))) - -#define OP_mfgenE(m,c) ((m) & (c)) -#define OP_mfmskE(m) (m) -#define OP_mfillE(d,m,k) ((d) | (k)) - -#define OP_mfgenF(m,c) (c) -#define OP_mfmskF(m) (m) -#define OP_mfillF(d,m,k) ((d) | (m)) - - -/* - * unmasked fill, color = 0 - * (pcc is too dumb for this) - */ -#define OP_uzero0(d) (0) -#define OP_uzero1(d) (~(d)) -#define OP_uzero2(d) (d) -#define OP_uzero3(d) (~0) -#define OP_uzero4(d) (0) -#define OP_uzero5(d) (~(d)) -#define OP_uzero6(d) (d) -#define OP_uzero7(d) (~0) -#define OP_uzero8(d) (0) -#define OP_uzero9(d) (~(d)) -#define OP_uzeroA(d) (d) -#define OP_uzeroB(d) (~0) -#define OP_uzeroC(d) (0) -#define OP_uzeroD(d) (~(d)) -#define OP_uzeroE(d) (d) -#define OP_uzeroF(d) (~0) - -/* - * masked fill, color = 0 - * - * generate mask for fill: m = OP_mfmsk(mask) - * perform masked zero fill: d = OP_mzero(dst, mask) - */ -#define OP_mzero0(d,m) ((d) & (m)) -#define OP_mzero1(d,m) ((d) ^ (m)) -#define OP_mzero2(d,m) (d) -#define OP_mzero3(d,m) ((d) | ~(m)) /* problem */ -#define OP_mzero4(d,m) ((d) & ~(m)) /* problem */ -#define OP_mzero5(d,m) ((d) ^ (m)) -#define OP_mzero6(d,m) (d) -#define OP_mzero7(d,m) ((d) | (m)) -#define OP_mzero8(d,m) ((d) & (m)) -#define OP_mzero9(d,m) ((d) ^ (m)) -#define OP_mzeroA(d,m) (d) -#define OP_mzeroB(d,m) ((d) | (m)) -#define OP_mzeroC(d,m) ((d) & (m)) -#define OP_mzeroD(d,m) ((d) ^ (m)) -#define OP_mzeroE(d,m) (d) -#define OP_mzeroF(d,m) ((d) | (k)) - -#endif diff --git a/include/pixrect/mem_rop_impl_util.h b/include/pixrect/mem_rop_impl_util.h deleted file mode 100644 index 1bd5efc58fd..00000000000 --- a/include/pixrect/mem_rop_impl_util.h +++ /dev/null @@ -1,61 +0,0 @@ -/* @(#)mem_rop_impl_util.h 1.7 89/05/19 SMI */ - -/* - * Copyright 1986, 1987 by Sun Microsystems, Inc. - */ - -#ifndef mem_rop_impl_util_DEFINED -#define mem_rop_impl_util_DEFINED - -/* - * Utility macros for memory pixrect code - */ - -/* - * Code selection macros - */ -#define IFTRUET(t, a, b) _STMT(if (t) {a;} else {b;}) -#define IFFALSET(t, a, b) _STMT(b;) - -/* - * Option control macros - */ -#define ALWAYS(option,a,b) IFTRUE(a,b) -#define NEVER(option,a,b) IFFALSE(a,b) -#define OPTION(option,a,b) option(a,b) - -#define ALWAYST(option,t,a,b) IFTRUET(t,a,b) -#define NEVERT(option,t,a,b) IFFALSET(t,a,b) -#define OPTIONT(option,t,a,b) option(t,a,b) - -/* - * Speed choice macros - * - * The T form is used when the "never" half of the fast code - * is the same as the slow code. - * - * Define NEVER_SLOW to get all fast code. - * Define NEVER_FAST to get all slow code. - */ - -#if defined(NEVER_FAST) && !defined(NEVER_SLOW) -#define FAST IFFALSE -#define FASTT IFFALSET -#else -#define FAST IFTRUE -#define FASTT IFTRUET -#endif - -#ifdef NEVER_SLOW -#define SLOW IFTRUE -#define SLOWT IFTRUET -#else -#define SLOW IFFALSE -#define SLOWT IFFALSET -#endif - -/* fast in user, slow in kernel */ -#define UFAST IFKERNEL(SLOW,FAST) -#define UFASTT IFKERNEL(SLOWT,FASTT) - -#endif mem_rop_impl_util_DEFINED diff --git a/include/pixrect/memreg.h b/include/pixrect/memreg.h deleted file mode 100644 index f2a1b011c4f..00000000000 --- a/include/pixrect/memreg.h +++ /dev/null @@ -1,65 +0,0 @@ -/* @(#)memreg.h 1.16 88/02/08 SMI */ - -/* - * Copyright 1983, 1987 by Sun Microsystems, Inc. - */ - -#ifndef memreg_DEFINED -#define memreg_DEFINED - -/* - * Rasterop hardware registers. To do a rasterop set the - * rasterop function in mrc_op. Clear mrc_pattern unless - * a special pattern is desired. - * - * Set mrc_shift to cause the source to be properly - * aligned with the destination: if words are being processed - * left-to-right, then mrc_shift should be a positive number - * between 0 and 15 inclusive; if words are being processed - * right-to-left, then mrc_shift should be a negative number - * between -16 and -1 inclusive. If the first source word - * does not supply enough data to satisfy the first destination - * words requirements then load mrc_source1 (in the left-to-right - * case) or mcr_source2 (in the right-to-left case) with the - * first source word. - * - * Load mrc_mask1 with a mask of the bits not contributed by - * the first source word (if the width were large), i.e. a - * mask of high-order bits. Load mrc_mask2 with a mask of the - * bits not contributed by the last source word, i.e. a mask - * of low-order bits. Set mrc_width to the number of words - * in the destination line. - * - * Then enable the chip and stuff the data through it and - * finally disable the chip. - */ -struct memropc -{ - u_short mrc_dest; /* destination register */ - u_short mrc_source1; /* source1 register (right) */ - u_short mrc_source2; /* source2 register (left) */ - u_short mrc_pattern; /* pattern register */ - u_short mrc_mask1; /* mask1 register */ - u_short mrc_mask2; /* mask2 register */ - short mrc_shift; /* bit 0..3 shift count for source */ - /* bit 8 sourceload bit */ - short mrc_op; /* function */ - short mrc_width; /* word width */ - short mrc_opcount; /* counts down the width */ - short mrc_decoderout; /* decoder output */ - short mrc_x11; /* manual load destination (diag)*/ - short mrc_x12; /* manual load source (diag) */ - short mrc_x13; - short mrc_x14; - short mrc_x15; /* flags register for applications */ -}; - -/* note: these are not relevant to color boards */ -#define mrc_enable(mrc) ((mrc)->mrc_shift |= 0x100) -#define mrc_disable(mrc) ((mrc)->mrc_shift &= ~0x100) - -/* macros for generating left (mask1) and right (mask2) masks */ -#define mrc_lmask(x) (0xffff0000 >> (x)) -#define mrc_rmask(x) (0x7fff >> (x)) - -#endif memreg_DEFINED diff --git a/include/pixrect/memvar.h b/include/pixrect/memvar.h deleted file mode 100644 index dab57fa1e3a..00000000000 --- a/include/pixrect/memvar.h +++ /dev/null @@ -1,152 +0,0 @@ -/* @(#)memvar.h 1.45 89/12/13 SMI */ - -/* - * Copyright 1986-1989 Sun Microsystems, Inc. - */ - -#ifndef memvar_DEFINED -#define memvar_DEFINED - -/* - * A memory pixrect is a special type of pixrect. Its image resides in - * memory, in a publicly known format permitting more direct access to the - * image than possible with the general pixrectops. - * - * In the memory pixrect the image is stored in consecutive memory locations, - * across the row from left to right, and then from top to bottom. Each row - * is padded to a 16-bit or 32-bit boundary (for details refer to the Pixrect - * Reference Manual). - * - * The depth of a pixel is the number of bits required to represent it. - * Pixels are placed in consecutive fields of width the depth of each pixel, - * with placement being independent of word or byte boundaries. - */ -struct mpr_data -{ - int md_linebytes; /* number of bytes from one line to next */ - short *md_image; /* word address */ - struct pr_pos md_offset; - short md_primary; - short md_flags; /* Flag bits, see below */ -}; - -/* pixrect data for memory pixrect with plane mask (MP_PLANEMASK set) */ -struct mprp_data -{ - struct mpr_data mpr; - int planes; -}; - -#define mpr_d(pr) ((struct mpr_data *) (pr)->pr_data) -#define mprp_d(pr) ((struct mprp_data *) (pr)->pr_data) - -/* md_flags bits definitions */ - -#define MP_REVERSEVIDEO 1 /* Pixrect is reverse video */ -/* (should only be set if pr_depth = 1) */ -#define MP_DISPLAY 2 /* Pixrect is a frame buffer device */ -#define MP_PLANEMASK 4 /* Pixrect has a plane mask */ -/* (should only be set if pr_depth > 1) */ -#ifdef i386 -#define MP_I386 8 /* Pixrect is for 386 architecture */ -#define MP_STATIC 16 /* Pixrect is a static pixrect */ -#endif /*i386*/ -#define MP_FONT 32 /* Pixrect is a part of a Pixfont */ -/* (hint to pr_batchrop) */ - -/* - * Each line (row) of the pixrect is padded to be a multiple - * of this many bits - */ -#define MPR_LINEBITPAD 16 - -#define mpr_linebytes(x, depth) \ - ( ((pr_product(x, depth) + (MPR_LINEBITPAD-1)) >> 3) &~ 1) -#define mpr_prlinebytes(mpr) \ - mpr_linebytes((mpr)->pr_size.x, (mpr)->pr_depth) -#define mpr_mdlinebytes(mpr) \ - (mpr_d(mpr)->md_linebytes) - -#define mprd_addr(mprd, xo, yo) \ - ((short *)( \ - (int)(mprd)->md_image \ - + pr_product((mprd)->md_linebytes,(mprd)->md_offset.y+(yo)) \ - + (((mprd)->md_offset.x+(xo)) >> 3) &~ 1)) - -#define mprd8_addr(mprd, xo, yo, d) \ - ((u_char *)( \ - (int)(mprd)->md_image \ - + pr_product((mprd)->md_linebytes,(mprd)->md_offset.y+(yo)) \ - + (pr_product((mprd)->md_offset.x+(xo), (d)) >> 3) ) ) - -#define mprd_skew(mprd, xo, yo) \ - (((mprd)->md_offset.x + (xo)) & 15) - -#define mprs_addr(mprs) _mprs_addr((struct pr_prpos *)&(mprs)) -#define mprs8_addr(mprs) _mprs8_addr((struct pr_prpos *)&(mprs)) -#define mprs_skew(mprs) _mprs_skew((struct pr_prpos *)&(mprs)) - -#if !defined lint || !defined KERNEL || defined(sun2) -short *_mprs_addr(); -u_char *_mprs8_addr(); -int _mprs_skew(); -#endif - -/* - * Static pixrects. A pixrect may be created at compile time using the - * mpr_static macro as part of the static declarations of a program. Thus - * mpr_static(cursor, 16, 16, 1, rawcursordata); - * will declare and initialize (using rawcursordata) the storage needed - * for a pixrect that may be referred to as 'cursor' subsequently in the - * same file, or as &cursor if a pointer to that pixrect is called for rather - * than the pixrect itself. - */ - -/* First a pair of utility macros that allow concatenation in a fashion that - * won't annoy lint (These belong in a standard header file!): - */ -#ifndef CAT -#undef IDENT -#define IDENT(x) x -#define CAT(a,b) IDENT(a)b -#endif - -#define mpr_static(name, w, h, d, image) \ - struct mpr_data CAT(name,_data) = \ - {mpr_linebytes(w,d), (short *)(image), {0, 0}, 0, 0}; \ - Pixrect name = {&mem_ops, w, h, d, (caddr_t)&CAT(name,_data)} - -/* static pixrect with variables declared "static" */ -#define mpr_static_static(name, w, h, d, image) \ - static struct mpr_data CAT(name,_data) = \ - {mpr_linebytes(w,d), (short *)(image), {0, 0}, 0, 0}; \ - static Pixrect name = {&mem_ops, w, h, d, (caddr_t)&CAT(name,_data)} - -/* - * During rop calls need to determine if dst/src is something that - * mem_rop() can handle. Use the following macro to find out. - */ -#define MP_NOTMPR(pr) ((pr)->pr_ops->pro_rop != mem_rop) - -extern struct pixrectops mem_ops; - -int mem_rop(); -#ifndef KERNEL -int mem_stencil(); -int mem_batchrop(); -Pixrect *mem_create(); /* General mpr create routine */ -Pixrect *mem_point(); /* Even more general mpr create */ -int mem_destroy(); -int mem_get(); -int mem_put(); -int mem_vector(); -Pixrect *mem_region(); -#endif /*KERNEL*/ -int mem_putcolormap(); -int mem_putattributes(); -#ifndef KERNEL -int mem_getcolormap(); -int mem_getattributes(); -#endif /* KERNEL*/ - -#endif /*!memvar_DEFINED*/ diff --git a/include/pixrect/pixfont.h b/include/pixrect/pixfont.h deleted file mode 100644 index 2bd132df5d9..00000000000 --- a/include/pixrect/pixfont.h +++ /dev/null @@ -1,59 +0,0 @@ -/* @(#)pixfont.h 1.14 88/02/08 SMI */ - -/* - * Copyright (c) 1986 by Sun Microsystems, Inc. - */ - -#ifndef pixfont_DEFINED -#define pixfont_DEFINED - -/* - * Definition of pixfonts for pixrect library. - * Include before this file. - */ - -/* - * A character descriptor contains the pixrect constituting the actual - * character, the coordinates of the home (top left) of that pixrect - * relative to the character origin (a point on the baseline near the left - * of the character), and the distance by which to advance the origin after - * printing this character. - */ -struct pixchar -{ - Pixrect *pc_pr; /* pixrect for this char */ - struct pr_pos pc_home; /* home coords relative to left baseline */ - struct pr_pos pc_adv; /* distance to next char */ -}; - -/* - * A font descriptor contains the width of a space (intended to be used - * in computing backspace and tab distances), the distance between consecutive - * baselines in the absence of any superscripting, subscripting, or similar - * vertical monkey business, and an array of 256 character descriptors. - */ -typedef struct pixfont -{ - struct pr_size pf_defaultsize; /* default character size */ - struct pixchar pf_char[256]; -} -Pixfont; - -/* structured text macros */ -#ifndef lint -#define prs_text(prpos, op, pf, str) \ - pr_text((prpos).pr, (prpos).pos.x, (prpos).pos.y, pf, str) - -#define prs_ttext(prpos, op, pf, str) \ - pr_ttext((prpos).pr, (prpos).pos.x, (prpos).pos.y, pf, str) -#endif /*lint*/ - -Pixfont *pf_open(); -Pixfont *pf_open_private(); -Pixfont *pf_default(); -struct pr_size pf_textbatch(); -struct pr_size pf_textwidth(); - -#define PIXFONT Pixfont - -#endif /*pixfont_DEFINED*/ diff --git a/include/pixrect/pixrect.h b/include/pixrect/pixrect.h deleted file mode 100644 index 684348ac41c..00000000000 --- a/include/pixrect/pixrect.h +++ /dev/null @@ -1,353 +0,0 @@ -/* @(#)pixrect.h 1.51 91/05/09 SMI */ -/* - * Copyright 1986-89 by Sun Microsystems, Inc. - */ - -#ifndef _pixrect_pixrect_h -#define _pixrect_pixrect_h - -#include /* system type defs */ - -/* - * This file defines the programmer interface to the pixrect abstraction. - * A pixrect is a rectangular array of pixels on which a number of - * operations are defined. - * - * Each pixrect has as visible attributes its height and width in - * pixels and the number of bits stored for each pixel. It also supports - * several operations. The proper way to think of the operations is - * that they are messages sent to the pixrect. The operations are: - * - * pr_destroy Destroy a pixrect. - * pr_rop Raster operation from another pixrect to the - * destination pixrect. The case where the source - * and destination overlap is properly handled. - * pr_stencil Raster operation from source pixrect to the - * dest pixrect using a stencil pixrect as a 'cookie - * cutter' to perform a spatial write enable. - * pr_batchrop Like pr_rop, but source is an array of pixrects, - * and an offset to be applied before each pixrect. - * This is specifically designed for operations like - * putting up text, which consists of a number of - * characters from a font, each given by a pixrect. - * pr_get Get the value of a single pixel from a pixrect. - * pr_put Change a single pixel value in a pixrect. - * pr_vector Draw a vector in a pixrect - * pr_region Create a new pixrect which describes a rectangular - * sub-region of an existing pixrect. - * pr_putcolormap Write a portion of the colormap. - * pr_getcolormap Read a portion of the colormap. - * pr_putattributes Set the plane mask. - * pr_getattributes Get the plane mask. - */ - -/* - * There are a number of structures used in the arguments to pixrects: - * - * struct pr_pos A position within a pixrect is a pair of - * integers giving the offset from the upper - * left corner. The pixels within a pixrect - * are numbered with (0,0) at the upper left - * and (width-1,height-1) at the lower right. - * struct pr_prpos A pixrect and a position within it. - * struct pr_size A pair of integers representing the - * size of a rectangle within a pixrect. - * struct pr_subregion A pixrect, a position and a size, - * specifying a rectangular sub-region. - */ - -struct pr_size -{ - int x, y; -}; - -typedef struct pixrect -{ - struct pixrectops *pr_ops; /* operations appropriate to this pr */ - struct pr_size pr_size; /* pixels per dimension */ - int pr_depth; /* bits per pixel */ - caddr_t pr_data; /* device-dependent data */ -} -Pixrect; -#define pr_width pr_size.x -#define pr_height pr_size.y - -struct pr_pos -{ - int x, y; -}; - -struct pr_prpos -{ - Pixrect *pr; - struct pr_pos pos; -}; - -struct pr_subregion -{ - Pixrect *pr; - struct pr_pos pos; - struct pr_size size; -}; - -/* - * Pr_product is used when doing multiplications involving pixrects, - * and casts its arguments to that the compiler will use 16 by 16 multiplies. - */ -#ifndef pr_product -#if defined(sun) && !defined(sparc) -#define pr_product(a, b) ((short)(a) * (short)(b)) -#else -#define pr_product(a, b) ((a) * (b)) -#endif -#endif - -#ifndef KERNEL -/* - * Takes device file name. This is how a screen pixrect is created. - */ -extern Pixrect *pr_open(); -#endif /* !KERNEL*/ - -/* - * Pixrect ops vector, used by pr_ macros below to call the appropriate - * device dependent function for the destination pixrect. - */ -struct pixrectops -{ - int (*pro_rop)(); -#ifndef KERNEL - int (*pro_stencil)(); - int (*pro_batchrop)(); - int (*pro_nop)(); /* place holder */ - int (*pro_destroy)(); - int (*pro_get)(); - int (*pro_put)(); - int (*pro_vector)(); - Pixrect * (*pro_region)(); -#endif /* !KERNEL */ - int (*pro_putcolormap)(); -#ifndef KERNEL - int (*pro_getcolormap)(); -#endif /* !KERNEL */ - int (*pro_putattributes)(); -#ifndef KERNEL - int (*pro_getattributes)(); -#endif /* !KERNEL */ -#ifdef KERNEL - int (*pro_nop)(); /* place holder */ -#endif /* KERNEL */ -}; - -#if !defined(lint) || defined(KERNEL) - -#define pr_rop(dpr, dx, dy, w, h, op, spr, sx, sy) \ - (*(dpr)->pr_ops->pro_rop)((dpr), (dx), (dy), (w), (h), (op), \ - (spr), (sx), (sy)) -#define pr_putcolormap(pr, ind, cnt, red, grn, blu) \ - (*(pr)->pr_ops->pro_putcolormap)((pr), (ind), (cnt), \ - (red), (grn), (blu)) -#define pr_putattributes(pr, planes) \ - (*(pr)->pr_ops->pro_putattributes)((pr), (planes)) -#define _PR_IOCTL_KERNEL_DEFINED -#define pr_ioctl(pr, cmd, data) \ - ((pr)->pr_ops->pro_nop ? (*(pr)->pr_ops->pro_nop)((pr), (cmd), (data)) : -1) - -#ifndef KERNEL - -#define pr_stencil(dpr, dx, dy, w, h, op, stpr, stx, sty, spr, sx, sy) \ - (*(dpr)->pr_ops->pro_stencil)((dpr), (dx), (dy), (w), (h), (op), \ - (stpr), (stx), (sty), (spr), (sx), (sy)) -#define pr_batchrop(dpr, x, y, op, sbp, n) \ - (*(dpr)->pr_ops->pro_batchrop)((dpr), (x), (y), (op), (sbp), (n)) -#define pr_destroy(pr) \ - (*(pr)->pr_ops->pro_destroy)(pr) -#define pr_get(pr, x, y) \ - (*(pr)->pr_ops->pro_get)((pr), (x), (y)) -#define pr_put(pr, x, y, val) \ - (*(pr)->pr_ops->pro_put)((pr), (x), (y), (val)) -#define pr_vector(pr, x0, y0, x1, y1, op, color) \ - (*(pr)->pr_ops->pro_vector)((pr), (x0), (y0), (x1), (y1), (op), \ - (color)) -#define pr_region(pr, x, y, w, h) \ - (*(pr)->pr_ops->pro_region)((pr), (x), (y), (w), (h)) -#define pr_getcolormap(pr, ind, cnt, red, grn, blu) \ - (*(pr)->pr_ops->pro_getcolormap)((pr), (ind), (cnt), \ - (red), (grn), (blu)) -#define pr_getattributes(pr, planes) \ - (*(pr)->pr_ops->pro_getattributes)((pr), (planes)) -#endif /* !KERNEL */ - -#else /* !lint || KERNEL*/ - -extern pr_rop(); -extern pr_stencil(); -extern pr_batchrop(); -extern pr_destroy(); -extern pr_get(); -extern pr_put(); -extern pr_vector(); -extern Pixrect *pr_region(); -extern pr_putcolormap(); -extern pr_getcolormap(); -extern pr_putattributes(); -extern pr_getattributes(); - -#endif /* lint*/ - -/* - * Several of the above operations return a common, distinguished value when - * an error arises. That value is defined as follows: - */ -#define PIX_ERR -1 - -/* - * Operations. The 'op' in 'rasterop' may be any binary Boolean function, - * encoded as an integer from 0 to 15 (the op code) shifted left by one bit. - * The function is applied per-pixel. - * - * The following permit the op to be expressed as Boolean combinations - * of the two inputs 'src' and 'dst'. Thus oring the source and destination - * together is written as PIX_SRC|PIX_DST, while xoring the source with the - * destination is PIX_SRC^PIX_DST. Since ~op would set the color and clip - * bits, the macro PIX_NOT is provided for use in place of ~. - */ -#define PIX_SRC (0xC << 1) -#define PIX_DST (0xA << 1) -#define PIX_NOT(op) ((op) ^ 0x1E) -#define PIX_CLR (0x0 << 1) -#define PIX_SET (0xF << 1) - -/* macros which tell whether a rasterop needs SRC or DST values */ -#define PIXOP_NEEDS_DST(op) ((((op)>>1)^(op)) & PIX_NOT(PIX_DST)) -#define PIXOP_NEEDS_SRC(op) ((((op)>>2)^(op)) & PIX_NOT(PIX_SRC)) - -/* macros for encoding and extracting color field */ -#define PIX_COLOR(c) ((c)<<5) -#define PIX_OPCOLOR(op) ((op)>>5) -#define PIX_OP_CLIP(op) ((op)&0x1f) -#define PIX_OP(op) ((op)&0x1e) - -/* - * The pseudo-operation PIX_DONTCLIP specifies that clipping should not - * be performed. PIX_CLIP is also provided, although unnecessary. - */ -#define PIX_DONTCLIP 0x1 -#define PIX_CLIP 0x0 - -/* - * The following structured definitions, all prefixed with prs_, correspond - * to the unstructured definitions above prefixed with pr_. - */ - -#if !defined(lint) || defined(KERNEL) - -#define prs_rop(dstreg, op, srcprpos) \ - pr_rop((dstreg).pr, (dstreg).pos.x, (dstreg).pos.y, \ - (dstreg).size.x, (dstreg).size.y, (op), \ - (srcprpos).pr, (srcprpos).pos.x, (srcprpos).pos.y) -#define prs_stencil(dstreg, op, stenprpos, srcprpos) \ - pr_stencil((dstreg).pr, (dstreg).pos.x, (dstreg).pos.y, \ - (dstreg).size.x, (dstreg).size.y, (op), \ - (stenprpos).pr, (stenprpos).pos.x, (stenprpos).pos.y, \ - (srcprpos).pr, (srcprpos).pos.x, (srcprpos).pos.y) -#define prs_batchrop(dstprpos, op, items, n) \ - pr_batchrop((dstprpos).pr, (dstprpos).pos.x, (dstprpos).pos.y, \ - (op), (items), (n)) -#define prs_destroy(pr) pr_destroy(pr) -#define prs_get(srcprpos) \ - pr_get((srcprpos).pr, (srcprpos).pos.x, (srcprpos).pos.y) -#define prs_put(dstprpos, val) \ - pr_put((dstprpos).pr, (dstprpos).pos.x, (dstprpos).pos.y, (val)) -#define prs_vector(pr, pos0, pos1, op, color) \ - pr_vector((pr), (pos0).x, (pos0).y, (pos1).x, (pos1).y, (op), (color)) -#define prs_region(dstreg) \ - pr_region((dstreg).pr, (dstreg).pos.x, (dstreg).pos.y, \ - (dstreg).size.x, (dstreg).size.y) -#define prs_putcolormap(pr, ind, cnt, red, grn, blu) \ - pr_putcolormap((pr), (ind), (cnt), (red), (grn), (blu)) -#define prs_getcolormap(pr, ind, cnt, red, grn, blu) \ - pr_getcolormap((pr), (ind), (cnt), (red), (grn), (blu)) -#define prs_putattributes(pr, planes) pr_putattributes((pr), (planes)) -#define prs_getattributes(pr, planes) pr_getattributes((pr), (planes)) - -/* pr_replrop is not currently in the ops vector */ -#define prs_replrop(dstreg, op, srcprpos) \ - pr_replrop((dstreg).pr, (dstreg).pos.x, (dstreg).pos.y, \ - (dstreg).size.x, (dstreg).size.y, (op), \ - (srcprpos).pr, (srcprpos).pos.x , (srcprpos).pos.y ) - -/* pr_close is a synonym for pr_destroy */ -#define pr_close(pr) pr_destroy(pr) - -/* textured line macro */ -#define pr_line(pr, x0, y0, x1, y1, brush, tex, op) \ - pro_line((pr), (x0), (y0), (x1), (y1), (brush), (tex), (op), 0) - -#else /* !lint || KERNEL */ - -extern prs_rop(); -extern prs_stencil(); -extern prs_batchrop(); -extern prs_destroy(); -extern prs_get(); -extern prs_put(); -extern prs_vector(); -extern Pixrect *prs_region(); -extern prs_putcolormap(); -extern prs_getcolormap(); -extern prs_putattributes(); -extern prs_getattributes(); - -extern prs_replrop(); -extern pr_close(); -extern pr_line(); - -#endif /* !lint || KERNEL*/ - - - -/* - * magic flag passed to true color frame buffer to force updating the - * colormap. Yes, a kludge. - * Value defined to be the same as PIX_DONT_SET_PLANES purposedly - */ -#define PR_FORCE_UPDATE (1 << 24) -/* Yet another magic flag - to explicitly not use the - * inverse gamma table. - */ -#define PR_DONT_DEGAMMA (1 << 23) -#define PR_DEGAMMA (1 << 22) - -#define ROUNDUP(val, gran) (((val) - 1 | (gran) - 1) + 1) - -/* structure used to specify fields in a 32-bit pixel */ -union fbunit -{ - unsigned int packed; /* whole-sale deal */ - struct - { -unsigned int A: - 8; /* unused, for now */ -unsigned int B: - 8; /* blue channel */ -unsigned int G: - 8; /* green channel */ -unsigned int R: - 8; /* red channel */ - } - channel; /* access per channel */ -}; - -#define pr_putlut(pr, ind, cnt, red, grn, blu) \ - (*(pr)->pr_ops->pro_putcolormap)((pr), PR_FORCE_UPDATE | (ind), \ - (cnt), (red), (grn), (blu)) - -#ifndef KERNEL -#define pr_getlut(pr, ind, cnt, red, grn, blu) \ - (*(pr)->pr_ops->pro_getcolormap)((pr), PR_FORCE_UPDATE | (ind), \ - (cnt), (red), (grn), (blu)) -#endif /* !KERNEL */ - - -#endif /* !_pixrect_pixrect_h */ diff --git a/include/pixrect/pixrect_hs.h b/include/pixrect/pixrect_hs.h deleted file mode 100644 index 7ac23e50ff5..00000000000 --- a/include/pixrect/pixrect_hs.h +++ /dev/null @@ -1,37 +0,0 @@ -/* @(#)pixrect_hs.h 1.23 90/04/23 SMI */ - -/* - * Copyright 1986, 1987 by Sun Microsystems, Inc. - */ - -/* - * Include this header file to get all pixrect related header files. - */ - -#ifndef pixrect_hs_DEFINED -#define pixrect_hs_DEFINED - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include - -#endif pixrect_hs_DEFINED diff --git a/include/pixrect/pr_dblbuf.h b/include/pixrect/pr_dblbuf.h deleted file mode 100644 index d0749778744..00000000000 --- a/include/pixrect/pr_dblbuf.h +++ /dev/null @@ -1,36 +0,0 @@ -/* @(#)pr_dblbuf.h 1.7 90/10/26 SMI */ - -/* - * Copyright 1986 by Sun Microsystems, Inc. - */ - -#ifndef pr_dblbuf_DEFINED -#define pr_dblbuf_DEFINED - -/* Attributes - Unless otherwise indicated, attributes can be used for gets and sets. -*/ - - -#define PR_DBL_AVAIL 1 /* AVAIL is get only. */ -#define PR_DBL_DISPLAY 2 -#define PR_DBL_WRITE 3 -#define PR_DBL_READ 4 -#define PR_DBL_DISPLAY_DONTBLOCK 5 -/* Similar to PR_DBL_DISPLAY, but DONTBLOCK is for set only. */ -#define PR_DBL_DEPTH 6 /* get only attribute */ -#define PR_DBL_WID 7 /* does wid allow multiple double buffering */ -#define PR_DBL_AVAIL_PG 8 /* Avail for a given plane group (get only) */ - - -/* Attribute values: -*/ - -#define PR_DBL_EXISTS 1 /* Value for AVAIL only */ -#define PR_DBL_A 2 -#define PR_DBL_B 3 -#define PR_DBL_BOTH 4 /* for PR_DBL_WRITE only. */ -#define PR_DBL_NONE 5 -/* can only be returned by pr_dbl_get with PR_DBL_WRITE attribute. */ - -#endif pr_dblbuf_DEFINED diff --git a/include/pixrect/pr_impl_make.h b/include/pixrect/pr_impl_make.h deleted file mode 100644 index 9954dde4c33..00000000000 --- a/include/pixrect/pr_impl_make.h +++ /dev/null @@ -1,31 +0,0 @@ -/* @(#)pr_impl_make.h 1.2 88/02/08 SMI */ - -#ifndef pr_impl_make_DEFINED -#define pr_impl_make_DEFINED - -/* - * Copyright 1987 by Sun Microsystems, Inc. - */ - -/* - * Pr_devdata is used to keep track of the mmapped virtual - * address of a device to prevent mapping more than once. - */ -struct pr_devdata -{ - struct pr_devdata *next; /* link to next device of this type */ - dev_t rdev; /* device type */ - int count; /* reference count */ - int fd; /* fd of frame buffer, -1 if unused */ - caddr_t va; /* virtual address */ - int bytes; /* size of va, 0 for no munmap */ - caddr_t va2; /* second virtual address, 0 if unused */ - int bytes2; /* second size */ -}; - -#ifndef KERNEL -Pixrect *pr_makefromfd(); -Pixrect *pr_makefromfd_2(); -#endif !KERNEL - -#endif pr_impl_make_DEFINED diff --git a/include/pixrect/pr_impl_util.h b/include/pixrect/pr_impl_util.h deleted file mode 100644 index f257ce36062..00000000000 --- a/include/pixrect/pr_impl_util.h +++ /dev/null @@ -1,187 +0,0 @@ -/* @(#)pr_impl_util.h 1.10 89/05/19 SMI */ - -/* - * Copyright 1987-1989 Sun Microsystems, Inc. - */ - -/* - * Pixrect implementation utilities - */ - -#ifndef pr_impl_util_DEFINED -#define pr_impl_util_DEFINED - -/* Reiser cpp concatenation macros */ -#ifndef _CAT -#undef _IDENT -#define _IDENT(x) x -#define _CAT(a,b) _IDENT(a)b -#endif - -/* - * code selection macros - */ -#define IFTRUE(a,b) a -#define IFFALSE(a,b) b - -/* and together multiple options */ -#define IFAND IFAND2 -#define IFAND2(opt1,opt2,a,b) opt1(opt2(a,b),b) -#define IFAND3(opt1,opt2,opt3,a,b) opt1(opt2(opt3(a,b),b),b) -#define IFAND4(opt1,opt2,opt3,opt4,a,b) opt1(opt2(opt3(opt4(a,b),b),b),b) -#define IFAND5(opt1,opt2,opt3,opt4,opt5,a,b) \ - opt1(opt2(opt3(opt4(opt5(a,b),b),b),b),b) -#define IFAND6(opt1,opt2,opt3,opt4,opt5,opt6,a,b) \ - opt1(opt2(opt3(opt4(opt5(opt6(a,b),b),b),b),b),b) - -#ifdef KERNEL -#define IFKERNEL IFTRUE -#else -#define IFKERNEL IFFALSE -#endif - -/* - * lint garbage - */ -#ifdef lint - -#define IFLINT IFTRUE - -int _ZERO_; /* "constant in conditional context" workaround */ -#define _ONE_ (!_ZERO_) -int _loop; /* "_loop redefinition hides earlier one" */ - -#else lint - -#define IFLINT IFFALSE - -#define _ZERO_ 0 -#define _ONE_ 1 - -#endif lint - -/* - * portability aids - */ -#ifdef mc68000 - -#define IF68000 IFTRUE - -typedef caddr_t INT_T; /* pseudo-integer type (address register) */ -typedef u_long PTR_T; /* pseudo-pointer type (data register) */ -typedef short LOOP_T; /* loop variable (for dbra loops) */ - -#define LOOP_DECR(var) (--(var) != -1) - -#else mc68000 - -#define IF68000 IFFALSE - -typedef int INT_T; -typedef caddr_t PTR_T; -typedef int LOOP_T; - -#define LOOP_DECR(var) (--(var) >= 0) - -#endif mc68000 - -#ifdef sparc -#define IFSPARC IFTRUE -#else -#define IFSPARC IFFALSE -#endif - -/* true if we can make 32 bit accesses on 16 bit boundaries */ -#ifndef SHORT_ALIGN -#define SHORT_ALIGN (!defined(sparc)) -#endif - -#if SHORT_ALIGN -#define IFSHORT_ALIGN IFTRUE -#else -#define IFSHORT_ALIGN IFFALSE -#endif - - -#ifndef LITTLE_ENDIAN -#define LITTLE_ENDIAN defined(i386) -#endif - -#if LITTLE_ENDIAN -#define ENDIAN IFTRUE -#else -#define ENDIAN IFFALSE -#endif - -/* - * SunOS release number - * warning: these tests are fragile - */ -#if defined(sun) && !defined(SUNOS) -#ifdef _sys_types_h -#define SUNOS 41 -#else _sys_types_h -#ifdef NFDBITS -#define SUNOS 40 -#else NFDBITS -#define SUNOS 35 -#endif NFDBITS -#endif _sys_types_h -#endif - -#if SUNOS >= 40 -#define IFSUNOS4 IFTRUE -#else -#define IFSUNOS4 IFFALSE -#endif - -#if SUNOS >= 41 -#define IFSUNOS41 IFTRUE -#else -#define IFSUNOS41 IFFALSE -#endif - - -/* - * misc. macros - */ - -/* statement macro */ -#define _STMT(op) do { op } while (_ZERO_) - -/* loop macros */ -#define PR_LOOPVP(var, op) do { op; } while (LOOP_DECR(var)) -#define PR_LOOPV(var, op) _STMT(while (LOOP_DECR(var)) { op; }) -#define PR_LOOPP(count, op) _STMT( \ - IFLINT(, register LOOP_T) _loop = (count); PR_LOOPVP(_loop, op);) -#define PR_LOOP(count, op) _STMT( \ - IFLINT(, register LOOP_T) _loop = (count); PR_LOOPV(_loop, op);) - -/* pointer manipulation */ -#define PTR_ADD(p, incr) ((caddr_t) (p) + (incr)) -#define PTR_INCR(type, p, incr) (p = (type) ((caddr_t) (p) + (incr))) - -/* unshifted pixrect op codes */ -#define PIX_OPSRC (12) -#define PIX_OPDST (10) -#define PIX_OPNOT(op) ((op) ^ 15) -#define PIX_OPCLR (0) -#define PIX_OPSET (15) - -/* extract color and op code fields */ -#define PIXOP_COLOR(op) ((op) >> 5) -#define PIXOP_OP(op) ((op) >> 1 & 15) - -/* reverse video src or dst */ -#define PIX_OP_REVERSESRC(op) (((op) & 3) << 2 | (op) >> 2 & 3) -#define PIX_OP_REVERSEDST(op) ((~(op) & 5) << 1 | ~(op) >> 1 & 0x5) - -/* determine if op needs src or dst */ -#define PIX_OP_NEEDS_SRC(op) (((op) >> 2 ^ (op)) & 3) -#define PIX_OP_NEEDS_DST(op) (((op) >> 1 ^ (op)) & 5) - -/* misc. data types */ -typedef short MPR_T; /* type used for memory pixrect data */ -typedef u_short UMPR_T; /* unsigned equivalent of MPR_T */ - -#endif pr_impl_util_DEFINED diff --git a/include/pixrect/pr_io.h b/include/pixrect/pr_io.h deleted file mode 100644 index e4acba74d59..00000000000 --- a/include/pixrect/pr_io.h +++ /dev/null @@ -1,57 +0,0 @@ -/* @(#)pr_io.h 1.7 88/02/08 SMI */ - -/* - * Copyright (c) 1984 by Sun Microsystems, Inc. - */ - -#ifndef pr_io_DEFINED -#define pr_io_DEFINED - -/* - * Data definitions and constant definitions for clients of utilities - * to do i/o between pixrects and rasterfiles. - * - */ - -typedef struct -{ - int type; - int length; - unsigned char *map[3]; -} -colormap_t; -/* - * The type should be one of the supported ras_maptype's in rasterfile.h. - * Note: the interpretation of the length and map array depends on the type. - */ - - -/* error messages */ -#define PR_IO_ERR_BADDEPTH "Cannot replicate color pixrect if depth != 8" -#define PR_IO_ERR_CDEPTH \ - "Color raster depth does not match display depth" -#define PR_IO_ERR_DISPLAY "Cannot open display device" -#define PR_IO_ERR_INFILE "Cannot open input file" -#define PR_IO_ERR_NOBWDISPLAY \ - "Cannot open display device for monochrome raster" -#define PR_IO_ERR_NOCDISPLAY "Cannot open display device for color raster" -#define PR_IO_ERR_NONULL "Cannot process null argument" -#define PR_IO_ERR_OUTFILE "Cannot open output file" -#define PR_IO_ERR_PIXRECT "Internal pixrect operation failed" -#define PR_IO_ERR_RASREAD "Error reading rasterfile input data" -#define PR_IO_ERR_RASREADH "Error reading rasterfile header" -#define PR_IO_ERR_RASWRITE "Error writing rasterfile output data" -#define PR_IO_ERR_RASWRITEH "Error writing rasterfile header" - -/* declarations */ -extern int pr_dump(); -extern int pr_dump_header(); -extern int pr_dump_image(); -extern Pixrect * pr_dump_init(); -extern Pixrect * pr_load(); -extern int pr_load_colormap(); -extern int pr_load_header(); -extern Pixrect * pr_load_image(); -extern Pixrect * pr_load_std_image(); - -#endif pr_io_DEFINED diff --git a/include/pixrect/pr_line.h b/include/pixrect/pr_line.h deleted file mode 100644 index 223f2b717d4..00000000000 --- a/include/pixrect/pr_line.h +++ /dev/null @@ -1,69 +0,0 @@ -/* @(#)pr_line.h 1.15 88/02/08 SMI */ - -/* - * Copyright 1986 by Sun Microsystems, Inc. - */ - - -#ifndef pr_line_h_DEFINED -#define pr_line_h_DEFINED - -#define POLY_CLOSE ((u_char *) 1) -#define POLY_DONTCLOSE ((u_char *) 0) - -extern short pr_tex_dotted[]; -extern short pr_tex_dashed[]; -extern short pr_tex_dashdot[]; -extern short pr_tex_dashdotdotted[]; -extern short pr_tex_longdashed[]; - - -typedef -struct pr_texture -{ - short *pattern; - short offset; - struct pr_texture_options - { -unsigned startpoint : - 1, -endpoint : - 1, -balanced : - 1, -givenpattern : - 1, -res_fat : - 1, -res_poly : - 1, -res_mvlist : - 1, -res_right : - 1, -res_close : - 1, -res_cliprt : - 1; - } - options; - short res_polyoff; - short res_oldpatln; - short res_fatoff; - short *res_patfat; - short res_numsegs; -} -Pr_texture; - - -typedef -struct pr_brush -{ - int width; -} -Pr_brush; - -#endif /*pr_line_h_DEFINED */ - - - diff --git a/include/pixrect/pr_planegroups.h b/include/pixrect/pr_planegroups.h deleted file mode 100644 index 358ba7d979e..00000000000 --- a/include/pixrect/pr_planegroups.h +++ /dev/null @@ -1,52 +0,0 @@ -/* @(#)pr_planegroups.h 1.13 91/05/09 SMI */ - -/* - * Copyright 1986 by Sun Microsystems, Inc. - */ - -#ifndef pr_planegroups_DEFINED -#define pr_planegroups_DEFINED - -/* Masks for frame buffer planes and plane group number */ -#define PIX_ALL_PLANES 0x00FFFFFF -#define PIX_GROUP_MASK 0x7F - -/* Macros to encode or extract group into or from attribute word */ -#define PIX_GROUP(g) ((g) << 25) -#define PIX_ATTRGROUP(attr) ((unsigned)(attr) >> 25) - -/* Flag bit which inhibits plane mask setting (for setting group only) */ -#define PIX_DONT_SET_PLANES (1 << 24) - -/* Plane groups definitions */ -/* !!! NOTE: Be sure to increment LAST_PLUS_ONE as new groups are added !!! */ - -#define PIXPG_CURRENT 0 -#define PIXPG_MONO 1 -#define PIXPG_8BIT_COLOR 2 -#define PIXPG_OVERLAY_ENABLE 3 -#define PIXPG_OVERLAY 4 -#define PIXPG_24BIT_COLOR 5 -#define PIXPG_VIDEO 6 -#define PIXPG_VIDEO_ENABLE 7 -#define PIXPG_TRANSPARENT_OVERLAY 8 -#define PIXPG_WID 9 /* Window Id */ -#define PIXPG_ZBUF 10 /* Z (depth) buffer */ -#define PIXPG_CURSOR_ENABLE 11 -#define PIXPG_CURSOR 12 -#define PIXPG_LAST_PLUS_ONE 13 /* array decls and loop termination */ -#define PIXPG_4BIT_OVERLAY 123 -#define PIXPG_ALT_COLOR 124 -#define PIXPG_A12BIT_COLOR 125 -#define PIXPG_B12BIT_COLOR 126 -#define PIXPG_INVALID 127 - -#define MAKEPLNGRP(pg) (1 << (pg)) - -/* Plane groups functions */ -extern int pr_available_plane_groups(); -extern int pr_get_plane_group(); -extern void pr_set_plane_group(); -extern void pr_set_planes(); - -#endif /* pr_planegroups_DEFINED*/ diff --git a/include/pixrect/pr_util.h b/include/pixrect/pr_util.h deleted file mode 100644 index adeadde2acd..00000000000 --- a/include/pixrect/pr_util.h +++ /dev/null @@ -1,139 +0,0 @@ -/* @(#)pr_util.h 1.18 88/02/08 SMI */ - -/* - * Copyright 1983, 1986, 1987 by Sun Microsystems, Inc. - */ - -#ifndef pr_util_DEFINED -#define pr_util_DEFINED - -/* - * WARNING: This include file is obsolete and may disappear in the future. - * - * pr_product has been moved to pixrect.h - * struct pr_devdata etc. has been moved to pr_impl_make.h - * new loop macros are in pr_impl_util.h - */ - -/* - * Utilities for implementing pixrect operations. - */ - -/* - * Aids to handling overlapping source and destination. - * Given the from and to pr_pos's, rop_direction tells - * whether the rasterop is up or down and left or right, - * encoded as the ROP_UP and ROP_LEFT bits or their absence. - * The macros rop_is(up|down|left|right) can then be used. - */ -#define ROP_UP 0x1 -#define ROP_LEFT 0x2 - -#define rop_direction(src, so, dst, do) \ - ( ( (((dst).x+(do).x) < ((src).x+(so).x)) << 1) | \ - (((dst).y+(do).y) < ((src).y+(so).y)) ) -#define rop_isleft(dir) ((dir)&ROP_LEFT) -#define rop_isup(dir) ((dir)&ROP_UP) -#define rop_isright(dir) (((dir)&ROP_LEFT)==0) -#define rop_isdown(dir) (((dir)&ROP_UP)==0) - -/* - * Aids to producing fast loops, either unrolled or very tight: - * - * Cases8(n, op) produces the dense case part of a case statement - * for the cases [n+1..n+8), repeating ``op'' 1-8 times respectively. - * - * Rop_slowloop(n, op) produces a loop to do ``op'' n times, in little space. - * - * Rop_fastloop(n, op) produces a loop to do ``op'' n times, in little time. - * - * Loop_d6(label, op) produces a dbra loop to do ``op'' the number of times - * in register d6 (second non-pointer register variable). - * - * Loop_d6 is only possible on a 68000 family processor, and rop_fastloop - * generates an unrolled loop only on a 68010 (assumes other processors - * will have some kind of I-cache). - */ -#ifdef mc68000 -/* generates a nice dbra loop */ -#define rop_slowloop(n, op) \ - { register int _loop = (n); \ - if (--_loop >= 0) do { op; } while (--_loop != -1); } - -#define loopd6(label, op) \ - if (0) { \ - asm("label:"); \ - op; \ - }; \ - asm("dbra d6,label"); -#else /* mc68000*/ -#define rop_slowloop(n, op) \ - { register int _loop = (n); \ - while (--_loop >= 0) { op; } } -#endif /* mc68000*/ - -#ifdef mc68010 -#define cases8(n, op) \ - case (n)+8: op; case (n)+7: op; case (n)+6: op; \ - case (n)+5: op; case (n)+4: op; case (n)+3: op; \ - case (n)+2: op; case (n)+1: op; \ - -#define rop_fastloop(n, op) \ - { register int _loop ; \ - for (_loop = (n); _loop > 15; _loop -= 16) \ - { op; op; op; op; op; op; op; op; \ - op; op; op; op; op; op; op; op; } \ - switch (_loop) { \ - cases8(8, op); \ - cases8(0, op); \ - case 0: break; \ - } } -#else /*mc68010*/ -#define rop_fastloop rop_slowloop -#endif /*mc68010*/ - -/* - * Alloctype(datatype) allocates a datatype structure using calloc - * with the appropriate type cast. - */ -#define alloctype(datatype) \ - (datatype *)calloc(1, sizeof (datatype)) - -/* - * Pr_product is used when doing multiplications involving pixrects, - * and casts its arguments to that the compiler will use 16 by 16 multiplies. - */ -#ifndef pr_product -#ifdef sun -#define pr_product(a, b) ((short)(a) * (short)(b)) -#else -#define pr_product(a, b) ((a) * (b)) -#endif -#endif - -/* - * Pr_area is the area of a rectangle. - */ -#define pr_area(size) pr_product((size).x, (size).y) - -/* - * Pr_devdata is used to keep track of the valloced/mmapped virtual - * address of a device to prevent doing it more than necessary. - */ -struct pr_devdata -{ - struct pr_devdata *next; /* link to next device of this type */ - dev_t rdev; /* device type */ - int count; /* reference count */ - int fd; /* fd of frame buffer, -1 if unused */ - short *va; /* virtual address */ - int bytes; /* size of va, 0 for no munmap */ - caddr_t va2; /* second virtual address, 0 if unused */ - int bytes2; /* second size */ -}; - -#ifndef KERNEL -Pixrect *pr_makefromfd(); -#endif /*!KERNEL*/ - -#endif /*pr_util_DEFINED*/ diff --git a/include/pixrect/traprop.h b/include/pixrect/traprop.h deleted file mode 100644 index bdedd1d82f4..00000000000 --- a/include/pixrect/traprop.h +++ /dev/null @@ -1,29 +0,0 @@ -/* @(#)traprop.h 1.7 88/02/08 SMI */ - -/* - * Copyright (c) 1984 by Sun Microsystems, Inc. - */ - -#ifndef traprop_DEFINED -#define traprop_DEFINED - -struct pr_chain -{ - struct pr_chain *next; - struct pr_size size; /* size of bounding box */ - int *bits; /* chain-encoding bits */ -}; - -struct pr_fall -{ - struct pr_pos pos; /* position of top of fall */ - struct pr_chain *chain; /* trajectory of fall */ -}; - -struct pr_trap -{ - struct pr_fall *left, *right; /* falls = left+right boundaries */ - int y0, y1; /* top+bottom boundaries */ -}; - -#endif /*traprop_DEFINED*/ diff --git a/include/pixrect/tv1var.h b/include/pixrect/tv1var.h deleted file mode 100644 index 08c4539fcdd..00000000000 --- a/include/pixrect/tv1var.h +++ /dev/null @@ -1,63 +0,0 @@ -/* @(#)tv1var.h 1.1 89/06/05 SMI */ - -/* - * Copyright 1988 by Sun Microsystems, Inc. - */ - -#ifndef tv1var_DEFINED -#define tv1var_DEFINED - -#include -#include -#include -#include -#include - -#define TV1_NFBS 2 -#define TV1_PRIMARY CG4_PRIMARY - -struct tv1_data -{ - struct mprp_data mprp; - int flags; - int fd; - short active; - unsigned int planes; - struct pr_pos offset; - struct csr *tv1_csr; - struct pr_size fbsize[TV1_NFBS]; - struct cg4fb fb[TV1_NFBS]; - struct pixrect *emufb; - struct pixrect *pr_video_enable; - struct pixrect *pr_video; -}; - -struct tv1_enable_data -{ - struct pixrect *sub_pixrect; /* pointer to the other pixrect */ - struct pr_pos *offset; /* pointer to offset, (in shared mem RO) */ - struct pr_pos region_start; /* start of region */ -}; - - -/* DELETE THE FOLLOWING DURING CLEAN UP - ALL REFS SHOULD - BE DIRECTLY VIA get_tv1_data -dw */ -#define tv1_d(pr) ((struct tv1_data *)((pr)->pr_data)) - -#define tv1_enable_d(pr) ((struct tv1_enable_data *)((pr)->pr_data)) - -#ifndef KERNEL - -Pixrect *tv1_make (); -int tv1_destroy (); -Pixrect *tv1_region (); -int tv1_getcolormap (); -int tv1_getattributes (); - -#ifndef ROUNDUP -#define ROUNDUP(val, gran) (((val) - 1 | (gran) - 1) + 1) -#endif - -#endif !KERNEL - -#endif tv1var_DEFINED diff --git a/include/pnm.h b/include/pnm.h deleted file mode 100644 index a17114a2851..00000000000 --- a/include/pnm.h +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file pnm.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* pnm.h - header file for libpnm portable anymap library -*/ - -#ifndef _PNM_H_ -#define _PNM_H_ - -#include "ppm.h" -typedef pixel xel; -typedef pixval xelval; -#define PNM_MAXMAXVAL PPM_MAXMAXVAL -#define PNM_GET1(x) PPM_GETB(x) -#define PNM_ASSIGN1(x,v) PPM_ASSIGN(x,0,0,v) -#define PNM_EQUAL(x,y) PPM_EQUAL(x,y) -#define PNM_FORMAT_TYPE(f) PPM_FORMAT_TYPE(f) - -/* Declarations of routines. */ - -void pnm_init ARGS(( int* argcP, char* argv[] )); - -#define pnm_allocarray( cols, rows ) ((xel**) pm_allocarray( cols, rows, sizeof(xel) )) -#define pnm_allocrow( cols ) ((xel*) pm_allocrow( cols, sizeof(xel) )) -#define pnm_freearray( xels, rows ) pm_freearray( (char**) xels, rows ) -#define pnm_freerow( xelrow ) pm_freerow( (char*) xelrow ) - -xel** pnm_readpnm ARGS(( FILE* file, int* colsP, int* rowsP, xelval* maxvalP, int* formatP )); -void pnm_readpnminit ARGS(( FILE* file, int* colsP, int* rowsP, xelval* maxvalP, int* formatP )); -void pnm_readpnmrow ARGS(( FILE* file, xel* xelrow, int cols, xelval maxval, int format )); - -void pnm_writepnm ARGS(( FILE* file, xel** xels, int cols, int rows, xelval maxval, int format, int forceplain )); -void pnm_writepnminit ARGS(( FILE* file, int cols, int rows, xelval maxval, int format, int forceplain )); -void pnm_writepnmrow ARGS(( FILE* file, xel* xelrow, int cols, xelval maxval, int format, int forceplain )); - -xel pnm_backgroundxel ARGS(( xel** xels, int cols, int rows, xelval maxval, int format )); -xel pnm_backgroundxelrow ARGS(( xel* xelrow, int cols, xelval maxval, int format )); -xel pnm_whitexel ARGS(( xelval maxval, int format )); -xel pnm_blackxel ARGS(( xelval maxval, int format )); -void pnm_invertxel ARGS(( xel* x, xelval maxval, int format )); -void pnm_promoteformat ARGS(( xel** xels, int cols, int rows, xelval maxval, int format, xelval newmaxval, int newformat )); -void pnm_promoteformatrow ARGS(( xel* xelrow, int cols, xelval maxval, int format, xelval newmaxval, int newformat )); - -extern xelval pnm_pbmmaxval; -/* This is the maxval used when a PNM program reads a PBM file. Normally -** it is 1; however, for some programs, a larger value gives better results -*/ - -#endif /*_PNM_H_*/ diff --git a/include/pointset.hpp b/include/pointset.h similarity index 97% rename from include/pointset.hpp rename to include/pointset.h index 94b5e4d0501..f4ace8f98c2 100644 --- a/include/pointset.hpp +++ b/include/pointset.h @@ -1,5 +1,5 @@ -#ifndef POINTSET_HPP -#define POINTSET_HPP +#ifndef POINTSET_H +#define POINTSET_H #include #include diff --git a/include/ppm.h b/include/ppm.h deleted file mode 100644 index f315bcb8f49..00000000000 --- a/include/ppm.h +++ /dev/null @@ -1,132 +0,0 @@ -/** - * @file ppm.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* ppm.h - header file for libppm portable pixmap library -*/ - -#ifndef _PPM_H_ -#define _PPM_H_ - -#include "pgm.h" - -typedef gray pixval; - -#ifdef PPM_PACKCOLORS - -#define PPM_MAXMAXVAL 1023 -typedef unsigned long pixel; -#define PPM_GETR(p) (((p) & 0x3ff00000) >> 20) -#define PPM_GETG(p) (((p) & 0xffc00) >> 10) -#define PPM_GETB(p) ((p) & 0x3ff) - -/************* added definitions *****************/ -#define PPM_PUTR(p, red) ((p) |= (((red) & 0x3ff) << 20)) -#define PPM_PUTG(p, grn) ((p) |= (((grn) & 0x3ff) << 10)) -#define PPM_PUTB(p, blu) ((p) |= ( (blu) & 0x3ff)) -/**************************************************/ - -#define PPM_ASSIGN(p,red,grn,blu) (p) = ((pixel) (red) << 20) | ((pixel) (grn) << 10) | (pixel) (blu) -#define PPM_EQUAL(p,q) ((p) == (q)) - -#else /*PPM_PACKCOLORS*/ - -#define PPM_MAXMAXVAL PGM_MAXMAXVAL -typedef struct -{ - pixval r, g, b; -} -pixel; -#define PPM_GETR(p) ((p).r) -#define PPM_GETG(p) ((p).g) -#define PPM_GETB(p) ((p).b) - -/************* added definitions *****************/ -#define PPM_PUTR(p,red) ((p).r = (red)) -#define PPM_PUTG(p,grn) ((p).g = (grn)) -#define PPM_PUTB(p,blu) ((p).b = (blu)) -/**************************************************/ - -#define PPM_ASSIGN(p,red,grn,blu) do { (p).r = (red); (p).g = (grn); (p).b = (blu); } while ( 0 ) -#define PPM_EQUAL(p,q) ( (p).r == (q).r && (p).g == (q).g && (p).b == (q).b ) - -#endif /*PPM_PACKCOLORS*/ - - -/* Magic constants. */ - -#define PPM_MAGIC1 'P' -#define PPM_MAGIC2 '3' -#define RPPM_MAGIC2 '6' -#define PPM_FORMAT (PPM_MAGIC1 * 256 + PPM_MAGIC2) -#define RPPM_FORMAT (PPM_MAGIC1 * 256 + RPPM_MAGIC2) -#define PPM_TYPE PPM_FORMAT - - -/* Macro for turning a format number into a type number. */ - -#define PPM_FORMAT_TYPE(f) ((f) == PPM_FORMAT || (f) == RPPM_FORMAT ? PPM_TYPE : PGM_FORMAT_TYPE(f)) - - -/* Declarations of routines. */ - -void ppm_init ARGS(( int* argcP, char* argv[] )); - -#define ppm_allocarray( cols, rows ) ((pixel**) pm_allocarray( cols, rows, sizeof(pixel) )) -#define ppm_allocrow( cols ) ((pixel*) pm_allocrow( cols, sizeof(pixel) )) -#define ppm_freearray( pixels, rows ) pm_freearray( (char**) pixels, rows ) -#define ppm_freerow( pixelrow ) pm_freerow( (char*) pixelrow ) - -pixel** ppm_readppm ARGS(( FILE* file, int* colsP, int* rowsP, pixval* maxvalP )); -void ppm_readppminit ARGS(( FILE* file, int* colsP, int* rowsP, pixval* maxvalP, int* formatP )); -void ppm_readppmrow ARGS(( FILE* file, pixel* pixelrow, int cols, pixval maxval, int format )); - -void ppm_writeppm ARGS(( FILE* file, pixel** pixels, int cols, int rows, pixval maxval, int forceplain )); -void ppm_writeppminit ARGS(( FILE* file, int cols, int rows, pixval maxval, int forceplain )); -void ppm_writeppmrow ARGS(( FILE* file, pixel* pixelrow, int cols, pixval maxval, int forceplain )); - -pixel ppm_parsecolor ARGS(( char* colorname, pixval maxval )); -char* ppm_colorname ARGS(( pixel* colorP, pixval maxval, int hexok )); - -extern pixval ppm_pbmmaxval; -/* This is the maxval used when a PPM program reads a PBM file. Normally -** it is 1; however, for some programs, a larger value gives better results -*/ - - -/* Color scaling macro -- to make writing ppmtowhatever easier. */ - -#define PPM_DEPTH(newp,p,oldmaxval,newmaxval) \ - PPM_ASSIGN( (newp), \ - ( (int) PPM_GETR(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \ - ( (int) PPM_GETG(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \ - ( (int) PPM_GETB(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval) ) - - -/* Luminance macro. */ - -#define PPM_LUMIN(p) ( 0.299 * PPM_GETR(p) + 0.587 * PPM_GETG(p) + 0.114 * PPM_GETB(p) ) - -#endif /*_PPM_H_*/ diff --git a/include/queue.h b/include/queue.h deleted file mode 100644 index c7f005ca503..00000000000 --- a/include/queue.h +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file queue.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)queue.h 1.4 - 3/31/94 -*/ -/*------------------------------------------------------------------------ - File Name: queue.h - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: - -------------------------------------------------------------------------*/ - - -#ifndef QUEUE_H -#define QUEUE_H - - -typedef struct _qelt_ -{ - struct _qelt_ *next ; - struct _qelt_ *prev ; - void *data ; -} -QELT ; - -typedef struct -{ - QELT *head ; - QELT *tail ; - int nelts ; /* # of elements in queue */ - int mode ; -} -QUEUE ; - -#define Q_WAIT_FOR_DATA 1 -#define Q_DONT_WAIT 2 - -#ifdef ANSI -int Qput(QUEUE *q, void *data) ; -void *Qget(QUEUE *q, int mode) ; -QUEUE *Qalloc(int max_elts) ; -void Qfree(QUEUE *q); -#else -int Qput() ; -void *Qget() ; -QUEUE *Qalloc() ; -void Qfree(); -#endif - - -#define Qempty(q) (((q)->head == NULL)) -#define Qfirst(q) ((q)->head ? (q)->head->data : NULL) -#define Qnelts(q) ((q)->nelts) - -#endif - - - diff --git a/include/rbf.h b/include/rbf.h index 7e3dc97d3c1..b9b243e5811 100644 --- a/include/rbf.h +++ b/include/rbf.h @@ -74,24 +74,24 @@ typedef struct } RBF ; -RBF *RBFinit(int ninputs, int noutputs, int max_clusters[], char *names[]) ; +RBF *RBFinit(int ninputs, int noutputs, int max_clusters[], const char *names[]) ; int RBFtrain(RBF *rbf, int (*get_observation_func) - (VECTOR *v_obs, int no, void *parm, int same_class,int *class), + (VECTOR *v_obs, int no, void *parm, int same_class,int *classnum), void *parm, float momentum) ; int RBFretrain(RBF *rbf, int (*get_observation_func) - (VECTOR *v_obs, int no, void *parm, int same_class,int *class), + (VECTOR *v_obs, int no, void *parm, int same_class,int *classnum), void *parm, float momentum) ; int RBFfree(RBF **prbf) ; int RBFprint(RBF *rbf, FILE *fp) ; int RBFprintActivations(RBF *rbf, VECTOR *v_obs, VECTOR *v_error, - int class, FILE *fp); + int classnum, FILE *fp); int RBFclassify(RBF *rbf, VECTOR *v_obs) ; int RBFwrite(RBF *rbf, char *fname) ; RBF *RBFread(char *fname) ; int RBFwriteInto(RBF *rbf, FILE *fp) ; RBF *RBFreadFrom(FILE *fp) ; RBF *RBFcopyWeights(RBF *rbf_src, RBF *rbf_dst) ; -float RBFcomputeErrors(RBF *rbf, int class, VECTOR *v_error) ; +float RBFcomputeErrors(RBF *rbf, int classnum, VECTOR *v_error) ; int RBFexamineTrainingSet(RBF *rbf, int (*get_observation_func) (VECTOR *v_obs, int no, void *parm, int same_class,int *pclass), void *parm) ; diff --git a/include/rec.h b/include/rec.h deleted file mode 100644 index 0e6d6c4cfc0..00000000000 --- a/include/rec.h +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @file rec.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef REC_H -#define REC_H - -#include "matrix.h" - -typedef struct -{ - int ntimepts ; - int ptime ; - int neeg_channels ; - int nmeg_channels ; - float *latencies ; - MATRIX *m_data ; -} -REC ; - - -/* each column is a time course (except 1st)*/ -REC *RecRead(char *fname, int iop_neeg, int iop_nmeg) ; - -/* flag == 1 - load only EEG channels - flag == 2 - load only MEG channels -*/ -REC *RecReadPartially(char *fname, int iop_neeg, int iop_nmeg, int flag) ; -#endif diff --git a/include/rescale.h b/include/rescale.h deleted file mode 100644 index 10610a3fda1..00000000000 --- a/include/rescale.h +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @file rescale.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/******************************************************************* - * Name: rescale.h - * Author: Douglas N. Greve, 5/14/96 - * Purpose: rescales the pixels of an image to within the given - * maximum and minimum. As a bonus, it also returns - * the row and column of the min and max. - *******************************************************************/ -#ifndef RESCALE_INC -#define RESCALE_INC -int h_rescale(struct header *phdSrc, - float NewMin, float NewMax, - int MinPoint[2], int MaxPoint[2], - struct header *phdDst); -int h_rescale_fb(struct header *phdSrc, - float Slope, float Offset, - struct header *phdDst); -int h_rescale_ff(struct header *phdSrc, - float Slope, float Offset, - struct header *phdDst); -#endif /** from #ifndef RESCALE_INC *****/ diff --git a/include/rfa.h b/include/rfa.h index dcd5849c795..468e45f4f06 100644 --- a/include/rfa.h +++ b/include/rfa.h @@ -26,11 +26,6 @@ #ifndef RFA_H #define RFA_H -#if defined(__cplusplus) -extern "C" { -#endif - - #include "mri.h" #include "transform.h" #include "colortab.h" @@ -109,14 +104,7 @@ int RFAsourceVoxelToAtlas( const RFA *rfa, MRI *mri, TRANSFORM *transform, double *px, double *py, double *pz ) ; int extract_feature(MRI *mri_in, int wsize, int x, int y, int z, double *feature, int xatlas, int yatlas, int zatlas) ; - -#if defined(__cplusplus) -}; -#endif - - - #define NOT_TRAINING_LABEL(l) (\ ((l) == Left_Accumbens_area) || \ ((l) == Right_Accumbens_area) || \ @@ -154,4 +142,5 @@ int extract_feature(MRI *mri_in, int wsize, int x, int y, int z, double *featur int MRIcountCSFInNbhd(MRI *mri_seg, int wsize, int x, int y, int z) ; int extract_long_features(MRI *mri_in, MRI *mri_seg, TRANSFORM *transform, GCA *gca, int wsize, int x, int y, int z, double *feature); + #endif diff --git a/include/rfutils.h b/include/rfutils.h index af1e70d2131..61e3754262c 100644 --- a/include/rfutils.h +++ b/include/rfutils.h @@ -26,11 +26,6 @@ #ifndef RFUTILS_H #define RFUTILS_H -#if defined(__cplusplus) -extern "C" { -#endif - - #include "mri.h" #include "transform.h" #include "colortab.h" @@ -39,6 +34,4 @@ extern "C" { #include "rforest.h" #include "cma.h" - - #endif diff --git a/include/rgb.h b/include/rgb.h new file mode 100644 index 00000000000..93b83b36409 --- /dev/null +++ b/include/rgb.h @@ -0,0 +1,120 @@ +#ifndef RGB_H +#define RGB_H + +#include + +/* + * Defines for image files . . . . + * + * Paul Haeberli - 1984 + * Look in /usr/people/4Dgifts/iristools/imgtools for example code! + * + */ + +#define IMAGIC 0732 +#define CM_NORMAL 0 +#define CM_DITHERED 1 +#define CM_SCREEN 2 +#define CM_COLORMAP 3 + +#define TYPEMASK 0xff00 +#define BPPMASK 0x00ff +#define ITYPE_VERBATIM 0x0000 +#define ITYPE_RLE 0x0100 +#define ISRLE(type) (((type) & 0xff00) == ITYPE_RLE) +#define ISVERBATIM(type) (((type) & 0xff00) == ITYPE_VERBATIM) +#define BPP(type) ((type) & BPPMASK) +#define RLE(bpp) (ITYPE_RLE | (bpp)) +#define UNCOMPRESSED(bpp) (ITYPE_VERBATIM | (bpp)) +#define IBUFSIZE(pixels) ((pixels+(pixels>>6))<<2) +#define RLE_NOP 0x00 + +#define ierror(p) (((p)->flags&_IOERR)!=0) +#define ifileno(p) ((p)->file) + +typedef struct { + unsigned short imagic; + unsigned short type; + unsigned short dim; + unsigned short xsize; + unsigned short ysize; + unsigned short zsize; + unsigned int min; + unsigned int max; + unsigned int wastebytes; + char name[80]; + unsigned int colormap; + int file; + unsigned short flags; + short dorev; + short x; + short y; + short z; + short cnt; + unsigned short *ptr; + unsigned short *base; + unsigned short *tmpbuf; + unsigned int offset; + unsigned int rleend; + unsigned int *rowstart; + int *rowsize; +} +RGB_IMAGE; + +RGB_IMAGE *icreate(); +RGB_IMAGE *iopen(const char *file, const char *mode, unsigned int type, unsigned int dim, unsigned int xsize, unsigned int ysize, unsigned int zsize); +RGB_IMAGE *fiopen(int f, const char *mode, unsigned int type, unsigned int dim, unsigned int xsize, unsigned int ysize, unsigned int zsize); +long reverse(unsigned long lwrd); +void cvtshorts( unsigned short *buffer, long n); +void i_seterror(void (*func)(char *)); +int getpix(RGB_IMAGE *image); +unsigned int putpix(RGB_IMAGE *image, unsigned int pix); +int img_read(RGB_IMAGE *image, char *buffer, int count); +int img_write(RGB_IMAGE *image, char *buffer,int count); +int img_badrow(RGB_IMAGE *image, unsigned int y, unsigned int z); +unsigned long img_seek(RGB_IMAGE *image, unsigned int y, unsigned int z); +long img_getrowsize(RGB_IMAGE *image); +void img_setrowsize(RGB_IMAGE *image, long cnt, long y, long z); +int img_rle_compact(unsigned short *expbuf, int ibpp, unsigned short *rlebuf, int obpp, int cnt); +void img_rle_expand(unsigned short *rlebuf, int ibpp, unsigned short *expbuf, int obpp); +int putrow(RGB_IMAGE *image, unsigned short *buffer, unsigned int y, unsigned int z); +int getrow(RGB_IMAGE *image, unsigned short *buffer, unsigned int y, unsigned int z); + +unsigned short *ibufalloc(RGB_IMAGE *image); +int ifilbuf(RGB_IMAGE *image); +int iflush(RGB_IMAGE *image); +unsigned int iflsbuf(RGB_IMAGE *image, unsigned int c); +void isetname(RGB_IMAGE *image, const char *name); +void isetcolormap(RGB_IMAGE *image, int colormap); + +int iclose(RGB_IMAGE *image); +int putrow(RGB_IMAGE *image, unsigned short *buffer,unsigned int y,unsigned int z); +int putrow_uc(RGB_IMAGE *image, unsigned char *buffer, unsigned int y, unsigned int z); +int getrow(RGB_IMAGE *image, unsigned short *buffer,unsigned int y,unsigned int z); + +#define IMAGEDEF + +unsigned long img_optseek(RGB_IMAGE *image, unsigned long offset); +int img_write(RGB_IMAGE *image, char *buffer,int count); +void cvtimage( long *buffer); +void cvtlongs( long *buffer, register long n); +void i_errhdlr(const char *fmt, int a1, int a2, int a3, int a4); +void swapImage(RGB_IMAGE *image); + +#ifndef _IOREAD +#define _IOREAD 0001 +#endif +#ifndef _IOWRT +#define _IOWRT 0002 +#endif +#ifndef _IOEOF +#define _IOEOF 0020 +#endif +#ifndef _IOERR +#define _IOERR 0040 +#endif +#ifndef _IORW +#define _IORW 0200 +#endif + +#endif diff --git a/include/rgb_image.h b/include/rgb_image.h deleted file mode 100644 index a06598a9e81..00000000000 --- a/include/rgb_image.h +++ /dev/null @@ -1,197 +0,0 @@ -/** - * @file rgb_image.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.12 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef __GL_RGB_IMAGE_H__ -#define __GL_RGB_IMAGE_H__ -#ifdef __cplusplus -extern "C" -{ -#endif - - - /* - * Defines for image files . . . . - * - * Paul Haeberli - 1984 - * Look in /usr/people/4Dgifts/iristools/imgtools for example code! - * - */ - -#include - -#define IMAGIC 0732 - - /* colormap of images */ -#define CM_NORMAL 0 /* file contains rows of values which - * are either RGB values (zsize == 3) - * or greyramp values (zsize == 1) */ -#define CM_DITHERED 1 -#define CM_SCREEN 2 /* file contains data which is a screen - * image; - getrow returns buffer which - * can be displayed directly with - * writepixels */ -#define CM_COLORMAP 3 /* a colormap file */ - -#define TYPEMASK 0xff00 -#define BPPMASK 0x00ff -#define ITYPE_VERBATIM 0x0000 -#define ITYPE_RLE 0x0100 -#define ISRLE(type) (((type) & 0xff00) == ITYPE_RLE) -#define ISVERBATIM(type) (((type) & 0xff00) == ITYPE_VERBATIM) -#define BPP(type) ((type) & BPPMASK) -#define RLE(bpp) (ITYPE_RLE | (bpp)) -#define UNCOMPRESSED(bpp) (ITYPE_VERBATIM | (bpp)) -#define IBUFSIZE(pixels) ((pixels+(pixels>>6))<<2) -#define RLE_NOP 0x00 - -#define ierror(p) (((p)->flags&_IOERR)!=0) -#define ifileno(p) ((p)->file) -#define getpix(p) (--(p)->cnt>=0 ? *(p)->ptr++ : ifilbuf(p)) -#define putpix(p,x) (--(p)->cnt>=0 \ - ? ((int)(*(p)->ptr++=(unsigned)(x))) \ - : iflsbuf(p,(unsigned)(x))) - - typedef struct - { - unsigned short imagic; /* stuff saved on disk . . */ - unsigned short type; - unsigned short dim; - unsigned short xsize; - unsigned short ysize; - unsigned short zsize; - unsigned int min; - unsigned int max; - unsigned int wastebytes; - char name[80]; - unsigned int colormap; - - int file; /* stuff used in core only */ - unsigned short flags; - short dorev; - short x; - short y; - short z; - short cnt; - unsigned short *ptr; - unsigned short *base; - unsigned short *tmpbuf; - unsigned int offset; - unsigned int rleend; /* for rle images */ - unsigned int *rowstart; /* for rle images */ - int *rowsize; /* for rle images */ - } - RGB_IMAGE; - - RGB_IMAGE *icreate(); - RGB_IMAGE *iopen(char *file, char *mode, unsigned int type, unsigned int dim, - unsigned int xsize, unsigned int ysize, unsigned int zsize); - RGB_IMAGE *fiopen(int f, char *mode, unsigned int type, unsigned int dim, - unsigned int xsize, unsigned int ysize, unsigned int zsize); - long reverse(unsigned long lwrd) ; - void cvtshorts( unsigned short *buffer, long n) ; - void i_seterror(void (*func)(char *)) ; -#undef getpix -#undef putpix - int getpix(RGB_IMAGE *image) ; - unsigned int putpix(RGB_IMAGE *image, unsigned int pix) ; - int img_read(RGB_IMAGE *image, char *buffer, int count) ; - int img_write(RGB_IMAGE *image, char *buffer,int count) ; - int img_badrow(RGB_IMAGE *image, unsigned int y, unsigned int z) ; - unsigned long img_seek(RGB_IMAGE *image, unsigned int y, unsigned int z) ; - long img_getrowsize(RGB_IMAGE *image) ; - void img_setrowsize(RGB_IMAGE *image, long cnt, long y, long z) ; - int img_rle_compact(unsigned short *expbuf, int ibpp, - unsigned short *rlebuf, int obpp, int cnt) ; - void img_rle_expand(unsigned short *rlebuf, int ibpp, - unsigned short *expbuf, int obpp) ; - int putrow(RGB_IMAGE *image, unsigned short *buffer, - unsigned int y, unsigned int z) ; - int getrow(RGB_IMAGE *image, unsigned short *buffer, - unsigned int y, unsigned int z) ; - - /* - * - * ...while iopen and fiopen can take an extended set of parameters, the - * last five are optional, so a more correct prototype would be: - * - * - * RGB_IMAGE *iopen(char *file, char *mode, ...); - * RGB_IMAGE *fiopen(int f, char *mode, ...); - */ - - unsigned short *ibufalloc(RGB_IMAGE *image); - int ifilbuf(RGB_IMAGE *image); - int iflush(RGB_IMAGE *image); - unsigned int iflsbuf(RGB_IMAGE *image, unsigned int c); - void isetname(RGB_IMAGE *image, char *name); - void isetcolormap(RGB_IMAGE *image, int colormap); - - int iclose(RGB_IMAGE *image); - int putrow(RGB_IMAGE *image, unsigned short *buffer,unsigned int y,unsigned int z); - int putrow_uc(RGB_IMAGE *image, unsigned char *buffer, - unsigned int y, unsigned int z) ; - int getrow(RGB_IMAGE *image, unsigned short *buffer,unsigned int y,unsigned int z); - - /* removed at tosa's request - RGB_IMAGE *iopen(); - RGB_IMAGE *icreate(); - - */ - - /* RKT: why is there a second definition here? why hasn't anything - complained before? */ - /* unsigned short *ibufalloc(); */ - -#define IMAGEDEF /* for backwards compatibility */ -#ifdef __cplusplus -} -#endif - -unsigned long img_optseek(RGB_IMAGE *image, unsigned long offset); -int img_write(RGB_IMAGE *image, char *buffer,int count) ; -void cvtimage( long *buffer) ; -void cvtlongs( long *buffer, register long n) ; -void i_errhdlr(char *fmt, int a1, int a2, int a3, int a4) ; -void swapImage(RGB_IMAGE *image) ; - -#ifndef _IOREAD -#define _IOREAD 0001 -#endif -#ifndef _IOWRT -#define _IOWRT 0002 -#endif -#ifndef _IOEOF -#define _IOEOF 0020 -#endif -#ifndef _IOERR -#define _IOERR 0040 -#endif -#ifndef _IORW -#define _IORW 0200 -#endif - -#endif /* !__GL_IMAGE_H__ */ diff --git a/include/rgb_utils.h b/include/rgb_utils.h deleted file mode 100644 index ee2380dc807..00000000000 --- a/include/rgb_utils.h +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @file rgb_utils.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -// -// rgbutils.h -// -#ifndef c_rgbutils_h -#define c_rgbutils_h - -int RGBwrite(IMAGE *I, char *fname, int frame) ; -IMAGE *RGBReadImage(char *fname); -IMAGE *RGBReadHeader(char *fname, IMAGE *); - -#endif diff --git a/include/romp_support.h b/include/romp_support.h index a1083bd4662..4ec78ce724b 100644 --- a/include/romp_support.h +++ b/include/romp_support.h @@ -119,8 +119,8 @@ typedef struct ROMP_pf_static_struct { typedef struct ROMP_pf_stack_struct { struct ROMP_pf_static_struct * staticInfo; - NanosecsTimer beginTime; - Nanosecs watchedThreadBeginCPUTimes[ROMP_maxWatchedThreadNum]; + Timer timer; + long watchedThreadBeginCPUTimes[ROMP_maxWatchedThreadNum]; int gone_parallel; ROMP_level entry_level; } ROMP_pf_stack_struct; @@ -148,7 +148,7 @@ void ROMP_pf_end( // typedef struct ROMP_pflb_stack_struct { ROMP_pf_stack_struct * pf_stack; - NanosecsTimer beginTime; + Timer timer; int tid; } ROMP_pflb_stack_struct; diff --git a/include/runfuncs.h b/include/runfuncs.h deleted file mode 100644 index 1399b1b5782..00000000000 --- a/include/runfuncs.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file runfuncs.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)runfuncs.h 1.1 - 4/4/94 -*/ -/*------------------------------------------------------------------------ - File Name: runfuncs.h - - Author: Bruce Fischl - - Created: Jan. 1993 - - Description: - -------------------------------------------------------------------------*/ -#ifndef RUNFUNCS_H -#define RUNFUNCS_H - -typedef int (*fwd_func)(unsigned char **outPtr) ; -typedef void (*inv_func)(unsigned char **outPtr, unsigned char val) ; - -void runFuncInit(fwd_func *fwd_array, inv_func *inv_array) ; - - -#endif diff --git a/include/sort_definition.h b/include/sort_definition.h index 232307a2ae5..4d115acfe24 100644 --- a/include/sort_definition.h +++ b/include/sort_definition.h @@ -128,7 +128,7 @@ static void SORT_NAME(SORT_ELEMENT* elts, size_t size, bool useThreads) { losIn [nPartitions-1] = 0; sizesIn[nPartitions-1] = size; while (2*nPartitions <= PARTITIONS_CAPACITY) { - int p; + unsigned int p; #pragma omp parallel for schedule(guided) for (p = 0; p < nPartitions; p++) { size_t lo = losIn[p]; @@ -143,7 +143,7 @@ static void SORT_NAME(SORT_ELEMENT* elts, size_t size, bool useThreads) { temp = losIn; losIn = losOut; losOut = temp; temp = sizesIn; sizesIn = sizesOut; sizesOut = temp; } - int p; + unsigned int p; #pragma omp parallel for schedule(guided) for (p = 0; p < nPartitions; p++) { SORT_NAME(&elts[losIn[p]],sizesIn[p], false); diff --git a/include/sse_mathfun.h b/include/sse_mathfun.h deleted file mode 100644 index 5148c2d3c1a..00000000000 --- a/include/sse_mathfun.h +++ /dev/null @@ -1,765 +0,0 @@ -/* SIMD (SSE1+MMX or SSE2) implementation of sin, cos, exp and log - - Inspired by Intel Approximate Math library, and based on the - corresponding algorithms of the cephes math library - - The default is to use the SSE1 version. If you define USE_SSE2 the - the SSE2 intrinsics will be used in place of the MMX intrinsics. Do - not expect any significant performance improvement with SSE2. - - http://gruntthepeon.free.fr/ssemath/ -*/ - -/* Copyright (C) 2007 Julien Pommier - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - (this is the zlib license) -*/ - -//NJS: gcc 3.4 doesnt have _mm_castps_si128(), so USE_SSE2 cannot be defined -//#define USE_SSE2 - -#include - -/* yes I know, the top of this file is quite ugly */ - -#ifdef _MSC_VER /* visual c++ */ -# define ALIGN16_BEG __declspec(align(16)) -# define ALIGN16_END -#else /* gcc or icc */ -# define ALIGN16_BEG -# define ALIGN16_END __attribute__((aligned(16))) -#endif - -/* __m128 is ugly to write */ -typedef __m128 v4sf; // vector of 4 float (sse1) - -#ifdef USE_SSE2 -# include -typedef __m128i v4si; // vector of 4 int (sse2) -#else -typedef __m64 v2si; // vector of 2 int (mmx) -#endif - -/* declare some SSE constants -- why can't I figure a better way to do that? */ -#define _PS_CONST(Name, Val) \ - static const ALIGN16_BEG float _ps_##Name[4] ALIGN16_END = { Val, Val, Val, Val } -#define _PI32_CONST(Name, Val) \ - static const ALIGN16_BEG int _pi32_##Name[4] ALIGN16_END = { Val, Val, Val, Val } -#define _PS_CONST_TYPE(Name, Type, Val) \ - static const ALIGN16_BEG Type _ps_##Name[4] ALIGN16_END = { Val, Val, Val, Val } - -_PS_CONST(1 , 1.0f); -_PS_CONST(0p5, 0.5f); -/* the smallest non denormalized float number */ -_PS_CONST_TYPE(min_norm_pos, int, 0x00800000); -_PS_CONST_TYPE(mant_mask, int, 0x7f800000); -_PS_CONST_TYPE(inv_mant_mask, int, ~0x7f800000); - -_PS_CONST_TYPE(sign_mask, int, 0x80000000); -_PS_CONST_TYPE(inv_sign_mask, int, ~0x80000000); - -_PI32_CONST(1, 1); -_PI32_CONST(inv1, ~1); -_PI32_CONST(2, 2); -_PI32_CONST(4, 4); -_PI32_CONST(0x7f, 0x7f); - -_PS_CONST(cephes_SQRTHF, 0.707106781186547524); -_PS_CONST(cephes_log_p0, 7.0376836292E-2); -_PS_CONST(cephes_log_p1, - 1.1514610310E-1); -_PS_CONST(cephes_log_p2, 1.1676998740E-1); -_PS_CONST(cephes_log_p3, - 1.2420140846E-1); -_PS_CONST(cephes_log_p4, + 1.4249322787E-1); -_PS_CONST(cephes_log_p5, - 1.6668057665E-1); -_PS_CONST(cephes_log_p6, + 2.0000714765E-1); -_PS_CONST(cephes_log_p7, - 2.4999993993E-1); -_PS_CONST(cephes_log_p8, + 3.3333331174E-1); -_PS_CONST(cephes_log_q1, -2.12194440e-4); -_PS_CONST(cephes_log_q2, 0.693359375); - -#if defined (__MINGW32__) - -/* the ugly part below: many versions of gcc used to be completely buggy with respect to some intrinsics - The movehl_ps is fixed in mingw 3.4.5, but I found out that all the _mm_cmp* intrinsics were completely - broken on my mingw gcc 3.4.5 ... - - Note that the bug on _mm_cmp* does occur only at -O0 optimization level -*/ - -inline __m128 my_movehl_ps(__m128 a, const __m128 b) { - asm ( - "movhlps %2,%0\n\t" - : "=x" (a) - : "0" (a), "x"(b) - ); - return a; } -#warning "redefined _mm_movehl_ps (see gcc bug 21179)" -#define _mm_movehl_ps my_movehl_ps - -inline __m128 my_cmplt_ps(__m128 a, const __m128 b) { - asm ( - "cmpltps %2,%0\n\t" - : "=x" (a) - : "0" (a), "x"(b) - ); - return a; - } -inline __m128 my_cmpgt_ps(__m128 a, const __m128 b) { - asm ( - "cmpnleps %2,%0\n\t" - : "=x" (a) - : "0" (a), "x"(b) - ); - return a; -} -inline __m128 my_cmpeq_ps(__m128 a, const __m128 b) { - asm ( - "cmpeqps %2,%0\n\t" - : "=x" (a) - : "0" (a), "x"(b) - ); - return a; -} -#warning "redefined _mm_cmpxx_ps functions..." -#define _mm_cmplt_ps my_cmplt_ps -#define _mm_cmpgt_ps my_cmpgt_ps -#define _mm_cmpeq_ps my_cmpeq_ps -#endif - -#ifndef USE_SSE2 -typedef union xmm_mm_union { - __m128 xmm; - __m64 mm[2]; -} xmm_mm_union; - -#define COPY_XMM_TO_MM(xmm_, mm0_, mm1_) { \ - xmm_mm_union u; u.xmm = xmm_; \ - mm0_ = u.mm[0]; \ - mm1_ = u.mm[1]; \ -} - -#define COPY_MM_TO_XMM(mm0_, mm1_, xmm_) { \ - xmm_mm_union u; u.mm[0]=mm0_; u.mm[1]=mm1_; xmm_ = u.xmm; \ - } - -#endif // USE_SSE2 - -/* natural logarithm computed for 4 simultaneous float - return NaN for x <= 0 -*/ -v4sf log_ps(v4sf x) { -#ifdef USE_SSE2 - v4si emm0; -#else - v2si mm0, mm1; -#endif - v4sf one = *(v4sf*)_ps_1; - - v4sf invalid_mask = _mm_cmple_ps(x, _mm_setzero_ps()); - - x = _mm_max_ps(x, *(v4sf*)_ps_min_norm_pos); /* cut off denormalized stuff */ - -#ifndef USE_SSE2 - /* part 1: x = frexpf(x, &e); */ - COPY_XMM_TO_MM(x, mm0, mm1); - mm0 = _mm_srli_pi32(mm0, 23); - mm1 = _mm_srli_pi32(mm1, 23); -#else - emm0 = _mm_srli_epi32(_mm_castps_si128(x), 23); -#endif - /* keep only the fractional part */ - x = _mm_and_ps(x, *(v4sf*)_ps_inv_mant_mask); - x = _mm_or_ps(x, *(v4sf*)_ps_0p5); - -#ifndef USE_SSE2 - /* now e=mm0:mm1 contain the really base-2 exponent */ - mm0 = _mm_sub_pi32(mm0, *(v2si*)_pi32_0x7f); - mm1 = _mm_sub_pi32(mm1, *(v2si*)_pi32_0x7f); - v4sf e = _mm_cvtpi32x2_ps(mm0, mm1); - _mm_empty(); /* bye bye mmx */ -#else - emm0 = _mm_sub_epi32(emm0, *(v4si*)_pi32_0x7f); - v4sf e = _mm_cvtepi32_ps(emm0); -#endif - - e = _mm_add_ps(e, one); - - /* part2: - if( x < SQRTHF ) { - e -= 1; - x = x + x - 1.0; - } else { x = x - 1.0; } - */ - v4sf mask = _mm_cmplt_ps(x, *(v4sf*)_ps_cephes_SQRTHF); - v4sf tmp = _mm_and_ps(x, mask); - x = _mm_sub_ps(x, one); - e = _mm_sub_ps(e, _mm_and_ps(one, mask)); - x = _mm_add_ps(x, tmp); - - - v4sf z = _mm_mul_ps(x,x); - - v4sf y = *(v4sf*)_ps_cephes_log_p0; - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p1); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p2); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p3); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p4); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p5); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p6); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p7); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_log_p8); - y = _mm_mul_ps(y, x); - - y = _mm_mul_ps(y, z); - - - tmp = _mm_mul_ps(e, *(v4sf*)_ps_cephes_log_q1); - y = _mm_add_ps(y, tmp); - - - tmp = _mm_mul_ps(z, *(v4sf*)_ps_0p5); - y = _mm_sub_ps(y, tmp); - - tmp = _mm_mul_ps(e, *(v4sf*)_ps_cephes_log_q2); - x = _mm_add_ps(x, y); - x = _mm_add_ps(x, tmp); - x = _mm_or_ps(x, invalid_mask); // negative arg will be NAN - return x; -} - -_PS_CONST(exp_hi, 88.3762626647949f); -_PS_CONST(exp_lo, -88.3762626647949f); - -_PS_CONST(cephes_LOG2EF, 1.44269504088896341); -_PS_CONST(cephes_exp_C1, 0.693359375); -_PS_CONST(cephes_exp_C2, -2.12194440e-4); - -_PS_CONST(cephes_exp_p0, 1.9875691500E-4); -_PS_CONST(cephes_exp_p1, 1.3981999507E-3); -_PS_CONST(cephes_exp_p2, 8.3334519073E-3); -_PS_CONST(cephes_exp_p3, 4.1665795894E-2); -_PS_CONST(cephes_exp_p4, 1.6666665459E-1); -_PS_CONST(cephes_exp_p5, 5.0000001201E-1); - -v4sf exp_ps(v4sf x) { - v4sf tmp = _mm_setzero_ps(), fx; -#ifdef USE_SSE2 - v4si emm0; -#else - v2si mm0, mm1; -#endif - v4sf one = *(v4sf*)_ps_1; - - x = _mm_min_ps(x, *(v4sf*)_ps_exp_hi); - x = _mm_max_ps(x, *(v4sf*)_ps_exp_lo); - - /* express exp(x) as exp(g + n*log(2)) */ - fx = _mm_mul_ps(x, *(v4sf*)_ps_cephes_LOG2EF); - fx = _mm_add_ps(fx, *(v4sf*)_ps_0p5); - - /* how to perform a floorf with SSE: just below */ -#ifndef USE_SSE2 - /* step 1 : cast to int */ - tmp = _mm_movehl_ps(tmp, fx); - mm0 = _mm_cvttps_pi32(fx); - mm1 = _mm_cvttps_pi32(tmp); - /* step 2 : cast back to float */ - tmp = _mm_cvtpi32x2_ps(mm0, mm1); -#else - emm0 = _mm_cvttps_epi32(fx); - tmp = _mm_cvtepi32_ps(emm0); -#endif - /* if greater, substract 1 */ - v4sf mask = _mm_cmpgt_ps(tmp, fx); - mask = _mm_and_ps(mask, one); - fx = _mm_sub_ps(tmp, mask); - - tmp = _mm_mul_ps(fx, *(v4sf*)_ps_cephes_exp_C1); - v4sf z = _mm_mul_ps(fx, *(v4sf*)_ps_cephes_exp_C2); - x = _mm_sub_ps(x, tmp); - x = _mm_sub_ps(x, z); - - z = _mm_mul_ps(x,x); - - v4sf y = *(v4sf*)_ps_cephes_exp_p0; - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_exp_p1); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_exp_p2); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_exp_p3); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_exp_p4); - y = _mm_mul_ps(y, x); - y = _mm_add_ps(y, *(v4sf*)_ps_cephes_exp_p5); - y = _mm_mul_ps(y, z); - y = _mm_add_ps(y, x); - y = _mm_add_ps(y, one); - - /* build 2^n */ -#ifndef USE_SSE2 - z = _mm_movehl_ps(z, fx); - mm0 = _mm_cvttps_pi32(fx); - mm1 = _mm_cvttps_pi32(z); - mm0 = _mm_add_pi32(mm0, *(v2si*)_pi32_0x7f); - mm1 = _mm_add_pi32(mm1, *(v2si*)_pi32_0x7f); - mm0 = _mm_slli_pi32(mm0, 23); - mm1 = _mm_slli_pi32(mm1, 23); - - v4sf pow2n; - COPY_MM_TO_XMM(mm0, mm1, pow2n); - _mm_empty(); -#else - emm0 = _mm_cvttps_epi32(fx); - emm0 = _mm_add_epi32(emm0, *(v4si*)_pi32_0x7f); - emm0 = _mm_slli_epi32(emm0, 23); - v4sf pow2n = _mm_castsi128_ps(emm0); -#endif - y = _mm_mul_ps(y, pow2n); - return y; -} - -_PS_CONST(minus_cephes_DP1, -0.78515625); -_PS_CONST(minus_cephes_DP2, -2.4187564849853515625e-4); -_PS_CONST(minus_cephes_DP3, -3.77489497744594108e-8); -_PS_CONST(sincof_p0, -1.9515295891E-4); -_PS_CONST(sincof_p1, 8.3321608736E-3); -_PS_CONST(sincof_p2, -1.6666654611E-1); -_PS_CONST(coscof_p0, 2.443315711809948E-005); -_PS_CONST(coscof_p1, -1.388731625493765E-003); -_PS_CONST(coscof_p2, 4.166664568298827E-002); -_PS_CONST(cephes_FOPI, 1.27323954473516); // 4 / M_PI - - -/* evaluation of 4 sines at onces, using only SSE1+MMX intrinsics so - it runs also on old athlons XPs and the pentium III of your grand - mother. - - The code is the exact rewriting of the cephes sinf function. - Precision is excellent as long as x < 8192 (I did not bother to - take into account the special handling they have for greater values - -- it does not return garbage for arguments over 8192, though, but - the extra precision is missing). - - Note that it is such that sinf((float)M_PI) = 8.74e-8, which is the - surprising but correct result. - - Performance is also surprisingly good, 1.33 times faster than the - macos vsinf SSE2 function, and 1.5 times faster than the - __vrs4_sinf of amd's ACML (which is only available in 64 bits). Not - too bad for an SSE1 function (with no special tuning) ! - However the latter libraries probably have a much better handling of NaN, - Inf, denormalized and other special arguments.. - - On my core 1 duo, the execution of this function takes approximately 95 cycles. - - From what I have observed on the experiments with Intel AMath lib, switching to an - SSE2 version would improve the perf by only 10%. - - Since it is based on SSE intrinsics, it has to be compiled at -O2 to - deliver full speed. -*/ -v4sf sin_ps(v4sf x) { // any x - v4sf xmm1, xmm2 = _mm_setzero_ps(), xmm3, sign_bit, y; - -#ifdef USE_SSE2 - v4si emm0, emm2; -#else - v2si mm0, mm1, mm2, mm3; -#endif - sign_bit = x; - /* take the absolute value */ - x = _mm_and_ps(x, *(v4sf*)_ps_inv_sign_mask); - /* extract the sign bit (upper one) */ - sign_bit = _mm_and_ps(sign_bit, *(v4sf*)_ps_sign_mask); - - /* scale by 4/Pi */ - y = _mm_mul_ps(x, *(v4sf*)_ps_cephes_FOPI); - - //printf("plop:"); print4(y); -#ifdef USE_SSE2 - /* store the integer part of y in mm0 */ - emm2 = _mm_cvttps_epi32(y); - /* j=(j+1) & (~1) (see the cephes sources) */ - emm2 = _mm_add_epi32(emm2, *(v4si*)_pi32_1); - emm2 = _mm_and_si128(emm2, *(v4si*)_pi32_inv1); - y = _mm_cvtepi32_ps(emm2); - /* get the swap sign flag */ - emm0 = _mm_and_si128(emm2, *(v4si*)_pi32_4); - emm0 = _mm_slli_epi32(emm0, 29); - /* get the polynom selection mask - there is one polynom for 0 <= x <= Pi/4 - and another one for Pi/4 - -struct timeb -{ - time_t time; - unsigned short millitm; - short timezone; - short dstflag; -}; - -#if defined(IRIX) -int ftime(struct timeb *t) ; -#endif - -#endif /*!_sys_timeb_h*/ diff --git a/include/thread.h b/include/thread.h deleted file mode 100644 index 7a2f39741d4..00000000000 --- a/include/thread.h +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file thread.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -/* - @(#)thread.h 1.4 - 8/10/95 -*/ -/*------------------------------------------------------------------------ - File Name: thread.h - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: - -------------------------------------------------------------------------*/ -#ifndef THREAD_H -#define THREAD_H - -#include "queue.h" - -#ifdef ANSI -int ThreadResume(int iTid, int iSignal) ; -int ThreadInit(int machine_id, int nthreads, int stacksize, int npriorities) ; -int ThreadEnd(int tid) ; -int ThreadStart(const char *name, void (*func)(int iTid, void *parm), - void *parm,int priority); -int ThreadSuspend(int tid, int iSignal) ; -int ThreadSleep(int tid, long usec) ; -int ThreadSignal(int tid, int signal) ; -int ThreadYield(void) ; -int ThreadEnqueue(int tid, void *msg) ; -void *ThreadDequeue(int mode) ; -int ThreadGetTid(void) ; -int ThreadGetMid(void) ; -int ThreadCheckMailbox(void) ; -void ThreadExit(int status) ; - -#else - -int ThreadInit() ; -int ThreadEnd() ; -int ThreadStart() ; -int ThreadSuspend() ; -int ThreadSleep() ; -int ThreadSignal() ; -int ThreadYield() ; -int ThreadEnqueue() ; -void *ThreadDequeue() ; -int ThreadGetTid() ; -int ThreadGetMid() ; -int ThreadCheckMailbox() ; - -#endif -/* 0 and positive thread id #s are reserved for real threads */ -#define TID_NONE -3 -#define TID_ALL -2 -#define TID_SELF -1 - -#define SIG_ALL 0xffffffff -#define SIG_ANY 0xffffffff -#define SIG_Q_PENDING 0x00000001 - - -#define MIN_PRIORITY 1 -#define SECONDS(sec) ((long)sec * 1000000) -#define MSEC(msec) ((long)msec * 1000) - -#define THREAD_DONE iDone -extern int iDone ; - -#endif diff --git a/include/timer.h b/include/timer.h index f342e348643..fcd75b1ac08 100644 --- a/include/timer.h +++ b/include/timer.h @@ -1,81 +1,41 @@ -/** - * @file timer.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - #ifndef TIMER_H #define TIMER_H -#include "base.h" - -#include - - - -#if defined(__cplusplus) -extern "C" { -#endif +#include +#include +#include -struct timeb *TimerStart(struct timeb *then) ; -int TimerStop(struct timeb *then) ; -typedef struct NanosecsTimer { struct timespec now; } NanosecsTimer; -typedef struct Nanosecs { long ns; } Nanosecs; -void TimerStartNanosecs (NanosecsTimer * now) ; -Nanosecs TimerElapsedNanosecs(NanosecsTimer * then) ; // returns delta in nanosecs +/// \class Timer +/// +/// A simple, high-resolution chronometer. +/// +/// The Timer class can be used to track elapsed time with nanosecond resolution. The timer +/// begins at construction but can be reset with the `reset()` function. -// mach_gettime is a replacement for clock_gettime (not available on osx < 10.12) -#if defined(__APPLE__) && !defined(HAVE_CLOCK_GETTIME) - typedef int clockid_t; - int mach_gettime(clockid_t clk_id, struct timespec *tp); -#endif +class Timer +{ +public: + Timer() : begin(clock::now()) {} -#ifdef Linux -/* don't know why this doesn't work on linux, but.... */ -extern int ftime (struct timeb *__timebuf); -#endif + // retrieves elapsed time + long nanoseconds(); + long milliseconds(); + double seconds(); + double minutes(); + double hours(); -#define TIMER_INTERVAL_BEGIN(NAME) \ - struct timeb NAME; \ - TimerStart(&NAME); - -#define TIMER_INTERVAL_END(NAME) \ - fprintf(stderr, "%s:%d interval took %d msec\n", __FILE__, __LINE__, TimerStop(&NAME)); - + // resets the timer + void reset(); -// Use this string for writing into files etc. which are not compared by the test system. -// -const char* current_date_time_noOverride(); +private: + typedef std::chrono::high_resolution_clock clock; + std::chrono::time_point begin; +}; -// Use this string for writing into files etc. where it might be compared by -// the test system. The string is usually the current date and time but -// can be overridden with a string that can the same across runs. -// -const char* current_date_time(); +#define TIMER_INTERVAL_BEGIN(NAME) Timer NAME; +#define TIMER_INTERVAL_END(NAME) std::cout << __FILE__ << ":" << __LINE__ << " interval took " << NAME.milliseconds() << " msec" << std::endl; -#if defined(__cplusplus) -}; -#endif +std::string currentDateTime(bool allowOverride = true); #endif diff --git a/include/topology/topo_parms.h b/include/topo_parms.h similarity index 100% rename from include/topology/topo_parms.h rename to include/topo_parms.h diff --git a/include/transform.h b/include/transform.h index dde0bd29311..e7163167c54 100644 --- a/include/transform.h +++ b/include/transform.h @@ -26,12 +26,6 @@ #define MGH_TRANSFORM_H #include "matrix.h" - -#if defined(__cplusplus) -extern "C" { -#endif - - #include "const.h" #include "float.h" @@ -64,7 +58,7 @@ typedef struct MATRIX *m_L ; /* transform matrix */ MATRIX *m_dL ; /* gradient of fuctional wrt transform matrix */ MATRIX *m_last_dL ; /* last time step for momentum */ - TransformType type; /* record transform type */ + int type; /* record transform type */ VOL_GEOM src; /* src for the transform */ VOL_GEOM dst; /* dst for the transform */ int label ; // if this xform only applies to a specific label @@ -285,10 +279,4 @@ int LTAmriIsTarget(const LTA *lta, const MRI *mri); LTA *LTAcreate(MRI *src, MRI *dst, MATRIX *T, int type); double RMSregDiffMJ(MATRIX *T1, MATRIX *T2, double radius); -#if defined(__cplusplus) -}; -#endif - - - #endif diff --git a/include/trig512.h b/include/trig512.h deleted file mode 100644 index ff435ef1c3e..00000000000 --- a/include/trig512.h +++ /dev/null @@ -1,544 +0,0 @@ -/** - * @file trig512.h - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#define PI ((double)3.14159265358979324) -#define COS(index) (_cosine[(index) & 511]) -#define SIN(index) (_cosine[((index)+128) & 511]) -#define TAN(index) (SIN(index)/COS(index)) -double _cosine[512] = { - 1.00000000000000000, - 0.99992470183914454, - 0.99969881869620422, - 0.99932238458834950, - 0.99879545620517239, - 0.99811811290014921, - 0.99729045667869022, - 0.99631261218277802, - 0.99518472667219689, - 0.99390697000235605, - 0.99247953459870999, - 0.99090263542778002, - 0.98917650996478097, - 0.98730141815785838, - 0.98527764238894125, - 0.98310548743121633, - 0.98078528040323044, - 0.97831737071962763, - 0.97570213003852854, - 0.97293995220556015, - 0.97003125319454399, - 0.96697647104485211, - 0.96377606579543987, - 0.96043051941556581, - 0.95694033573220887, - 0.95330604035419383, - 0.94952818059303666, - 0.94560732538052132, - 0.94154406518302078, - 0.93733901191257492, - 0.93299279883473889, - 0.92850608047321556, - 0.92387953251128675, - 0.91911385169005774, - 0.91420975570353065, - 0.90916798309052238, - 0.90398929312344334, - 0.89867446569395384, - 0.89322430119551532, - 0.88763962040285395, - 0.88192126434835504, - 0.87607009419540662, - 0.87008699110871142, - 0.86397285612158674, - 0.85772861000027208, - 0.85135519310526514, - 0.84485356524970708, - 0.83822470555483805, - 0.83146961230254524, - 0.82458930278502526, - 0.81758481315158370, - 0.81045719825259480, - 0.80320753148064492, - 0.79583690460888354, - 0.78834642762660626, - 0.78073722857209447, - 0.77301045336273697, - 0.76516726562245893, - 0.75720884650648455, - 0.74913639452345933, - 0.74095112535495909, - 0.73265427167241284, - 0.72424708295146692, - 0.71573082528381865, - 0.70710678118654753, - 0.69837624940897286, - 0.68954054473706693, - 0.68060099779545305, - 0.67155895484701840, - 0.66241577759017177, - 0.65317284295377677, - 0.64383154288979147, - 0.63439328416364550, - 0.62485948814238639, - 0.61523159058062685, - 0.60551104140432552, - 0.59569930449243336, - 0.58579785745643886, - 0.57580819141784531, - 0.56573181078361320, - 0.55557023301960222, - 0.54532498842204642, - 0.53499761988709722, - 0.52458968267846891, - 0.51410274419322173, - 0.50353838372571756, - 0.49289819222978405, - 0.48218377207912275, - 0.47139673682599766, - 0.46053871095824003, - 0.44961132965460662, - 0.43861623853852764, - 0.42755509343028211, - 0.41642956009763719, - 0.40524131400498989, - 0.39399204006104811, - 0.38268343236508976, - 0.37131719395183755, - 0.35989503653498814, - 0.34841868024943457, - 0.33688985339222004, - 0.32531029216226294, - 0.31368174039889147, - 0.30200594931922808, - 0.29028467725446236, - 0.27851968938505312, - 0.26671275747489838, - 0.25486565960451458, - 0.24298017990326388, - 0.23105810828067113, - 0.21910124015686979, - 0.20711137619221856, - 0.19509032201612827, - 0.18303988795514097, - 0.17096188876030122, - 0.15885814333386146, - 0.14673047445536175, - 0.13458070850712620, - 0.12241067519921620, - 0.11022220729388307, - 0.09801714032956060, - 0.08579731234443991, - 0.07356456359966743, - 0.06132073630220859, - 0.04906767432741802, - 0.03680722294135885, - 0.02454122852291229, - 0.01227153828571995, - 0.00000000000000001, - -0.01227153828571993, - -0.02454122852291228, - -0.03680722294135884, - -0.04906767432741801, - -0.06132073630220858, - -0.07356456359966741, - -0.08579731234443990, - -0.09801714032956059, - -0.11022220729388306, - -0.12241067519921619, - -0.13458070850712619, - -0.14673047445536174, - -0.15885814333386144, - -0.17096188876030121, - -0.18303988795514096, - -0.19509032201612826, - -0.20711137619221855, - -0.21910124015686978, - -0.23105810828067112, - -0.24298017990326387, - -0.25486565960451457, - -0.26671275747489837, - -0.27851968938505310, - -0.29028467725446235, - -0.30200594931922806, - -0.31368174039889146, - -0.32531029216226293, - -0.33688985339222003, - -0.34841868024943456, - -0.35989503653498813, - -0.37131719395183754, - -0.38268343236508977, - -0.39399204006104810, - -0.40524131400498987, - -0.41642956009763720, - -0.42755509343028207, - -0.43861623853852763, - -0.44961132965460660, - -0.46053871095824004, - -0.47139673682599763, - -0.48218377207912274, - -0.49289819222978404, - -0.50353838372571758, - -0.51410274419322170, - -0.52458968267846889, - -0.53499761988709721, - -0.54532498842204644, - -0.55557023301960221, - -0.56573181078361319, - -0.57580819141784530, - -0.58579785745643886, - -0.59569930449243332, - -0.60551104140432550, - -0.61523159058062685, - -0.62485948814238639, - -0.63439328416364547, - -0.64383154288979146, - -0.65317284295377676, - -0.66241577759017177, - -0.67155895484701837, - -0.68060099779545304, - -0.68954054473706693, - -0.69837624940897286, - -0.70710678118654754, - -0.71573082528381864, - -0.72424708295146691, - -0.73265427167241284, - -0.74095112535495911, - -0.74913639452345931, - -0.75720884650648454, - -0.76516726562245893, - -0.77301045336273697, - -0.78073722857209446, - -0.78834642762660626, - -0.79583690460888354, - -0.80320753148064492, - -0.81045719825259477, - -0.81758481315158368, - -0.82458930278502526, - -0.83146961230254524, - -0.83822470555483802, - -0.84485356524970706, - -0.85135519310526514, - -0.85772861000027208, - -0.86397285612158672, - -0.87008699110871141, - -0.87607009419540660, - -0.88192126434835504, - -0.88763962040285393, - -0.89322430119551531, - -0.89867446569395384, - -0.90398929312344334, - -0.90916798309052237, - -0.91420975570353065, - -0.91911385169005774, - -0.92387953251128677, - -0.92850608047321558, - -0.93299279883473887, - -0.93733901191257492, - -0.94154406518302078, - -0.94560732538052134, - -0.94952818059303666, - -0.95330604035419383, - -0.95694033573220887, - -0.96043051941556581, - -0.96377606579543985, - -0.96697647104485211, - -0.97003125319454399, - -0.97293995220556015, - -0.97570213003852854, - -0.97831737071962763, - -0.98078528040323044, - -0.98310548743121633, - -0.98527764238894124, - -0.98730141815785838, - -0.98917650996478097, - -0.99090263542778002, - -0.99247953459870999, - -0.99390697000235603, - -0.99518472667219689, - -0.99631261218277802, - -0.99729045667869021, - -0.99811811290014921, - -0.99879545620517239, - -0.99932238458834950, - -0.99969881869620422, - -0.99992470183914454, - -1.00000000000000000, - -0.99992470183914454, - -0.99969881869620422, - -0.99932238458834950, - -0.99879545620517239, - -0.99811811290014921, - -0.99729045667869022, - -0.99631261218277802, - -0.99518472667219689, - -0.99390697000235605, - -0.99247953459870999, - -0.99090263542778002, - -0.98917650996478097, - -0.98730141815785838, - -0.98527764238894125, - -0.98310548743121633, - -0.98078528040323046, - -0.97831737071962764, - -0.97570213003852854, - -0.97293995220556015, - -0.97003125319454400, - -0.96697647104485211, - -0.96377606579543987, - -0.96043051941556583, - -0.95694033573220887, - -0.95330604035419383, - -0.94952818059303666, - -0.94560732538052134, - -0.94154406518302079, - -0.93733901191257493, - -0.93299279883473889, - -0.92850608047321558, - -0.92387953251128677, - -0.91911385169005776, - -0.91420975570353065, - -0.90916798309052237, - -0.90398929312344335, - -0.89867446569395384, - -0.89322430119551532, - -0.88763962040285395, - -0.88192126434835505, - -0.87607009419540662, - -0.87008699110871142, - -0.86397285612158674, - -0.85772861000027209, - -0.85135519310526515, - -0.84485356524970708, - -0.83822470555483804, - -0.83146961230254525, - -0.82458930278502528, - -0.81758481315158370, - -0.81045719825259478, - -0.80320753148064493, - -0.79583690460888355, - -0.78834642762660627, - -0.78073722857209447, - -0.77301045336273698, - -0.76516726562245894, - -0.75720884650648455, - -0.74913639452345933, - -0.74095112535495912, - -0.73265427167241286, - -0.72424708295146693, - -0.71573082528381865, - -0.70710678118654752, - -0.69837624940897287, - -0.68954054473706694, - -0.68060099779545305, - -0.67155895484701839, - -0.66241577759017178, - -0.65317284295377674, - -0.64383154288979147, - -0.63439328416364553, - -0.62485948814238636, - -0.61523159058062686, - -0.60551104140432556, - -0.59569930449243334, - -0.58579785745643889, - -0.57580819141784527, - -0.56573181078361320, - -0.55557023301960226, - -0.54532498842204641, - -0.53499761988709724, - -0.52458968267846896, - -0.51410274419322172, - -0.50353838372571759, - -0.49289819222978401, - -0.48218377207912276, - -0.47139673682599770, - -0.46053871095824001, - -0.44961132965460662, - -0.43861623853852770, - -0.42755509343028209, - -0.41642956009763722, - -0.40524131400498985, - -0.39399204006104812, - -0.38268343236508982, - -0.37131719395183754, - -0.35989503653498818, - -0.34841868024943453, - -0.33688985339222005, - -0.32531029216226297, - -0.31368174039889146, - -0.30200594931922808, - -0.29028467725446243, - -0.27851968938505309, - -0.26671275747489842, - -0.25486565960451454, - -0.24298017990326390, - -0.23105810828067117, - -0.21910124015686978, - -0.20711137619221857, - -0.19509032201612833, - -0.18303988795514095, - -0.17096188876030127, - -0.15885814333386141, - -0.14673047445536176, - -0.13458070850712624, - -0.12241067519921618, - -0.11022220729388309, - -0.09801714032956067, - -0.08579731234443989, - -0.07356456359966747, - -0.06132073630220855, - -0.04906767432741803, - -0.03680722294135889, - -0.02454122852291228, - -0.01227153828571996, - 0.00000000000000004, - 0.01227153828571992, - 0.02454122852291224, - 0.03680722294135886, - 0.04906767432741799, - 0.06132073630220852, - 0.07356456359966743, - 0.08579731234443986, - 0.09801714032956064, - 0.11022220729388305, - 0.12241067519921615, - 0.13458070850712621, - 0.14673047445536173, - 0.15885814333386138, - 0.17096188876030123, - 0.18303988795514092, - 0.19509032201612830, - 0.20711137619221854, - 0.21910124015686975, - 0.23105810828067113, - 0.24298017990326386, - 0.25486565960451450, - 0.26671275747489839, - 0.27851968938505307, - 0.29028467725446239, - 0.30200594931922805, - 0.31368174039889142, - 0.32531029216226295, - 0.33688985339222002, - 0.34841868024943450, - 0.35989503653498815, - 0.37131719395183750, - 0.38268343236508980, - 0.39399204006104809, - 0.40524131400498981, - 0.41642956009763719, - 0.42755509343028206, - 0.43861623853852767, - 0.44961132965460660, - 0.46053871095823998, - 0.47139673682599766, - 0.48218377207912273, - 0.49289819222978398, - 0.50353838372571756, - 0.51410274419322169, - 0.52458968267846894, - 0.53499761988709719, - 0.54532498842204638, - 0.55557023301960223, - 0.56573181078361318, - 0.57580819141784524, - 0.58579785745643886, - 0.59569930449243332, - 0.60551104140432553, - 0.61523159058062683, - 0.62485948814238633, - 0.63439328416364550, - 0.64383154288979144, - 0.65317284295377671, - 0.66241577759017176, - 0.67155895484701837, - 0.68060099779545306, - 0.68954054473706691, - 0.69837624940897280, - 0.70710678118654753, - 0.71573082528381862, - 0.72424708295146695, - 0.73265427167241283, - 0.74095112535495906, - 0.74913639452345934, - 0.75720884650648453, - 0.76516726562245889, - 0.77301045336273697, - 0.78073722857209446, - 0.78834642762660628, - 0.79583690460888352, - 0.80320753148064487, - 0.81045719825259480, - 0.81758481315158368, - 0.82458930278502522, - 0.83146961230254524, - 0.83822470555483802, - 0.84485356524970709, - 0.85135519310526514, - 0.85772861000027203, - 0.86397285612158674, - 0.87008699110871141, - 0.87607009419540657, - 0.88192126434835502, - 0.88763962040285392, - 0.89322430119551532, - 0.89867446569395383, - 0.90398929312344331, - 0.90916798309052238, - 0.91420975570353064, - 0.91911385169005771, - 0.92387953251128675, - 0.92850608047321555, - 0.93299279883473890, - 0.93733901191257492, - 0.94154406518302075, - 0.94560732538052132, - 0.94952818059303666, - 0.95330604035419385, - 0.95694033573220887, - 0.96043051941556580, - 0.96377606579543987, - 0.96697647104485210, - 0.97003125319454397, - 0.97293995220556015, - 0.97570213003852854, - 0.97831737071962764, - 0.98078528040323044, - 0.98310548743121631, - 0.98527764238894125, - 0.98730141815785838, - 0.98917650996478096, - 0.99090263542778002, - 0.99247953459870999, - 0.99390697000235605, - 0.99518472667219689, - 0.99631261218277800, - 0.99729045667869022, - 0.99811811290014921, - 0.99879545620517239, - 0.99932238458834950, - 0.99969881869620422, - 0.99992470183914454 - }; diff --git a/include/utils.h b/include/utils.h index affb846476e..34354eae4a0 100644 --- a/include/utils.h +++ b/include/utils.h @@ -26,13 +26,9 @@ #ifndef UTILS_H #define UTILS_H -#if defined(__cplusplus) -extern "C" { -#endif #include "base.h" - #define MATLAB_FILE 0 #define HIPS_FILE 1 #define LIST_FILE 2 @@ -83,8 +79,7 @@ int FileNumber(const char *fname) ; int FileNumberOfEntries(const char *fname) ; char *FileName(char *full_name) ; char *FileFullName(char *full_name) ; -char *FileTmpName(char *base) ; -char *FileTmpName(char *basename) ; +char *FileTmpName(const char *basename) ; void FileRename(const char *inName,const char *outName) ; char *FileNameAbsolute(const char *fname, char *absFname) ; char *FileNamePath(const char *fname, char *pathName) ; @@ -139,15 +134,10 @@ extern int global_progress_range[2]; void SetProgressCallback(void (*callback)(int), int start, int end); void exec_progress_callback(int slice, int total_slices, int frame, int total_frames); - int *compute_permutation(int num, int *vec) ; int *GetMemUsage(int *u); int PrintMemUsage(FILE *fp); int PrintRUsage(int who, const char *pre, FILE *fp); int WriteRUsage(int who, const char *pre, char *fname); -#if defined(__cplusplus) -}; -#endif - #endif diff --git a/include/utilsmath.h b/include/utilsmath.h index 0c2bb499592..0ae1b60af59 100644 --- a/include/utilsmath.h +++ b/include/utilsmath.h @@ -22,25 +22,11 @@ #ifndef utilsmath_h #define utilsmath_h -// The following is usable from C -#ifdef __cplusplus -extern "C" -{ -#endif - #include "mri.h" #include "mrisurf.h" #include "diag.h" #include "proto.h" -#ifdef __cplusplus -} -#endif - - -// C++ portion starts here -#ifdef __cplusplus - #include #include #include @@ -697,5 +683,4 @@ namespace Math } -#endif //cplusplus #endif //utilsmath_h diff --git a/include/version.h b/include/version.h index fc030bc8232..e887a4db8b2 100644 --- a/include/version.h +++ b/include/version.h @@ -30,10 +30,6 @@ #ifndef VERSION_H #define VERSION_H -#if defined(__cplusplus) -extern "C" { -#endif - /* This function looks for the --version, or -version tag in the argv and if found, prints out version information. This can be used in any binary. It will return the number of options processed and @@ -69,17 +65,11 @@ extern "C" { */ -int handle_version_option (int argc, char** argv, - const char* id_string, const char* version_string); -int make_cmd_version_string (int argc, char** argv, const char* id_string, - const char* version_string, char *return_string) ; +int handle_version_option(int argc, char** argv, const char* id_string, const char* version_string); +int make_cmd_version_string(int argc, char** argv, const char* id_string, const char* version_string, char *return_string); char *argv2cmdline(int argc, char *argv[]); char *VERuser(void); char *VERfileTimeStamp(char *fname); char *VERcurTimeStamp(void); -#if defined(__cplusplus) -}; -#endif - #endif diff --git a/include/voxlist.h b/include/voxlist.h index 5ae2bc88fb0..539731892c0 100644 --- a/include/voxlist.h +++ b/include/voxlist.h @@ -30,11 +30,6 @@ #include "mri.h" #include "label.h" -#if defined(__cplusplus) -extern "C" { -#endif - - #define VOXLIST_NORMAL 0 #define VOXLIST_SPLINE 1 @@ -123,9 +118,4 @@ float VLSTcomputeSplineMedian(VOXEL_LIST *vl_spline, MRI *mri, double step_size) double VLSThausdorffDistance(VOXEL_LIST *vl1, VOXEL_LIST *vl2, double max_dist, MRI **pmri_dist) ; double VLSTrmsDistance(VOXEL_LIST *vl1, VOXEL_LIST *vl2, double max_dist, MRI **pmri_dist) ; -#if defined(__cplusplus) -}; -#endif - - #endif diff --git a/include/x3DList.h b/include/x3DList.h deleted file mode 100644 index 257d0b3ef8f..00000000000 --- a/include/x3DList.h +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @file x3DList.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef x3DList_H -#define x3DList_H - -#include "xTypes.h" -#include "xList.h" -#include "xVoxel.h" - -typedef enum -{ - x3Lst_tPlane_X = 0, - x3Lst_tPlane_Y, - x3Lst_tPlane_Z, - x3Lst_knNumPlanes -} x3Lst_tPlane; - - -typedef struct -{ - - tSignature mSignature; - - int mnPlaneSize; - xListRef* mPlane[ x3Lst_knNumPlanes ]; - -} -x3DList, *x3DListRef; - -#define x3Lst_kSignature 0x780123bc - -typedef enum -{ - x3Lst_tErr_NoErr = 0, - x3Lst_tErr_InvalidPtr, - x3Lst_tErr_InvalidSignature, - x3Lst_tErr_ErrorAccessingList, - x3Lst_tErr_ItemNotInSpace, - x3Lst_tErr_InvalidSpace, - x3Lst_tErr_InvalidLocation, - x3Lst_tErr_InvalidPlaneNumber, - x3Lst_tErr_CouldntAllocateSpace, - x3Lst_tErr_CouldntAllocateList, - x3Lst_tErr_InvalidErrorCode, - x3Lst_knNumErrorCodes -} x3Lst_tErr; - -/* allocate and init the space */ -x3Lst_tErr x3Lst_New ( x3DListRef* op3DList, - int inListSize ); - -/* delete the space */ -x3Lst_tErr x3Lst_Delete ( x3DListRef* iop3DList ); - -x3Lst_tErr x3Lst_GetPlaneSize ( x3DListRef this, - int* onPlaneSize ); - -/* add an item to the space */ -x3Lst_tErr x3Lst_AddItem ( x3DListRef this, - xVoxelRef iWhere, - void* ipItem ); - -/* remove an item from the space */ -x3Lst_tErr x3Lst_RemoveItem ( x3DListRef this, - xVoxelRef iWhere, - void** iopItem ); - -/* clears all the items in the -space. */ -x3Lst_tErr x3Lst_Clear ( x3DListRef this ); - -/* determine whether or not an item - is in the space */ -x3Lst_tErr x3Lst_IsInList ( x3DListRef this, - void* ipData, - tBoolean* outIsInList ); - -/* return a pointer to a list of - items in a particular plane. */ -x3Lst_tErr x3Lst_GetItemsInXPlane ( x3DListRef this, - int inXPlane, - xListRef* opList ); -x3Lst_tErr x3Lst_GetItemsInYPlane ( x3DListRef this, - int inYPlane, - xListRef* opList ); -x3Lst_tErr x3Lst_GetItemsInZPlane ( x3DListRef this, - int inZPlane, - xListRef* opList ); -x3Lst_tErr x3Lst_GetItemsInPlane_ ( x3DListRef this, - x3Lst_tPlane iPlane, - int inPlaneIndex, - xListRef* opList ); - -x3Lst_tErr x3Lst_SetComparator ( x3DListRef this, - xList_tCompare(*iComparator)(void*,void*) ); - -x3Lst_tErr x3Lst_Verify ( x3DListRef this ); -x3Lst_tErr x3Lst_VerifyLocation ( x3DListRef this, - xVoxelRef iWhere ); - -char* x3Lst_GetErrorString ( x3Lst_tErr ieCode ); - - -#endif diff --git a/include/xDebug.h b/include/xDebug.h index 5e189bbd0ef..e9eff979f61 100644 --- a/include/xDebug.h +++ b/include/xDebug.h @@ -45,7 +45,7 @@ void xDbg_PrintStatus (); void xDbg_RegisterSegfaultHandler ( void(*f)(int) ); void xDbg_PushStack ( char* isTitle, char* isNote ); void xDbg_PopStack (); -char* xDbg_GetCurrentFunction (); +const char* xDbg_GetCurrentFunction (); void xDbg_PrintStack (); void xDbg_SegfaultHandler ( int ); void xDbg_Segfault (); diff --git a/include/xGLutWindow.h b/include/xGLutWindow.h deleted file mode 100644 index f83591bd289..00000000000 --- a/include/xGLutWindow.h +++ /dev/null @@ -1,209 +0,0 @@ -/** - * @file xGLutWindow.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.11 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef xGLutWindow_h -#define xGLutWindow_h - -#include -#include "xTypes.h" - -typedef enum -{ - - xGWin_tErr_NoErr = 0, - xGWin_tErr_InvalidWindowPtr, - xGWin_tErr_InvalidWindowSignature, - xGWin_tErr_AllocationFailed, - xGWin_tErr_InvalidParameter, - xGWin_tErr_InvalidErrorCode, - xGWin_knNumErrorCodes - -} xGWin_tErr; - -/* the event class */ -typedef enum -{ - - xGWin_tEventType_NoEvent = 0, - xGWin_tEventType_KeyDown, - xGWin_tEventType_MouseDown, - xGWin_tEventType_MouseUp, - xGWin_tEventType_MouseMoved, - xGWin_tEventType_Resize, - xGWin_tEventType_Draw, - xGWin_tEventType_Idle, - xGWin_NumEventTypes - -} xGWin_tEventType; - -typedef int xGWin_tButton; -typedef unsigned char xGWin_tKey; - -/* special keys */ -enum -{ - - xGWin_tKey_Tab = 9, /* 9 myst remain hardcoded */ - xGWin_tKey_UpArrow = 10, - xGWin_tKey_DownArrow, - xGWin_tKey_LeftArrow, - xGWin_tKey_RightArrow, - xGWin_tKey_PageUp, - xGWin_tKey_PageDown, - xGWin_tKey_End, - xGWin_tKey_Insert, - xGWin_tKey_Home -}; - -#define xGWin_knCtrlA 1 -#define xGWin_knCtrl0 48 -#define xGWin_knCtrl1 49 -#define xGWin_knCtrl2 0 -#define xGWin_knCtrl3 27 -#define xGWin_knCtrl4 28 -#define xGWin_knCtrl5 29 -#define xGWin_knCtrl6 30 -#define xGWin_knCtrl7 31 -#define xGWin_knCtrl8 127 -#define xGWin_knCtrl9 57 - -typedef struct -{ - - xGWin_tEventType mType; // type of event that occured. - xPoint2n mWhere; // where mouse was (or what window resized to) - xGWin_tButton mButton; // which button (1,2,3) - xGWin_tKey mKey; // what key (a letter or a special enum) - tBoolean mbCtrlKey; // ctrl key was down? - tBoolean mbAltKey; // alt key was down? - tBoolean mbShiftKey; // shift key was down? - -} -xGWin_tEvent, *xGWin_tEventRef; - -/* create and destroy events */ -void xGWin_NewEvent ( xGWin_tEventRef* oppEvent ); -void xGWin_DeleteEvent ( xGWin_tEventRef* ioppEvent ); - -/* print event data */ -void xGWin_DebugPrintEvent ( xGWin_tEventRef this ); - -/* event handle function signature */ -typedef void(*xGWin_tEventHandlerFunc) ( void* ipData, xGWin_tEventRef ); -typedef void(*xGWin_tIdleFunc) ( void ); - -#define xGWin_kSignature 0x1234ABCD - -/* window class */ -typedef struct -{ - - tSignature mSignature; - int mnGLutWindowID; // openGL window id - xGWin_tEventHandlerFunc mpHandlerFunc; // subclass event handler - void* mpHandlerFuncData; // ptr to subclass data -} -xGLutWindow, *xGLutWindowRef; - -/* creates and deletes windows. */ -xGWin_tErr xGWin_New ( xGLutWindowRef* oppWindow, - int inWidth, - int inHeight, - char* isTitle ); -xGWin_tErr xGWin_Delete ( xGLutWindowRef* ioppWindow ); - -/* sets the window title */ -xGWin_tErr xGWin_SetWindowTitle ( xGLutWindowRef ipWindow, - char* isTitle ); - -/* set the event handler for this window. when an event is received, - calls ipFunc( ipData ). */ -xGWin_tErr xGWin_SetEventHandlerFunc ( xGLutWindowRef this, - xGWin_tEventHandlerFunc ipFunc, - void* ipData ); - -/* activate idle events for this window */ -xGWin_tErr xGWin_ActivateIdleEvents ( xGLutWindowRef this ); - -/* activate passive motion events for this window */ -xGWin_tErr xGWin_ActivatePassiveMotionEvents ( xGLutWindowRef this ); - - -xGWin_tErr xGWin_Verify ( xGLutWindowRef this ); - -char* xGWin_GetErrorString ( xGWin_tErr ); - - -/* since glut doesn't provide us a way to attach a ptr to a glut window, - we have to make a lookup list of gl id numbers and window ptrs, so when - we get an event, we figure out the current window, look up its ptr, - and pass the event to the right window. */ - -#define xGWin_knMaxNumWindows 200 - -/* this adds an id and window to the list. it will also init the list if - it hasn't been done yet. */ -void xGWin_AddWindowIDToLookupList ( int inWindowID, - xGLutWindowRef ipWindow ); - -/* this gets a window ptr from an id. returns null if it can't find the - the id. */ -void xGWin_GetWindowFromID ( int inWindowID, - xGLutWindowRef* oppWindow ); - -/* removes a window from the list. does nothing if it can't find the id. */ -void xGWin_RemoveWindowIDFromLookupList ( int inWindowID ); - -/* passes an event to a window. */ -void xGWin_PassEventToCurrentWindow ( xGWin_tEventRef ipEvent ); -void xGWin_PassEventToAllWindows ( xGWin_tEventRef ipEvent ); - -/* these are the callbacks we register with glut. since glut's event system - is pretty barebones, and each callback has a different signature, we - stuff each event into a custom structure and pass it to a single event - handler on the window side. */ -void xGWin_GLutKeyboardCallback ( unsigned char icKey, - int inX, - int inY ); -void xGWin_GLutSpecialCallback ( int inKey, - int inX, - int inY ); -void xGWin_GLutMouseCallback ( int inButton, - int inState, - int inX, - int inY ); -void xGWin_GLutMotionCallback ( int inX, - int inY ); -void xGWin_GLutPassiveMotionCallback ( int inX, - int inY ); -void xGWin_GLutResizeCallback ( int inWidth, - int inHeight ); -void xGWin_GLutDrawCallback (); -void xGWin_GLutIdleCallback (); - -/* posts a redisplay for all windows. note that the redisplays go into the - normal glut event queue. */ -void xGWin_RedrawAllWindows (); - -#endif diff --git a/include/xGrowableArray.h b/include/xGrowableArray.h deleted file mode 100644 index b53643e649b..00000000000 --- a/include/xGrowableArray.h +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @file xGrowableArray.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef xGrowableArray_h -#define xGrowableArray_h - -typedef enum -{ - - xGArr_tErr_NoErr, - xGArr_tErr_InvalidObject, - xGArr_tErr_InvalidSignature, - xGArr_tErr_AllocationFailed, - xGArr_tErr_LastItem, - xGArr_tErr_InvalidErrorCode, - xGArr_knNumErrorCodes -} xGArr_tErr; - -#define xGArr_kSignature 0x8765433 - -typedef struct -{ - - long mSignature; - - /* storage */ - int mnNumItems; - int mnMaxNumItems; - int mnItemSizeBytes; - int mnMaxSizeBytes; - void* mpData; - - /* iterator */ - int mnNext; - -} -xGrowableArray, *xGrowableArrayRef; - -xGArr_tErr xGArr_New ( xGrowableArrayRef* opList, - int inSize, - int inNumItems ); -xGArr_tErr xGArr_Delete ( xGrowableArrayRef* iopList ); - -xGArr_tErr xGArr_Add ( xGrowableArrayRef this, - void* ipSrc ); - -xGArr_tErr xGArr_ResetIterator ( xGrowableArrayRef this ); -xGArr_tErr xGArr_NextItem ( xGrowableArrayRef this, - void* opDest ); - -xGArr_tErr xGArr_Clear ( xGrowableArrayRef this ); - -xGArr_tErr xGArr_Verify ( xGrowableArrayRef this ); -char* xGArr_GetErrorString ( xGArr_tErr ieCode ); - -#endif diff --git a/include/xList.h b/include/xList.h deleted file mode 100644 index feef4ad6a86..00000000000 --- a/include/xList.h +++ /dev/null @@ -1,290 +0,0 @@ -/** - * @file xList.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.7 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef xList_H -#define xList_H - -#include "xTypes.h" - -/* various error codes that will be -returned by all functions. these can be -translated into human readable strings -with the GetErrorString func below. note -that some of these code are not -necessarily errors. if you ask for the -next item and get a EndOfList error, it -just means you're at the end of the -list. */ -typedef enum -{ - - xList_tErr_NoErr = 0, // no error - xList_tErr_AllocationFailed, // local memory allocation failed - xList_tErr_InternalAllocationFailed, // rts list new failed - xList_tErr_InternalDeletionFailed, // rts list delete failed - xList_tErr_DeletionFailed, // local delete failed - xList_tErr_InvalidListRef, // null list arg ptr - xList_tErr_ListFull, // couldn't insert item - xList_tErr_ItemNotInList, // item not found - xList_tErr_ErrorFindingItem, // couldn't look for item - xList_tErr_ErrorGettingSize, // couldn't get size - xList_tErr_EndOfList, // end of list - xList_tErr_ListEmpty, // list is empty - xList_tErr_InvalidErrorCode, - xList_knNumErrorCodes - -} xList_tErr; - -typedef enum -{ - - xList_tCompare_LessThan = -1, - xList_tCompare_Match = 0, - xList_tCompare_GreaterThan = 1 -} xList_tCompare; - - -/* we use a signature to detect corrupted -memory or multiple deletes on the same -ptr. */ -#define xList_kSignature 0x8f7f6f5c - -/* private list node struct. */ -typedef struct -{ - - long mSignature; // the signature - void* mpData; // pointer to the data in the list - void* mpNext; // ptr to the next node -} -xListNode, *xListNodeRef; - -/* private list struct. */ -typedef struct -{ - - long mSignature; // the signature - xListNodeRef mpHead; // first node - xListNodeRef mpTail; // last node - xListNodeRef mpNext; // the next node in a traversal - - xList_tCompare(*mComparator)(void*,void*); - -} -xList, *xListRef; - -/* public interface */ - -/* desc: -call to create a new list. pass in -an uninited xListRef and get back an -inited list. allocated a single node. -* returns: -AllocationFailed: couldn't allocate -necessary memory. oppList will be nil. -*/ -xList_tErr xList_New ( xListRef* oppList ); - -/* desc: -deletes the list. note that this will -leave orphaned ptrs. -* returns: -InvalidListRef: null list ptr or bad -signature. -*/ -xList_tErr xList_Delete ( xListRef* ioppList ); - -/* desc: -inserts an item onto the tail of the -list. -* returns: -InvalidListRef: null list ptr or bad -signature. -*/ -xList_tErr xList_InsertItem ( xListRef this, - void* ipItemToInsert ); - -/* desc: -removes an item from the list. note -that if a comparator is defined, the -ptr that is passed in may not be the -same as the ptr in the list; both can -point to different pieces of memory. -since the one in the list needs to be -removed, it will be returned in the -item paramter. it should then be -deleted. -* returns: -InvalidListRef: null list ptr or bad -signature. -InternalAllocationFailed: couldn't -allocate node. -*/ -xList_tErr xList_RemoveItem ( xListRef this, - void** iopItemToRemove ); - -/* desc: -searches list for item, returns true if -found. -* returns: -InvalidListRef: null list ptr or bad -signature. -ItemNotInList: couldn't find -ipItemToRemove. -*/ -xList_tErr xList_IsInList ( xListRef this, - void* ipItem, - tBoolean* obpIsInList ); - -/* desc: -empties the list. only deletes nodes, -not the data they're pointing to. -* returns: -InvalidListRef: null list ptr or bad -signature. -*/ -xList_tErr xList_Clear ( xListRef this ); - -/* desc: -returns the number of items in the -list. -* returns: -InvalidListRef: null list ptr or bad -signature for list or node. -*/ -xList_tErr xList_GetCount ( xListRef this, - int* opCount ); - -/* desc: -item by item acccess. gets first item -at head of list. for simple list -traversing, it's quicker to use the -ResetPosition and -GetNextItemFromPosition functions. -* returns: -InvalidListRef: null list ptr or bad -signature. -*/ -xList_tErr xList_GetFirstItem ( xListRef this, - void** oppFirstItem ); - -/* desc: given an item, searches the list -for the item, gets the next node, and -returns the data at that node. -* returns: -InvalidListRef: null list ptr or bad -signature. -*/ -xList_tErr xList_GetNextItem ( xListRef this, - void* ipCurrentItem, - void** oppNextItem ); - -/* desc: -quicker for simple sequential access. -resets internal position to the head of -the list. call before traversing. -* returns: -InvalidListRef: null list ptr or bad -signature. -EndOfList: no next item. oppNextItem -will be null. -ItemNotInList: couldn't find -ipCurrentItem. -*/ -xList_tErr xList_ResetPosition ( xListRef this ); - -/* desc: -gets the data at the current internal -position and advances the internal -ptr. -* returns: -InvalidListRef: null list ptr or bad -signature. -*/ -xList_tErr xList_GetNextItemFromPosition ( xListRef this, - void** oppNextItem ); -xList_tErr xList_NextFromPos ( xListRef this, - void** oppNextItem ); - -/* desc: -for stack style access. pushes onto the -head. -* returns: -InvalidListRef: null list ptr or bad -signature for list or node. -EndOfList: no next item. oppNextItem -will be nil. -*/ -xList_tErr xList_PushItem ( xListRef this, - void* ipItemToInsert ); - -/* desc: -for stack style access. pops an item off -the head and returns its data -* returns: -InvalidListRef: null list ptr or bad -signature. -InternalAllocationFailed: couldn't -allocate node. -*/ -xList_tErr xList_PopItem ( xListRef this, void** oppItem ); - -/* desc: -error checking. checks for null ptr and -for a valid signature. every function -calls this one, so you shouldn't have to, -but you can. -* returns: -InvalidListRef: null list ptr or bad -signature. -*/ -xList_tErr xList_SetComparator ( xListRef this, - xList_tCompare(*iComparator)(void*,void*) ); - -xList_tCompare xList_CompareItems_ ( xListRef this, - void* pItemA, - void* pItemB ); - -xList_tErr xList_Verify ( xListRef this ); - -/* desc: -gives back an error string. -* returns: -ptr to a string. -*/ -char* xList_GetErrorString ( xList_tErr ieCode ); - -/* private functions */ - -/* desc: -internal method for finding the node -containing a specific ptr. -* returns: -ptr to the node or nil if not found. -*/ -xListNodeRef xList_FindItem_ ( xListRef this, - void* ipItem ); - - -#endif diff --git a/include/xSparseVolume.h b/include/xSparseVolume.h deleted file mode 100644 index 772a18207dd..00000000000 --- a/include/xSparseVolume.h +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file xSparseVolume.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef xSparseVolume_h -#define xSparseVolume_h - -#include "xTypes.h" -#include "xVoxel.h" - -typedef enum -{ - xSVol_tErr_NoErr = 0, - xSVol_tErr_InvalidObject, - xSVol_tErr_InvalidParameter, - xSVol_tErr_InvalidSignature, - xSVol_tErr_AllocationFailed, - xSVol_tErr_ItemNotFound, - xSVol_tErr_IndexOutOfBounds, - xSVol_tErr_IndexNotAllocated, - xSVol_tErr_InvalidErrorCode, - xSVol_knNumErrorCodes -} xSVol_tErr; - -#define xSVol_kSignature 0x098abcdd - -typedef struct -{ - - tSignature mSignature; - - /* stored mStorage[z][y][x] */ - void**** mStorage; - - /* dimensions of volume */ - int mnXDim; - int mnYDim; - int mnZDim; - -} -xSparseVolume, *xSparseVolumeRef; - -typedef void(*xSVol_tDeleteEntryFuncPtr)( void* ); - -/* only allocates an array of z values */ -xSVol_tErr xSVol_New ( xSparseVolumeRef* opVolume, - int inXDim, - int inYDim, - int inZDim ); -xSVol_tErr xSVol_Delete ( xSparseVolumeRef* iopVolume, - xSVol_tDeleteEntryFuncPtr ipDeleteFunc ); - -/* checks if the given location exists. if so, returns the value of the - data stored there (a pointer). if not, returns NULL and - xSVol_tErr_ItemNotFound. */ -xSVol_tErr xSVol_Get ( xSparseVolumeRef this, - xVoxelRef iWhere, - void** oppItem ); - -/* sets the pointer value of the location. if necessary, allocates additional - storage in the volume. starts out with only a z array allocated. when it - gets a set request for 1,2,3, it will allocate a y array at mStorage[3], and - then an x array at mStorage[3][2]. a subsequent set request for 2,2,3 will - not allocate any more memory, while one for 2,3,3 will allocate another y - and x array. */ -xSVol_tErr xSVol_Set ( xSparseVolumeRef this, - xVoxelRef iWhere, - void* ipItem ); - -/* purges all memory. calls the given delete function on each object, if - given. */ -xSVol_tErr xSVol_Purge ( xSparseVolumeRef this, - xSVol_tDeleteEntryFuncPtr ipDeleteFunc ); - -/* calls given function an all entries. calls the z function every time a new - z index is entered or left, the y function etc */ -xSVol_tErr xSVol_VisitAll ( xSparseVolumeRef this, - void(*ipVisitFunction)(void* ipItem), - void(*ipXFunction)(int inIndex,tBoolean bEntering), - void(*ipYFunction)(int inIndex,tBoolean bEntering), - void(*ipZFunction)(int inIndex,tBoolean bEntering)); - -xSVol_tErr xSVol_VerifyIndex_ ( xSparseVolumeRef this, - xVoxelRef iIndex ); - -char* xSVol_GetErrorString ( xSVol_tErr ieCode ); -xSVol_tErr xSVol_Verify ( xSparseVolumeRef this ); - - -#endif diff --git a/include/xUndoList.h b/include/xUndoList.h deleted file mode 100644 index 21731bedf7c..00000000000 --- a/include/xUndoList.h +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file xUndoList.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef xUndoList_H -#define xUndoList_H - -#include "xList.h" - -typedef enum -{ - - xUndL_tErr_NoErr = 0, - xUndL_tErr_AllocationFailed, - xUndL_tErr_InternalAllocationFailed, - xUndL_tErr_ItemDeletionFailed, - xUndL_tErr_ListDeletionFailed, - xUndL_tErr_InvalidFunctionPtr, - xUndL_tErr_InsertionFailed, - xUndL_tErr_RetrievalFailed, - xUndL_tErr_AllocationOfSwapListFailed, - xUndL_tErr_SwapListInsertionFailed, - xUndL_tErr_InvalidListPtr, - xUndL_tErr_ClearFailed, - xUndL_tErr_ListCountFailed, - xUndL_tErr_ListResetFailed, - xUndL_tErr_InvalidPrintFunction, - xUndL_tErr_InvalidErrorCode, - xUndL_knNumErrorCodes - -} xUndL_tErr; - -#define xUndL_kSignature 0xf0f9f8f7 - -typedef void* xUndL_tEntryPtr; - -typedef void(*xUndL_tSwapFuncPtr) ( xUndL_tEntryPtr, xUndL_tEntryPtr* ); -typedef void(*xUndL_tDeleteEntryFuncPtr)( xUndL_tEntryPtr* ); -typedef void(*xUndL_tPrintEntryFuncPtr) ( xUndL_tEntryPtr ); - -typedef struct -{ - - long mSignature; - - xListRef mpList; - xUndL_tSwapFuncPtr mpSwapFunction; - xUndL_tDeleteEntryFuncPtr mpDeleteFunction; - xUndL_tPrintEntryFuncPtr mpPrintFunction; - -} -xUndoList, *xUndoListRef; - -xUndL_tErr xUndL_New ( xUndoListRef* oppList, - xUndL_tSwapFuncPtr ipSwapFunction, - xUndL_tDeleteEntryFuncPtr ipDeleteFunction ); - -xUndL_tErr xUndL_Delete ( xUndoListRef* ioppList ); - -xUndL_tErr xUndL_Clear ( xUndoListRef ipList ); - -xUndL_tErr xUndL_AddEntry ( xUndoListRef ipList, - xUndL_tEntryPtr ipEntry ); - -xUndL_tErr xUndL_Restore ( xUndoListRef ipList ); - -xUndL_tErr xUndL_SetPrintFunction ( xUndoListRef ipList, - xUndL_tPrintEntryFuncPtr ipPrintFunction ); - -xUndL_tErr xUndL_Print ( xUndoListRef ipList ); - -xUndL_tErr xUndL_Verify ( xUndoListRef ipList ); - -char * xUndL_GetErrorString ( xUndL_tErr ieCode ); - -/* private */ - -xUndL_tErr xUndL_NewList_ ( xListRef* ippList ); - -xUndL_tErr xUndL_DeleteList_ ( xUndoListRef ipUndoList, - xListRef* oppList ); - - - - - -#endif diff --git a/include/xUtilities.h b/include/xUtilities.h deleted file mode 100644 index 86613fb0a51..00000000000 --- a/include/xUtilities.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file xUtilities.h - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:10 $ - * $Revision: 1.7 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#include "xTypes.h" -#include "xDebug.h" - -typedef enum -{ - xUtil_tErr_Invalid = -1, - xUtil_tErr_NoError = 0, - xUtil_tErr_InvalidErrorCode, - xUtil_tErr_knNumErrorCodes -} xUtil_tErr; - -xUtil_tErr xUtil_BreakStringIntoPathAndStem ( char* isPathAndStem, - char* osPath, - char* osStem ); - -/* - * Poor man's profiler. Use these to time code execution length. Pass a - * message top be printed to the debug stream when the time is stopped. - */ - -void xUtil_StartTimer (); -void xUtil_StopTimer ( char* isMessage ); - -/* - * These are 'safe' replacements for the normal string routines. At least, - * I think they are safe. The functions without n use sizeof on the buffer - * and then call the n sized functions. After each n function copies in - * normally, it sets the last character in the buffer to null. If it wasn't - * null, it was print out a debugging note for an overflow alert. - */ - -void xUtil_strcpy ( char* ipDest, char* ipSrc ); -void xUtil_strncpy ( char* ipDest, char* ipSrc, int inSize ); -void xUtil_snprintf ( char* ipDest, int inSize, char* isFormat, ... ); -void xUtil_sprintf ( char* ipDest, char* isFormat, ... ); - - - -char* xUtil_GetErrorString( xUtil_tErr iCode ); - - -/* - * For doing ctrl-c to cancel long operations but not quit the program. - */ -void xUtil_InitializeUserCancel (); -void xUtil_StartListeningForUserCancel (); -void xUtil_StopListeningForUserCancel (); -int xUtil_DidUserCancel (); -void xUtil_HandleUserCancelCallback (int signal); diff --git a/include/xVoxel.h b/include/xVoxel.h index 408e44b9371..a46695f1223 100644 --- a/include/xVoxel.h +++ b/include/xVoxel.h @@ -25,13 +25,9 @@ #ifndef xxVoxl_H #define xxVoxl_H -#if defined(__cplusplus) -extern "C" { -#endif - #include "xTypes.h" -/* Enable this to turn on macros, see details below. */ +/* Enable item to turn on macros, see details below. */ #define XVOXL_USE_MACROS typedef struct @@ -85,39 +81,39 @@ float xVoxl_GetFloatZ ( xVoxelRef ThisKRT ); /* The do/while garbage is to allow the compiler to parse a semicolon after the macro call. */ -#define xVoxl_Set(this,x,y,z) \ +#define xVoxl_Set(item,x,y,z) \ do { \ - (this)->mfX = (x); \ - (this)->mfY = (y); \ - (this)->mfZ = (z); \ + (item)->mfX = (x); \ + (item)->mfY = (y); \ + (item)->mfZ = (z); \ }while(0) -#define xVoxl_GetX(this) (int)(floor( (this)->mfX + 0.5 )) -#define xVoxl_GetY(this) (int)(floor( (this)->mfY + 0.5 )) -#define xVoxl_GetZ(this) (int)(floor( (this)->mfZ + 0.5 )) +#define xVoxl_GetX(item) (int)(floor( (item)->mfX + 0.5 )) +#define xVoxl_GetY(item) (int)(floor( (item)->mfY + 0.5 )) +#define xVoxl_GetZ(item) (int)(floor( (item)->mfZ + 0.5 )) -#define xVoxl_GetRoundX(this) rint( (this)->mfX ) -#define xVoxl_GetRoundY(this) rint( (this)->mfY ) -#define xVoxl_GetRoundZ(this) rint( (this)->mfZ ) +#define xVoxl_GetRoundX(item) rint( (item)->mfX ) +#define xVoxl_GetRoundY(item) rint( (item)->mfY ) +#define xVoxl_GetRoundZ(item) rint( (item)->mfZ ) -#define xVoxl_SetFloat(this,x,y,z) \ +#define xVoxl_SetFloat(item,x,y,z) \ do { \ - (this)->mfX = (x); \ - (this)->mfY = (y); \ - (this)->mfZ = (z); \ + (item)->mfX = (x); \ + (item)->mfY = (y); \ + (item)->mfZ = (z); \ }while(0) -#define xVoxl_SetX(this,x) (this)->mfX = (x) -#define xVoxl_SetY(this,y) (this)->mfY = (y) -#define xVoxl_SetZ(this,z) (this)->mfZ = (z) +#define xVoxl_SetX(item,x) (item)->mfX = (x) +#define xVoxl_SetY(item,y) (item)->mfY = (y) +#define xVoxl_SetZ(item,z) (item)->mfZ = (z) -#define xVoxl_SetFloatX(this,x) (this)->mfX = (x) -#define xVoxl_SetFloatY(this,y) (this)->mfY = (y) -#define xVoxl_SetFloatZ(this,z) (this)->mfZ = (z) +#define xVoxl_SetFloatX(item,x) (item)->mfX = (x) +#define xVoxl_SetFloatY(item,y) (item)->mfY = (y) +#define xVoxl_SetFloatZ(item,z) (item)->mfZ = (z) -#define xVoxl_GetFloatX(this) (this)->mfX -#define xVoxl_GetFloatY(this) (this)->mfY -#define xVoxl_GetFloatZ(this) (this)->mfZ +#define xVoxl_GetFloatX(item) (item)->mfX +#define xVoxl_GetFloatY(item) (item)->mfY +#define xVoxl_GetFloatZ(item) (item)->mfZ #endif /* end of macro versions */ @@ -146,16 +142,4 @@ void xVoxl_PrintDebug ( xVoxelRef ThisKRT ); #define xVoxl_ExpandInt(v) xVoxl_GetX(v), xVoxl_GetY(v), xVoxl_GetZ(v) #define xVoxl_ExpandRint(v) (int)rint(xVoxl_GetX(v)), (int)rint(xVoxl_GetY(v)), (int)rint(xVoxl_GetZ(v)) -#if defined(__cplusplus) -}; -#endif - - #endif - - - - - - - diff --git a/include/xview/alert.h b/include/xview/alert.h deleted file mode 100644 index dff619d72b2..00000000000 --- a/include/xview/alert.h +++ /dev/null @@ -1,63 +0,0 @@ -/* @(#)alert.h 20.15 91/09/14 */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* SunView 1.x "alerts" are now called "notices" in SunXView.x. Below - * is for backwards compatibility only. All usages of alert.h should - * be discontinued as further releases may not support this interface. - * Not all "alert" attributes apply in SunXView.x, so full compatiblity - * does not exist. - * Include notice.h definitions and attributes instead. - */ - -#ifndef xview_alert_DEFINED -#define xview_alert_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define Alert_attribute Notice_attribute - -#define ALERT_NO_BEEPING NOTICE_NO_BEEPING -#define ALERT_MESSAGE_STRINGS NOTICE_MESSAGE_STRINGS -#define ALERT_MESSAGE_STRINGS_ARRAY_PTR NOTICE_MESSAGE_STRINGS_ARRAY_PTR -#define ALERT_MESSAGE_FONT NOTICE_FONT -#define ALERT_BUTTON_YES NOTICE_BUTTON_YES -#define ALERT_BUTTON_NO NOTICE_BUTTON_NO -#define ALERT_BUTTON NOTICE_BUTTON -#define ALERT_TRIGGER NOTICE_TRIGGER - -/* - * Useful constants - */ -#define ALERT_YES 1 -#define ALERT_NO 0 -#define ALERT_FAILED -1 -#define ALERT_TRIGGERED -2 - -#define alert_prompt notice_prompt - -/* - * PRIVATE #defines - */ -#define alert_attr_next(attr) (Notice_attribute *)attr_next((caddr_t *)attr) - -#endif /* ~xview_alert_DEFINED */ diff --git a/include/xview/attr.h b/include/xview/attr.h deleted file mode 100644 index b20a7e093bf..00000000000 --- a/include/xview/attr.h +++ /dev/null @@ -1,481 +0,0 @@ -/* @(#)attr.h 20.42 91/06/17 */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_attr_DEFINED -#define xview_attr_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * This macro is machine dependent in that it assumes - * the cardinality will be in the lower 5 bits of the type-cardinality - * pair. - */ -#define ATTR_TYPE(base_type, cardinality) \ - (((((unsigned)(base_type)) & 0x07f) << 5) | \ - (((unsigned)(cardinality)) & 0x0f)) - -/* - * Note that this macro is machine dependent in that it assumes the - * base_type-cardinality pair will be in the lower 13 bits of the - * list_type-base_cardinality pair. - */ -#define ATTR_LIST_OF(list_type, list_ptr_type, base_cardinality) \ - (((((unsigned)(list_type)) & 0x3) << 14) | \ - (((unsigned)(list_ptr_type) & 0x1) << 13) | \ - (((unsigned)(base_cardinality)) & 0x3fff)) - -#define ATTR_LIST_INLINE(list_type, base_cardinality) \ - ATTR_LIST_OF(list_type, ATTR_LIST_IS_INLINE, base_cardinality) - -#define ATTR_LIST_PTR(list_type, base_cardinality) \ - ATTR_LIST_OF(list_type, ATTR_LIST_IS_PTR, base_cardinality) - -/* - * An attribute is composed of - * pkg ( 8 bits): id of package that uses the attribute - * ordinal ( 8 bits): ordinal number of the attribute - * type (16 bits): list type, list pointer type, base type, and cardinality - */ -#define ATTR(pkg, type, ordinal) \ - ( ((((unsigned)(pkg)) & 0x7f) << 24) | \ - ((((unsigned)(ordinal)) & 0xff) << 16) | \ - (((unsigned)(type)) & 0xffef) ) - - -/* - * The base type space potentially runs from 0 to 127 inclusive. This is - * subdivided as follows: - * [0..32) [ATTR_BASE_UNUSED_FIRST..ATTR_BASE_UNUSED_LAST] - * Reserved for non-Sun packages. - * [32..64) Reserved for future use. - * [64..128) [ATTR_BASE_FIRST..ATTR_BASE_LAST] is currently used by - * Sun packages - * (ATTR_BASE_LAST..128) is for future use by Sun packages. - */ -#define ATTR_BASE_UNUSED_FIRST 0 -#define ATTR_BASE_UNUSED_LAST 31 -#define ATTR_BASE_FIRST 64 - -#define ATTR_PKG_UNUSED_FIRST 1 -#define ATTR_PKG_UNUSED_LAST 31 -#define ATTR_PKG_FIRST 64 - -/* - * Values from the Attr_pkg enumeration which are required for some - * of the following #defines. This allows those defines to remain in this - * section rather than below the enumeration. - */ -#define ATTR_PKG_ZERO_VALUE 0 -#define ATTR_PKG_GENERIC_VALUE ATTR_PKG_FIRST -#define ATTR_PKG_LAST_VALUE ATTR_PKG_FIRST + 14 - -/* - * ATTR_STANDARD_SIZE is large enough to allow for - * most attribute-value lists. - */ -#define ATTR_STANDARD_SIZE 250 - -/* - * Generic attribute definition - */ -#define GENERIC_ATTR(type, ordinal) \ - ATTR(ATTR_PKG_GENERIC_VALUE, type, ordinal) - -/* - * Note that in these macros, attr must not be - * in a register or be a constant. - * Since this is deemed too restrictive, we use - * shifting & masking instead. - * #define ATTR_UNION(attr) ((Attr_union *) &((Attr_attribute) (attr))) - * #define ATTR_INFO(attr) (ATTR_UNION(attr)->info) - * #define ATTR_CODE(attr) (ATTR_UNION(attr)->code) - * #define ATTR_LIST_TYPE(attr) (ATTR_INFO(attr).list_type) - * #define ATTR_LIST_PTR_TYPE(attr) (ATTR_INFO(attr).list_ptr_type) - * #define ATTR_BASE_TYPE(attr) (ATTR_INFO(attr).base_type) - * #define ATTR_CARDINALITY(attr) (ATTR_INFO(attr).cardinality) - * #define ATTR_CONSUMED(attr) (ATTR_INFO(attr).consumed) - * #define ATTR_PKG(attr) (ATTR_INFO(attr).pkg) - * #define ATTR_ORDINAL(attr) (ATTR_INFO(attr).ordinal) - */ - -#define ATTR_CODE(attr) ((unsigned) (attr)) - -#define ATTR_PKG(attr) \ - ((Attr_pkg) ((ATTR_CODE(attr) >> 24) & 0xFF)) - -#define ATTR_ORDINAL(attr) \ - ((unsigned) ((ATTR_CODE(attr) >> 16) & 0xFF)) - -#define ATTR_LIST_TYPE(attr) \ - ((Attr_list_type) ((ATTR_CODE(attr) >> 14) & 0x3)) - -#define ATTR_LIST_PTR_TYPE(attr) \ - ((Attr_list_ptr_type) ((ATTR_CODE(attr) >> 13) & 0x1)) - -#define ATTR_BASE_TYPE(attr) \ - ((Attr_base_type) ((ATTR_CODE(attr) >> 5) & 0x7F)) - -/* - * This macro is different from ATTR_BASE_TYPE in that it returns - * the 'type' of the attribute, and not just the base type. - * The base type is one of the things that is used to specify 'type'. - * - * It is also different from ATTR_TYPE, which returns the - * bits. - * - * Note: Bit 4 i.e. the spare1 bit is zeroed. - */ -#define ATTR_WHICH_TYPE(attr) \ - ((Attr_base_cardinality) ((ATTR_CODE(attr)) & 0xffef)) - -#define ATTR_CARDINALITY(attr) \ - ((unsigned) (ATTR_CODE(attr) & 0xF)) - -#define ATTR_CONSUMED(attr) ((unsigned) ((ATTR_CODE(attr) >> 12) & 0x1)) - -#define attr_skip(attr, argv) \ - ((ATTR_LIST_TYPE((attr)) == ATTR_NONE) \ - ? (Attr_avlist) (argv) + ATTR_CARDINALITY((attr)) \ - : attr_skip_value((Attr_attribute)(attr), (argv))) - -#define attr_next(attrs) attr_skip((*(attrs)), ((attrs)+1)) - -#define attr_make( listhead, listlen, valist ) \ - attr_make_count( listhead, listlen, valist, NULL ) - -/* - * Character unit support - * Provided for SunView 1 compatibility. - */ -#ifndef lint -#define attr_replace_cu(avlist, font, lmargin, tmargin, rgap) \ - attr_rc_units_to_pixels(avlist, xv_get(font, FONT_DEFAULT_CHAR_WIDTH), \ - xv_get(font, FONT_DEFAULT_CHAR_HEIGHT), lmargin, tmargin, 0, rgap) - -#define attr_cu_to_x(encoded_value, font, left_margin) \ - attr_rc_unit_to_x(encoded_value, xv_get(font, FONT_DEFAULT_CHAR_WIDTH), left_margin, 0) - -#define attr_cu_to_y(encoded_value, font, top_margin, row_gap) \ - attr_rc_unit_to_y(encoded_value, xv_get(font, FONT_DEFAULT_CHAR_HEIGHT), top_margin, \ - row_gap) -#endif /* lint */ - -#define ATTR_CU_TAG 0x80000000 -#define ATTR_PIXEL_OFFSET 0x00008000 -#define ATTR_CU_MASK 0xC0000000 - -#define ATTR_CU_TYPE(n) \ - ((Attr_cu_type) ((n) & (unsigned) (ATTR_CU_LENGTH))) - -#define ATTR_CU(unit, n) \ - (((unsigned)(unit)) | (((n) & 0x1FFF) << 16) | \ - ATTR_CU_TAG | ATTR_PIXEL_OFFSET) - -/* - * attr_is_cu(n) returns non-zero if n has - * been encoded using ATTR_CU() - */ -#define attr_is_cu(n) (((n) & ATTR_CU_MASK) == ATTR_CU_TAG) - -/* - * Following are useful for multi-pass avlist processing. - */ -#define ATTR_NOP(attr) (ATTR_CODE(attr) | (0x1 << 12)) -#define ATTR_CONSUME(attr) (attr) = ((Xv_opaque)ATTR_NOP(attr)) - -/* - * For Sunview 1 compatibility - */ - -#define ATTR_PIXWIN_PTR ATTR_OPAQUE - -/* - * Macros for position including - * margins. - */ -#define ATTR_COL(n) ATTR_CU(ATTR_CU_POSITION, n) -#define ATTR_ROW(n) ATTR_CU(ATTR_CU_POSITION, n) - -/* - * Macros for length excluding - * margins. - */ -#define ATTR_COLS(n) ATTR_CU(ATTR_CU_LENGTH, n) -#define ATTR_ROWS(n) ATTR_CU(ATTR_CU_LENGTH, n) -#define ATTR_CHARS(n) ATTR_CU(ATTR_CU_LENGTH, n) -#define ATTR_LINES(n) ATTR_CU(ATTR_CU_LENGTH, n) - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -/* - * Attr_avlist is not an array of Attr_attributes, because it is an array - * of intermixed attributes and values. - */ -typedef unsigned long Attr_attribute; /* 32 bit quantity */ -typedef Attr_attribute *Attr_avlist; - -/* - * Enumerations - */ - -typedef enum { - ATTR_CU_POSITION = 0x0, /* bit 29 is off */ - ATTR_CU_LENGTH = 0x20000000 /* bit 29 is on */ -} Attr_cu_type; - -typedef enum { - ATTR_LIST_IS_INLINE = 0, - ATTR_LIST_IS_PTR = 1 -} Attr_list_ptr_type; - -typedef enum { - /* Note that ATTR_NONE must have a value of zero, - * since a no-list type is assumed for each of the - * types in Attr_base_cardinality. - */ - ATTR_NONE = 0, - ATTR_RECURSIVE = 1, - ATTR_NULL = 2, - ATTR_COUNTED = 3 -} Attr_list_type; - -/* - * NOTE: The base type numbers have to be EXACTLY the same as SunView1 in order - * to support cut and paste between SunView1 and XView windows. - * Nothing changes! - */ -typedef enum { - ATTR_BASE_NO_VALUE = ATTR_BASE_FIRST + 17, - /* - * Fundamental C types. - */ - ATTR_BASE_INT = ATTR_BASE_FIRST, - ATTR_BASE_LONG = ATTR_BASE_FIRST + 24, - ATTR_BASE_SHORT = ATTR_BASE_FIRST + 25, - ATTR_BASE_ENUM = ATTR_BASE_FIRST + 9, - ATTR_BASE_CHAR = ATTR_BASE_FIRST + 10, -#ifdef OW_I18N - ATTR_BASE_WCHAR = ATTR_BASE_FIRST + 26, -#define ATTR_BASE_CHAR_WC ATTR_BASE_WCHAR -#endif - ATTR_BASE_STRING = ATTR_BASE_FIRST + 11, -#ifdef OW_I18N - ATTR_BASE_WSTRING = ATTR_BASE_FIRST + 27, -#define ATTR_BASE_STRING_WCS ATTR_BASE_WSTRING -#endif - ATTR_BASE_FUNCTION_PTR = ATTR_BASE_FIRST + 19, - /* - * Derivative C types. - */ - ATTR_BASE_BOOLEAN = ATTR_BASE_FIRST + 8, - ATTR_BASE_OPAQUE = ATTR_BASE_FIRST + 16, - /* - * Special coordinate types; look in attr_cu.c for the details. - */ - ATTR_BASE_X = ATTR_BASE_FIRST + 2, - ATTR_BASE_INDEX_X = ATTR_BASE_FIRST + 3, - ATTR_BASE_Y = ATTR_BASE_FIRST + 4, - ATTR_BASE_INDEX_Y = ATTR_BASE_FIRST + 5, - ATTR_BASE_XY = ATTR_BASE_FIRST + 6, - ATTR_BASE_INDEX_XY = ATTR_BASE_FIRST + 7, - /* - * Pointer types. - */ - ATTR_BASE_PIXRECT_PTR = ATTR_BASE_FIRST + 12, - ATTR_BASE_PIXFONT_PTR = ATTR_BASE_FIRST + 13, - ATTR_BASE_RECT_PTR = ATTR_BASE_FIRST + 15, - ATTR_BASE_AV = ATTR_BASE_FIRST + 18, - ATTR_BASE_ICON_PTR = ATTR_BASE_FIRST + 20, - ATTR_BASE_SINGLE_COLOR_PTR = ATTR_BASE_FIRST + 21, - ATTR_BASE_CURSOR_PTR = ATTR_BASE_FIRST + 22, -#ifdef OW_I18N - ATTR_BASE_LAST = ATTR_BASE_FIRST + 27 -#else - ATTR_BASE_LAST = ATTR_BASE_FIRST + 25 -#endif -} Attr_base_type; - -/* Clients of the attribute value package should use - * Attr_base_cardinality elements to define the base type - * and cardinality of their attributes. - */ -typedef enum { - ATTR_NO_VALUE = ATTR_TYPE(ATTR_BASE_NO_VALUE, 0), - ATTR_INT = ATTR_TYPE(ATTR_BASE_INT, 1), - ATTR_INT_PAIR = ATTR_TYPE(ATTR_BASE_INT, 2), - ATTR_INT_TRIPLE = ATTR_TYPE(ATTR_BASE_INT, 3), - ATTR_LONG = ATTR_TYPE(ATTR_BASE_LONG, 1), - ATTR_SHORT = ATTR_TYPE(ATTR_BASE_SHORT, 1), - ATTR_ENUM = ATTR_TYPE(ATTR_BASE_ENUM, 1), - ATTR_CHAR = ATTR_TYPE(ATTR_BASE_CHAR, 1), -#ifdef OW_I18N - ATTR_WCHAR = ATTR_TYPE(ATTR_BASE_WCHAR, 1), -#define ATTR_CHAR_WC ATTR_WCHAR -#endif - ATTR_STRING = ATTR_TYPE(ATTR_BASE_STRING, 1), -#ifdef OW_I18N - ATTR_WSTRING = ATTR_TYPE(ATTR_BASE_WSTRING, 1), -#define ATTR_STRING_WCS ATTR_WSTRING -#endif - ATTR_FUNCTION_PTR = ATTR_TYPE(ATTR_BASE_FUNCTION_PTR, 1), - ATTR_BOOLEAN = ATTR_TYPE(ATTR_BASE_BOOLEAN, 1), - ATTR_OPAQUE = ATTR_TYPE(ATTR_BASE_OPAQUE, 1), - ATTR_OPAQUE_PAIR = ATTR_TYPE(ATTR_BASE_OPAQUE, 2), - ATTR_OPAQUE_TRIPLE = ATTR_TYPE(ATTR_BASE_OPAQUE, 3), - ATTR_X = ATTR_TYPE(ATTR_BASE_X, 1), - ATTR_INDEX_X = ATTR_TYPE(ATTR_BASE_INDEX_X, 2), - ATTR_Y = ATTR_TYPE(ATTR_BASE_Y, 1), - ATTR_INDEX_Y = ATTR_TYPE(ATTR_BASE_INDEX_Y, 2), - ATTR_XY = ATTR_TYPE(ATTR_BASE_XY, 2), - ATTR_INDEX_XY = ATTR_TYPE(ATTR_BASE_INDEX_XY, 3), - ATTR_PIXRECT_PTR = ATTR_TYPE(ATTR_BASE_PIXRECT_PTR, 1), - ATTR_PIXFONT_PTR = ATTR_TYPE(ATTR_BASE_PIXFONT_PTR, 1), - ATTR_RECT_PTR = ATTR_TYPE(ATTR_BASE_RECT_PTR, 1), - ATTR_AV = ATTR_TYPE(ATTR_BASE_AV, 1), - ATTR_ICON_PTR = ATTR_TYPE(ATTR_BASE_ICON_PTR, 1), - ATTR_SINGLE_COLOR_PTR = ATTR_TYPE(ATTR_BASE_SINGLE_COLOR_PTR, 1), - ATTR_CURSOR_PTR = ATTR_TYPE(ATTR_BASE_CURSOR_PTR, 1) -} Attr_base_cardinality; - -/* - * The package id space potentially runs from 0 to 255 inclusive. This is - * subdivided as follows: - * 0 NEVER a valid package id. - * [1..32) [ATTR_PKG_UNUSED_FIRST..ATTR_PKG_UNUSED_LAST] - * Reserved for non-Sun packages. - * [32..64) Reserved for future use. - * [64..128) [ATTR_PKG_FIRST..ATTR_PKG_LAST] is currently used by - * Sun packages - * (ATTR_PKG_LAST..128) is for future use by Sun packages. - * [128..256) Reserved for future use. - */ -typedef enum { - ATTR_PKG_ZERO = ATTR_PKG_ZERO_VALUE, - ATTR_PKG_GENERIC = ATTR_PKG_GENERIC_VALUE, - - ATTR_PKG_CURSOR = ATTR_PKG_FIRST + 1, - ATTR_PKG_DRAWABLE = ATTR_PKG_FIRST + 2, - ATTR_PKG_FONT = ATTR_PKG_FIRST + 3, - ATTR_PKG_IMAGE = ATTR_PKG_FIRST + 4, - ATTR_PKG_SERVER_IMAGE = ATTR_PKG_FIRST + 5, - ATTR_PKG_SCREEN = ATTR_PKG_FIRST + 6, - ATTR_PKG_SELN_BASE = 71, /* ATTR_PKG_FIRST + 7 */ - /* ATTR_PKG_SELN_BASE must be 71, as it is known to 3.X and 4.X code. - * In fact, the layout of the bits in an attribute is known, and also - * cannot change without breaking communication between SunView 1 and - * XView selections. - */ - ATTR_PKG_SERVER = ATTR_PKG_FIRST + 8, - ATTR_PKG_WIN = ATTR_PKG_FIRST + 9, - ATTR_PKG_SV = ATTR_PKG_FIRST + 10, - ATTR_PKG_FULLSCREEN = ATTR_PKG_FIRST + 11, - ATTR_PKG_ERROR = ATTR_PKG_FIRST + 12, - ATTR_PKG_CMS = ATTR_PKG_FIRST + 13, - ATTR_PKG_DND = ATTR_PKG_FIRST + 14, - - /* REMIND: ATTR_PKG_SELECTION should be ATTR_PKG_FIRST+15 put this - will cause the pkg values for the OL pkgs to change. This - would break binary compatibility. So we put the new intrinsic - pkg after the OL pkgs. When we can again break binary - compatibility, we should change this and add some space - between the intrinsic pkgs and the OL pkgs. - Remove comment in attrol.h when this is fixed. - */ - ATTR_PKG_SELECTION = ATTR_PKG_LAST_VALUE + 20, - - ATTR_PKG_LAST = ATTR_PKG_LAST_VALUE - /* - * Change ATTR_PKG_LAST_VALUE to be EQUAL to the last legal pkg id. - * The procedure counter(), called by attr_make, aborts if - * PKG_ID > ATTR_PKG_LAST - * PKG name should also be added to attr_names[] in attr.c - */ -} Attr_pkg; - -/* - * Generic attributes: ATTR_PKG_GENERIC is shared with - * generic.h [64..128). - */ -typedef enum { - ATTR_LIST = GENERIC_ATTR(ATTR_LIST_PTR(ATTR_RECURSIVE, ATTR_NO_VALUE), 0), - ATTR_NOP0 = GENERIC_ATTR(ATTR_NO_VALUE, 16), - ATTR_NOP1 = GENERIC_ATTR(ATTR_OPAQUE, 17), - ATTR_NOP2 = GENERIC_ATTR(ATTR_TYPE(ATTR_BASE_OPAQUE, 2), 18), - ATTR_NOP3 = GENERIC_ATTR(ATTR_TYPE(ATTR_BASE_OPAQUE, 3), 19), - ATTR_NOP4 = GENERIC_ATTR(ATTR_TYPE(ATTR_BASE_OPAQUE, 4), 20) -} Attr_generic; - -/* - * Structs - */ - -typedef union { - struct - { -ENUM_BITFIELD(Attr_pkg) pkg : - 8; -unsigned ordinal : - 8; -ENUM_BITFIELD(Attr_list_type) list_type : - 2; -ENUM_BITFIELD(Attr_list_ptr_type) list_ptr_type : - 1; -unsigned consumed : - 1; -ENUM_BITFIELD(Attr_base_type) base_type : - 7; -unsigned spare1 : - 1; /*unused*/ -unsigned cardinality : - 4; - } - info; - Attr_attribute code; -} Attr_union; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Public Functions - */ -EXTERN_FUNCTION (Attr_avlist attr_create_list, (Attr_attribute attr1, DOTDOTDOT)); - -/* - * Private Functions - */ -EXTERN_FUNCTION (int attr_copy, (Attr_avlist *source, Attr_avlist *dest)); -EXTERN_FUNCTION (int attr_count, (Attr_avlist count)); -EXTERN_FUNCTION (char * attr_name, (Attr_attribute attr)); -EXTERN_FUNCTION (Attr_avlist attr_skip_value, (Attr_attribute attr, Attr_avlist avlist)); -EXTERN_FUNCTION (int attr_rc_unit_to_x, (unsigned int encoded_value, int col_width, int left_margin, int col_gap)); -EXTERN_FUNCTION (int attr_rc_unit_to_y, (unsigned int encoded_value, int row_height, int top_margin, int row_gap)); -EXTERN_FUNCTION (void attr_rc_units_to_pixels, (Attr_avlist avlist, int col_width, int row_height, int left_margin, int top_margin, int col_gap, int row_gap)); - -#endif /* xview_attr_DEFINED */ diff --git a/include/xview/attrol.h b/include/xview/attrol.h deleted file mode 100644 index 1a425d4bf9c..00000000000 --- a/include/xview/attrol.h +++ /dev/null @@ -1,64 +0,0 @@ -/* @(#)attrol.h 20.11 88/09/05 */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_attrol_DEFINED -#define xview_attrol_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * These are the packages that are part of the XView OL library. - * - * IMPORTANT NOTE: The attr id numbers start where the "intrinsics" - * attr ids leave off. The range of valid values - * for these objects is [64..128) where - * ATTR_PKG_LAST_VALUE must be less than 128 and all - * ATTR_PKG_ ids defined here must fit in the range - * (ATTR_PKG_LAST_VALUE..128). - * - * Be sure to check the value of ATTR_PKG_LAST_VALUE - * when adding any new packages. - */ - -#define ATTR_PKG_CANVAS (ATTR_PKG_LAST_VALUE + 1) -#define ATTR_PKG_ENTITY (ATTR_PKG_LAST_VALUE + 2) -#define ATTR_PKG_TERMSW (ATTR_PKG_LAST_VALUE + 3) -#define ATTR_PKG_FRAME (ATTR_PKG_LAST_VALUE + 4) -#define ATTR_PKG_ICON (ATTR_PKG_LAST_VALUE + 5) -#define ATTR_PKG_MENU (ATTR_PKG_LAST_VALUE + 6) -#define ATTR_PKG_PANEL (ATTR_PKG_LAST_VALUE + 7) -#define ATTR_PKG_OPENWIN (ATTR_PKG_LAST_VALUE + 8) -#define ATTR_PKG_TEXTSW (ATTR_PKG_LAST_VALUE + 9) -#define ATTR_PKG_TTY (ATTR_PKG_LAST_VALUE + 10) -#define ATTR_PKG_NOTICE (ATTR_PKG_LAST_VALUE + 11) -#define ATTR_PKG_HELP (ATTR_PKG_LAST_VALUE + 12) -#define ATTR_PKG_TEXTSW_VIEW (ATTR_PKG_LAST_VALUE + 13) -#define ATTR_PKG_PANEL_VIEW (ATTR_PKG_LAST_VALUE + 14) -#define ATTR_PKG_CANVAS_VIEW (ATTR_PKG_LAST_VALUE + 15) -#define ATTR_PKG_CANVAS_PAINT_WINDOW (ATTR_PKG_LAST_VALUE + 16) -#define ATTR_PKG_TTY_VIEW (ATTR_PKG_LAST_VALUE + 17) -#define ATTR_PKG_TERMSW_VIEW (ATTR_PKG_LAST_VALUE + 18) -#define ATTR_PKG_SCROLLBAR (ATTR_PKG_LAST_VALUE + 19) - -/* See REMIND in attr.h before adding any new pkgs. */ - -#endif /* ~xview_attrol_DEFINED */ - diff --git a/include/xview/base.h b/include/xview/base.h deleted file mode 100644 index 3c7b0680c50..00000000000 --- a/include/xview/base.h +++ /dev/null @@ -1,121 +0,0 @@ -/* @(#)base.h 20.30 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_base_DEFINED -#define xview_base_DEFINED -#include -#ifndef Darwin -#include -#else -void *malloc(size_t byteSize) ; -#endif - -#include - -#if defined(__STDC__) || defined(__cplusplus) || defined(c_plusplus) -#include -#endif /* __cplusplus || __STDC__ */ - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -#define XV_OK 0 -#define XV_ERROR 1 - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef FALSE -#define FALSE 0 -#endif - -#ifndef NULL -#define NULL 0 -#endif - -#ifndef MIN -#define MIN(x, y) ( ((x) < (y)) ? (x) : (y) ) -#endif - -#ifndef MAX -#define MAX(x, y) ( ((x) > (y)) ? (x) : (y) ) -#endif - -/* These are portability #defines needed by public header files. Please see - * misc/portable.h for the bulk of the portability #defines. - */ -#if ( defined( SVR4 ) || defined( SYSV )) -#define XV_OS_SVR4 -#define XV_USE_TTCOMPAT -#define SYSV_WAIT -#define SYSV_UCONTEXT -#define XV_USE_XVFCNTL -#endif - -/* - * These alloc macros should be functions someday with an error call out - * to cleanup, if the underlying malloc fails. - */ - -extern void *xv_alloc_save_ret; -extern void xv_alloc_error(); -extern void *xv_calloc(); - -#define xv_alloc(t) \ - ((( xv_alloc_save_ret = (void *)calloc( 1, sizeof( t ))) ? (void)0 : \ - xv_alloc_error()) \ - , xv_alloc_save_ret ) - -#define xv_alloc_n(t, n) \ - ((( xv_alloc_save_ret = (void *)calloc( n, sizeof( t ))) ? (void)0 : \ - xv_alloc_error()) \ - , xv_alloc_save_ret ) - -#define xv_malloc( size ) \ - ((( xv_alloc_save_ret = (void *)malloc( size )) ? (void)0 : \ - xv_alloc_error()) \ - , xv_alloc_save_ret ) - -#define xv_realloc( ptr, size ) \ - ((( xv_alloc_save_ret = (void *)realloc( ptr, size )) ? (void)0 : \ - xv_alloc_error()) \ - , xv_alloc_save_ret ) - -#define xv_valloc( size ) \ - ((( xv_alloc_save_ret = (void *)valloc( size )) ? (void)0 : \ - xv_alloc_error()) \ - , xv_alloc_save_ret ) - -#define xv_free(s) ((void) free((char *)s)) -#define xv_strsave(s) strcpy( (char *)xv_malloc(strlen(s)+1), (s) ) - -#define XV_NULL ((Xv_opaque)NULL) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structs - *********************************************************************** - */ - -typedef unsigned long Xv_opaque; -typedef unsigned long Xv_object; - - -/* - *********************************************************************** - * Global Functions - *********************************************************************** - */ - -extern int defeat_event_security; - -#endif /* xview_base_DEFINED */ diff --git a/include/xview/canvas.h b/include/xview/canvas.h deleted file mode 100644 index cd11708035a..00000000000 --- a/include/xview/canvas.h +++ /dev/null @@ -1,162 +0,0 @@ -/* @(#)canvas.h 20.35 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_canvas_DEFINED -#define xview_canvas_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define CANVAS &xv_canvas_pkg -#define CANVAS_VIEW &xv_canvas_view_pkg -#define CANVAS_PAINT_WINDOW &xv_canvas_pw_pkg - -#define CANVAS_PIXWIN CANVAS_NTH_PAINT_WINDOW, 0 -#define CANVAS_AUTO_CLEAR OPENWIN_AUTO_CLEAR - -/* - * Some useful macros - */ -#define canvas_pixwin(canvas) \ - ((Pixwin *)xv_get(canvas, CANVAS_NTH_PAINT_WINDOW, 0)) -#define canvas_paint_window(canvas) \ - ((Xv_Window)xv_get(canvas, CANVAS_NTH_PAINT_WINDOW, 0)) - -#define CANVAS_EACH_PAINT_WINDOW(canvas, pw) \ - {int _pw_cnt = 0; \ - while (((pw) = (Xv_Window) xv_get((canvas), CANVAS_NTH_PAINT_WINDOW, _pw_cnt++)) != NULL) { \ - -#define CANVAS_END_EACH }} - -/* - * PRIVATE #defines - */ - -#define CANVAS_ATTR(type, ordinal) ATTR(ATTR_PKG_CANVAS, type, ordinal) -#define CANVAS_VIEW_ATTR(type, ordinal) ATTR(ATTR_PKG_CANVAS_VIEW,type, ordinal) -#define CANVAS_PAINT_ATTR(type, ordinal) ATTR(ATTR_PKG_CANVAS_PAINT_WINDOW,type, ordinal) -#define CANVAS_ATTR_LIST(ltype, type, ordinal) \ - CANVAS_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - - -/* - * For SunView 1 compatibility - */ -#define CANVAS_TYPE ATTR_PKG_CANVAS -#define CANVAS_MARGIN CANVAS_VIEW_MARGIN - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structs - *********************************************************************** - */ - -typedef Xv_opaque Canvas; -typedef Xv_opaque Canvas_view; -typedef Xv_opaque Canvas_paint_window; - -/* - * Enumerations - */ - -typedef enum { - /* - * Public attributes - */ - CANVAS_AUTO_EXPAND = CANVAS_ATTR(ATTR_BOOLEAN, 1), - CANVAS_AUTO_SHRINK = CANVAS_ATTR(ATTR_BOOLEAN, 5), - CANVAS_FIXED_IMAGE = CANVAS_ATTR(ATTR_BOOLEAN, 10), - CANVAS_HEIGHT = CANVAS_ATTR(ATTR_Y, 15), - CANVAS_MIN_PAINT_HEIGHT = CANVAS_ATTR(ATTR_Y, 20), - CANVAS_MIN_PAINT_WIDTH = CANVAS_ATTR(ATTR_X, 25), - CANVAS_NTH_PAINT_WINDOW = CANVAS_ATTR(ATTR_OPAQUE, 30), - CANVAS_REPAINT_PROC = CANVAS_ATTR(ATTR_FUNCTION_PTR, 35), - CANVAS_RESIZE_PROC = CANVAS_ATTR(ATTR_FUNCTION_PTR, 40), - CANVAS_RETAINED = CANVAS_ATTR(ATTR_BOOLEAN, 45), - CANVAS_VIEW_MARGIN = CANVAS_ATTR(ATTR_INT, 50), - CANVAS_VIEWABLE_RECT = CANVAS_ATTR(ATTR_RECT_PTR, 55), - CANVAS_WIDTH = CANVAS_ATTR(ATTR_X, 60), - CANVAS_X_PAINT_WINDOW = CANVAS_ATTR(ATTR_BOOLEAN, 65), - CANVAS_PAINTWINDOW_ATTRS = CANVAS_ATTR_LIST(ATTR_RECURSIVE, ATTR_AV, 70), - CANVAS_NO_CLIPPING = CANVAS_ATTR(ATTR_BOOLEAN, 75), - CANVAS_CMS_REPAINT = CANVAS_ATTR(ATTR_BOOLEAN, 80) -} Canvas_attribute; - - -typedef enum { - CANVAS_VIEW_PAINT_WINDOW = CANVAS_VIEW_ATTR(ATTR_OPAQUE, 1), - CANVAS_VIEW_CANVAS_WINDOW = CANVAS_VIEW_ATTR(ATTR_OPAQUE, 2) -} Canvas_view_attribute; - -typedef enum { - CANVAS_PAINT_CANVAS_WINDOW = CANVAS_PAINT_ATTR(ATTR_OPAQUE, 1), - CANVAS_PAINT_VIEW_WINDOW = CANVAS_PAINT_ATTR(ATTR_OPAQUE, 2) -} Canvas_paint_attribute; - -/* - * Structures - */ - -typedef struct -{ - Xv_openwin parent_data; - Xv_opaque private_data; -} -Xv_canvas; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_canvas_view; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_canvas_pw; - - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Variables - */ -extern Xv_pkg xv_canvas_pkg; -extern Xv_pkg xv_canvas_view_pkg; -extern Xv_pkg xv_canvas_pw_pkg; - -/* - * Functions - */ -EXTERN_FUNCTION (Event * canvas_event, (Canvas canvas_obj, Event *event)); -EXTERN_FUNCTION (Event * canvas_window_event, (Canvas canvas_obj, Event *event)); - -#endif /* ~xview_canvas_DEFINED */ diff --git a/include/xview/cms.h b/include/xview/cms.h deleted file mode 100644 index 9b7c9e5f1b8..00000000000 --- a/include/xview/cms.h +++ /dev/null @@ -1,151 +0,0 @@ -/* @(#)cms.h 20.12 89/08/17 SMI */ -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_cms_h_DEFINED -#define xview_cms_h_DEFINED - -#include - -/* - *********************************************************************** - * Include files - *********************************************************************** - */ - -#include - - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define CMS &xv_cms_pkg -#define Xv_Singlecolor Xv_singlecolor -#define CMS_NAME XV_NAME -#define XV_DEFAULT_CMS_SIZE 2 - -#define CMS_CONTROL_BG1 0 -#define CMS_CONTROL_BG2 1 -#define CMS_CONTROL_BG3 2 -#define CMS_CONTROL_HIGHLIGHT 3 -#define CMS_CONTROL_COLORS 4 - -/* - * Private #defines - */ -#define CMS_ATTR(type, ordinal) ATTR(ATTR_PKG_CMS, type, ordinal) -#define CMS_ATTR_LIST(ltype, type, ordinal) \ - CMS_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) -#define CMS_CONTROL_CMS_NAME(name, visual, color) \ - sprintf(name, "xv_ctl_%x_%d%d%d", visual, \ - color.red, color.green, color.blue); -#define CMS_STATUS(bits, status) ((bits) & (1 << (status))) - -#define CMS_STATUS_DEFAULT 0 -#define CMS_STATUS_CONTROL 1 -#define CMS_STATUS_FRAME 2 - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef Xv_opaque Cms; - -typedef enum Xv_cmstype { - XV_STATIC_CMS = 1, - XV_DYNAMIC_CMS = 2 -} Cms_type; - -typedef enum { - /* - * Public attributes. - */ - CMS_TYPE = CMS_ATTR(ATTR_ENUM, 5), - CMS_SIZE = CMS_ATTR(ATTR_INT, 10), - CMS_COLORS = CMS_ATTR(ATTR_SINGLE_COLOR_PTR, 15), - CMS_NAMED_COLORS = CMS_ATTR_LIST(ATTR_NULL, ATTR_STRING, 16), - CMS_X_COLORS = CMS_ATTR(ATTR_OPAQUE, 17), - CMS_INDEX = CMS_ATTR(ATTR_INT, 20), - CMS_COLOR_COUNT = CMS_ATTR(ATTR_INT, 25), - CMS_SCREEN = CMS_ATTR(ATTR_OPAQUE, 30), - CMS_INDEX_TABLE = CMS_ATTR(ATTR_OPAQUE, 35), - CMS_FOREGROUND_PIXEL= CMS_ATTR(ATTR_INT, 40), - CMS_BACKGROUND_PIXEL= CMS_ATTR(ATTR_INT, 45), - CMS_PIXEL = CMS_ATTR(ATTR_INT, 50), - CMS_CMS_DATA = CMS_ATTR(ATTR_OPAQUE, 55), - CMS_CONTROL_CMS = CMS_ATTR(ATTR_BOOLEAN, 60), - /* - * Private attributes. - */ - CMS_DEFAULT_CMS = CMS_ATTR(ATTR_BOOLEAN, 70), - CMS_FRAME_CMS = CMS_ATTR(ATTR_BOOLEAN, 75), - CMS_CMAP_ID = CMS_ATTR(ATTR_OPAQUE, 80), - CMS_CMAP_TYPE = CMS_ATTR(ATTR_ENUM, 85), - CMS_STATUS_BITS = CMS_ATTR(ATTR_INT, 90) -} Cms_attribute; - -typedef struct -{ - Xv_generic_struct parent_data; - Xv_opaque private_data; -} -Xv_cms_struct; - - -typedef struct xv_cmsdata -{ - Cms_type type; - short size; - short index; - short rgb_count; - unsigned char *red; - unsigned char *green; - unsigned char *blue; -} -Xv_cmsdata; - -typedef struct xv_singlecolor -{ - u_char red, green, blue; -} -Xv_singlecolor; - - -/* - * do we really need this ? check and remove. - */ -typedef struct xv_color_info -{ - Cms cms; - int cms_fg; /* CMS index of the foreground color */ - int cms_bg; /* CMS index of the background color */ -} -Xv_Color_info; - -/* - * Private typedefs - */ -typedef enum { - XV_STATIC_CMAP = 1, - XV_DYNAMIC_CMAP = 2 -} Cmap_type; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ -extern Xv_pkg xv_cms_pkg; - -#endif /* ~xview_cms_h_DEFINED */ diff --git a/include/xview/cms_grays.h b/include/xview/cms_grays.h deleted file mode 100644 index 923686323b9..00000000000 --- a/include/xview/cms_grays.h +++ /dev/null @@ -1,45 +0,0 @@ -/* @(#)cms_grays.h 20.11 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_cms_grays_DEFINED -#define xview_cms_grays_DEFINED - -/* - * Definition of the colormap segment CMS_GRAYS, a collection of grays. - */ - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define CMS_GRAYS "grays" -#define CMS_GRAYSSIZE 8 - -#define WHITE 0 -#define GRAY(i) ((BLACK)*(i)/100) -#define BLACK 7 - -#define cms_grayssetup(r,g,b) \ - { unsigned char v = 0, vi; \ - int i, gi; \ - vi = 255/BLACK; \ - for (i=BLACK-1;i>WHITE;i--) { /* Dark (small v)->light (large v) */ \ - v += vi; \ - gi = GRAY(100/8*i); \ - (r)[gi] = v; (g)[gi] = v; (b)[gi] = v; \ - } \ - (r)[WHITE] = 255; (g)[WHITE] = 255; (b)[WHITE] = 255; \ - (r)[BLACK] = 0; (g)[BLACK] = 0; (b)[BLACK] = 0; \ - } - -#endif /* ~xview_cms_grays_DEFINED */ diff --git a/include/xview/cms_mono.h b/include/xview/cms_mono.h deleted file mode 100644 index 6820808bbf4..00000000000 --- a/include/xview/cms_mono.h +++ /dev/null @@ -1,37 +0,0 @@ -/* @(#)cms_mono.h 20.11 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - * Definition of the colormap segment CMS_MONOCHROME, - * a black and white color map segment. - */ - -#ifndef xview_cms_mono_DEFINED -#define xview_cms_mono_DEFINED - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define CMS_MONOCHROME "monochrome" -#define CMS_MONOCHROMESIZE 2 - -#define WHITE 0 -#define BLACK 1 - -#define cms_monochromeload(r,g,b) \ - (r)[WHITE] = -1;(g)[WHITE] = -1;(b)[WHITE] = -1; \ - (r)[BLACK] = 0;(g)[BLACK] = 0;(b)[BLACK] = 0; - - -#endif /* ~xview_cms_mono_DEFINED */ diff --git a/include/xview/cms_rgb.h b/include/xview/cms_rgb.h deleted file mode 100644 index b9ba8a84c6b..00000000000 --- a/include/xview/cms_rgb.h +++ /dev/null @@ -1,49 +0,0 @@ -/* @(#)cms_rgb.h 20.11 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - * Definition of the colormap segment CMS_RGB, - * the collection of rgb (red-green-blue) binary combinations. - */ - -#ifndef xview_cms_rgb_DEFINED -#define xview_cms_rgb_DEFINED - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define CMS_RGB "rgb" -#define CMS_RGBSIZE 8 - -#define BLACK 0 -#define RED 1 -#define YELLOW 2 -#define GREEN 3 -#define CYAN 4 -#define BLUE 5 -#define MAGENTA 6 -#define WHITE 7 - -#define cms_rgbsetup(r,g,b) \ - (r)[BLACK] = 0; (g)[BLACK] = 0; (b)[BLACK] = 0; \ - (r)[RED] = 255; (g)[RED] = 0; (b)[RED] = 0; \ - (r)[YELLOW] = 128; (g)[YELLOW] = 128; (b)[YELLOW] = 0; \ - (r)[GREEN] = 0; (g)[GREEN] = 255; (b)[GREEN] = 0; \ - (r)[CYAN] = 0; (g)[CYAN] = 128; (b)[CYAN] = 128; \ - (r)[BLUE] = 0; (g)[BLUE] = 0; (b)[BLUE] = 255; \ - (r)[MAGENTA] = 128; (g)[MAGENTA] = 0; (b)[MAGENTA] = 128; \ - (r)[WHITE] = 255; (g)[WHITE] = 255; (b)[WHITE] = 255; - - -#endif /* ~xview_cms_rgb_DEFINED */ diff --git a/include/xview/cmsrainbow.h b/include/xview/cmsrainbow.h deleted file mode 100644 index 0e0f0540ee6..00000000000 --- a/include/xview/cmsrainbow.h +++ /dev/null @@ -1,57 +0,0 @@ -/* @(#)cmsrainbow.h 20.11 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - * Definition of the colormap segment CMS_RAINBOW, - * a small collection of colors of the rainbow. - */ - -#ifndef xview_cms_rainbow_DEFINED -#define xview_cms_rainbow_DEFINED - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define CMS_RAINBOW "rainbow" -#define CMS_RAINBOWSIZE 8 - -#define WHITE 0 -#define RED 1 -#define ORANGE 2 -#define YELLOW 3 -#define GREEN 4 -#define BLUE 5 -#define INDIGO 6 -#define VIOLET 7 - -#define cms_rainbowsetup(r,g,b) \ - (r)[WHITE] = 255; (g)[WHITE] = 255; (b)[WHITE] = 255; \ - (r)[RED] = 255; (g)[RED] = 0; (b)[RED] = 0; \ - (r)[ORANGE] = 192; (g)[ORANGE] = 64; (b)[ORANGE] = 0; \ - (r)[YELLOW] = 128; (g)[YELLOW] = 128; (b)[YELLOW] = 0; \ - (r)[GREEN] = 0; (g)[GREEN] = 255; (b)[GREEN] = 0; \ - (r)[BLUE] = 0; (g)[BLUE] = 0; (b)[BLUE] = 255; \ - /* \ - * The rule for indigo is B > R & SQRT(B**2+R**2) < .5 \ - * where 0.0<=B|R<=1.0). Trying R=.25 and B=.3. \ - */ \ - (r)[INDIGO] = 64; (g)[INDIGO] = 0; (b)[INDIGO] = 76; \ - /* \ - * The rule for violet is R > B & SQRT(B**2+R**2) > .5 \ - * where 0.0<=B|R<=1.0). Trying R=.5 and B=.7. \ - */ \ - (r)[VIOLET] = 128; (g)[VIOLET] = 0; (b)[VIOLET] = 178; - - -#endif /* ~xview_cms_rainbow_DEFINED */ diff --git a/include/xview/cursor.h b/include/xview/cursor.h deleted file mode 100644 index 01321a63281..00000000000 --- a/include/xview/cursor.h +++ /dev/null @@ -1,156 +0,0 @@ -/* @(#)cursor.h 20.34 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_cursor_DEFINED -#define xview_cursor_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include -#include -#include - -#ifdef __STDC__ -#ifndef CAT -#define CAT(a,b) a ## b -#endif -#endif -#include - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -#define CURSOR &xv_cursor_pkg - -#define CURSOR_ATTR(type, ordinal) ATTR(ATTR_PKG_CURSOR, type, ordinal) - -/* - * For Sunview 1 compatibility - */ -#define CURSOR_MAX_IMAGE_BYTES 32 /* max. # of image bytes */ -#define CURSOR_MAX_IMAGE_WORDS 16 - -#define CUR_MAXIMAGEBYTES CURSOR_MAX_IMAGE_BYTES -#define CUR_MAXIMAGEWORDS CURSOR_MAX_IMAGE_WORDS - -#define NOFONTCURSOR -1 - -/* - * OPEN LOOK Cursor character definitions - */ -/* Source characters */ -#define OLC_BASIC_PTR 0 -#define OLC_BASIC_MASK_PTR 1 -#define OLC_MOVE_PTR 2 -#define OLC_MOVE_MASK_PTR 3 -#define OLC_COPY_PTR 4 -#define OLC_COPY_MASK_PTR 5 -#define OLC_BUSY_PTR 6 -#define OLC_BUSY_MASK_PTR 7 -#define OLC_STOP_PTR 8 /* Note: Not an official OPEN LOOK cursor */ -#define OLC_STOP_MASK_PTR 9 -#define OLC_PANNING_PTR 10 -#define OLC_PANNING_MASK_PTR 11 -#define OLC_NAVIGATION_LEVEL_PTR 12 -#define OLC_NAVIGATION_LEVEL_MASK_PTR 13 - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef Xv_opaque Xv_Cursor; -typedef Xv_opaque Xv_cursor; - -typedef enum { - CURSOR_NEUTRAL = 0, - CURSOR_ACCEPT = 1, - CURSOR_REJECT = 2 -} Cursor_drag_state; - -typedef enum { - CURSOR_MOVE = 0, - CURSOR_DUPLICATE = 1 -} Cursor_drag_type; - -typedef enum { - /* - * Public Attributes - */ - CURSOR_BACKGROUND_COLOR = CURSOR_ATTR(ATTR_SINGLE_COLOR_PTR, 27), - CURSOR_DRAG_STATE = CURSOR_ATTR(ATTR_ENUM, 2), - CURSOR_DRAG_TYPE = CURSOR_ATTR(ATTR_ENUM, 3), - CURSOR_FOREGROUND_COLOR = CURSOR_ATTR(ATTR_SINGLE_COLOR_PTR, 26), - CURSOR_IMAGE = CURSOR_ATTR(ATTR_PIXRECT_PTR, 1), - CURSOR_MASK_CHAR = CURSOR_ATTR(ATTR_INT, 5), - CURSOR_OP = CURSOR_ATTR(ATTR_INT, 10), - CURSOR_SRC_CHAR = CURSOR_ATTR(ATTR_INT, 15), - CURSOR_STRING = CURSOR_ATTR(ATTR_STRING, 16), -#ifdef OW_I18N - CURSOR_STRING_WCS = CURSOR_ATTR(ATTR_WSTRING, 17), -#endif - CURSOR_XHOT = CURSOR_ATTR(ATTR_INT, 20), - CURSOR_YHOT = CURSOR_ATTR(ATTR_INT, 25), - /* - * OPEN LOOK cursors. Used as index to XV_KEY_DATA on server. - */ - CURSOR_BASIC_PTR = CURSOR_ATTR(ATTR_OPAQUE, 30), - CURSOR_MOVE_PTR = CURSOR_ATTR(ATTR_OPAQUE, 35), - CURSOR_COPY_PTR = CURSOR_ATTR(ATTR_OPAQUE, 40), - CURSOR_BUSY_PTR = CURSOR_ATTR(ATTR_OPAQUE, 45), - CURSOR_PANNING_PTR = CURSOR_ATTR(ATTR_OPAQUE, 50), - CURSOR_NAVIGATION_LEVEL_PTR = CURSOR_ATTR(ATTR_OPAQUE, 55), - CURSOR_STOP_PTR = CURSOR_ATTR(ATTR_OPAQUE, 60), - CURSOR_QUESTION_MARK_PTR = CURSOR_ATTR(ATTR_OPAQUE, 65) -} Cursor_attribute; -#define CURSOR_SHOW_CURSOR XV_SHOW - -typedef struct -{ - Xv_generic_struct parent_data; - Xv_opaque private_data; -} -Xv_cursor_struct; - - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_cursor_pkg; - -/* - * Public Functions - */ - -EXTERN_FUNCTION (void cursor_set_cursor, (Xv_object window, Xv_Cursor cursor)); - -/* - * For Sunview 1 compatibility - */ -EXTERN_FUNCTION (Xv_Cursor cursor_create, (Attr_attribute attr1, DOTDOTDOT)); -EXTERN_FUNCTION (void cursor_destroy, (Xv_Cursor cursor)); -EXTERN_FUNCTION (Xv_Cursor cursor_copy, (Xv_Cursor cursor)); -EXTERN_FUNCTION (Xv_opaque cursor_get, (Xv_Cursor cursor, Cursor_attribute attr)); -EXTERN_FUNCTION (int cursor_set, (Xv_Cursor cursor, DOTDOTDOT)); - -#endif /* xview_cursor_DEFINED */ diff --git a/include/xview/db.h b/include/xview/db.h deleted file mode 100644 index 9f5c9f587ee..00000000000 --- a/include/xview/db.h +++ /dev/null @@ -1,26 +0,0 @@ -/* @(#)db.h 50.12 91/09/14 SMI */ -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_db_h_DEFINED -#define xview_db_h_DEFINED - -#include -#include -#include -#include - -/* type converters */ -#define db_cvt_int_to_string(from_value, to_value) \ - (void) sprintf(to_value, "%d", (int)from_value) - -#define db_cvt_bool_to_string(from_value, to_value) \ - (void) strcpy(to_value, ((int)from_value) ? "True" : "False") - -#define db_cvt_char_to_string(from_value, to_value) \ - to_value[0] = (char)from_value, to_value[1] = '\0' - -#endif /* ~xview_db_h_DEFINED */ diff --git a/include/xview/defaults.h b/include/xview/defaults.h deleted file mode 100644 index 490c5239485..00000000000 --- a/include/xview/defaults.h +++ /dev/null @@ -1,155 +0,0 @@ -/* "@(#)defaults.h 20.19 91/03/27 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_defaults_DEFINED -#define xview_defaults_DEFINED - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -#define DEFAULTS_MAX_VALUE_SIZE 128 /* move this to defaults.h */ - -#ifndef Bool -#define Bool int -#endif - -#include - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef struct _default_pairs -{ - char *name; /* Name of pair */ - int value; /* Value of pair */ -} -Defaults_pairs; - - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Public Functions - * - * - * NOTE: Any returned string pointers should be considered temporary at best. - * If you want to hang onto the data, make your own private copy of the string! - */ - -/* - * defaults_exists(name, class_name) will return TRUE if a values exists in the database - * for name, and class_name. - */ - -EXTERN_FUNCTION (Bool defaults_exists, (char * name, char * class_name)); - -/* - * defaults_get_boolean(name, class_name, ddefault) will lookup name and class_name in - * the defaults database and return TRUE if the value is "True", "Yes", "On", - * "Enabled", "Set", "Activated", or "1". FALSE will be returned if the - * value is "False", "No", "Off", "Disabled", "Reset", "Cleared", - * "Deactivated", or "0". If the value is none of the above, a warning - * message will be displayed and Default will be returned. - */ -EXTERN_FUNCTION (Bool defaults_get_boolean, (char *name, char *class_name, Bool ddefault)); -/* - * defaults_get_character(name, class_name, ddefault) will lookup name and class_name in - * the defaults database and return the resulting character value. Default - * will be returned if any error occurs. - */ -EXTERN_FUNCTION (char defaults_get_character, (char *name, char *class_name, int default_char)); -/* - * defaults_get_enum(name, class_name, pairs) will lookup the value associated - * with name and class_name, scan the Pairs table and return the associated value. - * If no match is found, an error is generated and the value associated with - * last entry (i.e. the NULL entry) is returned. - */ -EXTERN_FUNCTION (int defaults_get_enum, (char *name, char *class_name, Defaults_pairs *pairs)); -/* - * defaults_get_integer(name, class_name, ddefault) will lookup name and class_name in - * the defaults database and return the resulting integer value. Default will - * be returned if any error occurs. - */ -EXTERN_FUNCTION (int defaults_get_integer, (char *name, char *class_name, int ddefault)); - -/* - * defaults_get_integer_check(name, class_name, ddefault, mininum, maximum) will - * lookup name and class_name in the defaults database and return the resulting - * integer value. If the value in the database is not between Minimum and - * Maximum (inclusive), an error message will be printed. Default will be - * returned if any error occurs. - */ -EXTERN_FUNCTION (int defaults_get_integer_check, (char *name, char *class_name, int ddefault, int minimum, int maximum)); - -/* - * defaults_get_string(name, class_name, ddefault) will lookup and return the - * null-terminated string value assocatied with name and class_name in the - * defaults database. Default will be returned if any error occurs. - */ -EXTERN_FUNCTION (char * defaults_get_string, (char *name, char *class_name, char *ddefault)); - -/* - * defaults_init_db() initializes the X11 Resource Manager. - */ -EXTERN_FUNCTION (void defaults_init_db, (void)); - -/* - * defaults_load_db(filename) will load the server database if filename is - * NULL, or the database residing in the specified filename. - */ -EXTERN_FUNCTION (void defaults_load_db, (char *filename)); - -/* - * defaults_store_db(filename) will write the defaults database to the - * specified file, and update the server Resource Manager property. - */ -EXTERN_FUNCTION (void defaults_store_db, (char *filename)); - -/* - * defaults_lookup(name, pairs) will linearly scan the Pairs data structure - * looking for Name. The value associated with Name will be returned. - * If Name can not be found in Pairs, the value assoicated with NULL will - * be returned. (The Pairs data structure must be terminated with NULL.) - */ -EXTERN_FUNCTION (int defaults_lookup, (char *name, Defaults_pairs *pairs)); - -/* - * defaults_set_character(resource, value) will set the resource to - * value. value is an character. resource is a string. - */ -EXTERN_FUNCTION (void defaults_set_character, (char *resource, int value)); - -/* - * defaults_set_character(resource, value) will set the resource to - * value. value is a integer. resource is a string. - */ -EXTERN_FUNCTION (void defaults_set_integer, (char *resource, int value)); - -/* - * defaults_set_boolean(resource, value) will set the resource to - * value. value is a Boolean. resource is a string. - */ -EXTERN_FUNCTION (void defaults_set_boolean, (char *resource, Bool value)); - -/* - * defaults_set_string(resource, value) will set the resource to - * value. value is a string. resource is a string. - */ -EXTERN_FUNCTION (void defaults_set_string, (char *resource, char *value)); - -#endif /* ~xview_defaults_DEFINED */ diff --git a/include/xview/dragdrop.h b/include/xview/dragdrop.h deleted file mode 100644 index 00ed6f079f2..00000000000 --- a/include/xview/dragdrop.h +++ /dev/null @@ -1,131 +0,0 @@ -#ifndef lint -#ifdef sccs -static char sccsid[] = "@(#)dragdrop.h 1.18 91/09/14"; -#endif -#endif - -/* - * (c) Copyright 1990 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_dnd_DEFINED -#define xview_dnd_DEFINED - -#include -#include -#include - -/* - * Private - */ - -#define DND_ATTR(type, ordinal) ATTR(ATTR_PKG_DND, type, ordinal) -#define DND_ATTR_LIST(ltype, type, ordinal) \ - DND_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - -/* - * Public - */ - -#define DRAGDROP &xv_dnd_pkg -#define DROP_SITE_ITEM &xv_drop_site_item -typedef Xv_opaque Xv_drag_drop, Drag_drop, Dnd; -typedef Xv_opaque Xv_drop_site, Drop_site_item; - -/* Error codes */ -#define DND_SUCCEEDED XV_OK -#define DND_ERROR XV_ERROR -#define DND_ILLEGAL_TARGET 2 -#define DND_TIMEOUT 3 -#define DND_SELECTION 4 -#define DND_ROOT 5 -#define DND_ABORTED 6 /* STOP key pressed */ - -/* Drag type */ -typedef enum -{ - DND_MOVE=0, - DND_COPY -} -DndDragType; - -#define DND_ENTERLEAVE (1<<0) -#define DND_MOTION (1<<1) -#define DND_DEFAULT_SITE (1<<2) - -#define DND_RECT_SITE 0 -/* XXX: Currently, only rect sites are supported. */ -#define DND_WINDOW_SITE 1 - -#define DND_VERSION 0 - -#define dnd_is_local(event) (event_flags(event) & DND_LOCAL) -#define dnd_is_forwarded(event) (event_flags(event) & DND_FORWARDED) - -/* Due to the unclear future for a standard drag and drop protocol, do not - * rely on being able to access the drop site id in the X event. It may - * not always be there. You've been warned! - */ -#define dnd_site_id(event) (event->ie_xevent->xclient.data.l[3]) - -/* Private defines */ -#define DND_MOVE_FLAG (1<<0) -#define DND_ACK_FLAG (1<<1) -#define DND_TRANSIENT_FLAG (1<<2) -#define DND_FORWARDED_FLAG (1<<3) -/* ie_flags */ -#define DND_LOCAL (1<<0) -#define DND_FORWARDED (1<<1) - - -/* - * Public attributes - */ -typedef enum { - /* Public Drag & Drop pkg attrs */ - DND_TYPE = DND_ATTR(ATTR_SHORT, 1), - DND_CURSOR = DND_ATTR(ATTR_OPAQUE, 5), - DND_X_CURSOR = DND_ATTR(ATTR_LONG, 10), - DND_ACCEPT_CURSOR = DND_ATTR(ATTR_OPAQUE, 15), - DND_ACCEPT_X_CURSOR = DND_ATTR(ATTR_LONG, 20), - DND_TIMEOUT_VALUE = DND_ATTR(ATTR_LONG, 25), - /* Private Drop Site Item attrs */ - DROP_SITE_SIZE = DND_ATTR(ATTR_INT, 95), - /* Public Drop Site Item attrs */ -#ifdef WINDOW_SITES - DROP_SITE_TYPE = DND_ATTR(ATTR_INT, 100), -#endif /* WINDOW_SITES */ - DROP_SITE_ID = DND_ATTR(ATTR_LONG, 105), - DROP_SITE_EVENT_MASK = DND_ATTR(ATTR_INT, 110), - DROP_SITE_REGION = DND_ATTR(ATTR_OPAQUE, 115), - DROP_SITE_REGION_PTR = DND_ATTR(ATTR_OPAQUE, 120), - DROP_SITE_DELETE_REGION = DND_ATTR(ATTR_OPAQUE, 125), - DROP_SITE_DELETE_REGION_PTR = DND_ATTR(ATTR_OPAQUE, 130), - DROP_SITE_DEFAULT = DND_ATTR(ATTR_BOOLEAN, 135) -} Dnd_attribute; - -typedef struct -{ - Xv_sel_owner parent_data; - Xv_opaque private_data; -} -Xv_dnd_struct, Xv_drop_site_struct; - -/* - * Public Functions - */ -extern Xv_pkg xv_dnd_pkg; -extern Xv_pkg xv_drop_site_item; -EXTERN_FUNCTION (int dnd_send_drop, (Xv_opaque object)); -EXTERN_FUNCTION (Xv_opaque dnd_decode_drop, (Xv_opaque object, Event *event)); -EXTERN_FUNCTION (void dnd_done, (Xv_opaque object)); - -/* The function xv_decode_drop is obsolete, please use the new V3 - drap and drop interface. The function is still provided for backwards - compatibility for V2 programs. -*/ -EXTERN_FUNCTION( int xv_decode_drop, ( Event *ev, char *buffer, unsigned int bsize )); - -#endif /* ~xview_dnd_DEFINED */ diff --git a/include/xview/drawable.h b/include/xview/drawable.h deleted file mode 100644 index 0cdb9bf2a3b..00000000000 --- a/include/xview/drawable.h +++ /dev/null @@ -1,70 +0,0 @@ -/* @(#)drawable.h 20.14 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_drawable_DEFINED -#define xview_drawable_DEFINED - -/* - * Interface to generic attributes of Drawable objects, where "drawable" - * is defined by X server. This is currently an implementation concept. - */ - -/* - *********************************************************************** - * Include files - *********************************************************************** - */ - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PRIVATE #defines - */ - -#define XV_DRAWABLE_OBJECT &xv_drawable_pkg - -#define DRAWABLE_ATTR(type, ordinal) ATTR(ATTR_PKG_DRAWABLE, type, ordinal) - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef Xv_opaque Xv_Drawable; -typedef Xv_opaque Xv_drawable; - -typedef enum { - /* - * Private Attributes - */ - DRAWABLE_INFO = DRAWABLE_ATTR(ATTR_OPAQUE, 100) -} Drawable_attr; - -typedef struct -{ /* For sub-pkg implementors only */ - Xv_generic_struct parent_data; - Xv_opaque private_data; -} -Xv_drawable_struct; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_drawable_pkg; - -#endif /* ~xview_drawable_DEFINED */ diff --git a/include/xview/expandname.h b/include/xview/expandname.h deleted file mode 100644 index dbf0a8f386c..00000000000 --- a/include/xview/expandname.h +++ /dev/null @@ -1,74 +0,0 @@ -/* @(#)expandname.h 20.13 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_expand_name_DEFINED -#define xview_expand_name_DEFINED - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define NONAMES ((struct namelist*) 0) - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -struct namelist -{ - unsigned count; - char *names[1]; /* LIE --it's actually names[count] - * followed by the strings themselves - */ -}; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Public Functions - * - * struct namelist * - * xv_expand_name(str) - * char *str; - * - * void - * free_namelist(nl) - * struct namelist *nl; - * - * xv_expand_name returns a pointer to a struct namelist containing - * the client's shell's idea of what its argument expands to. - * If str contains no shell metacharacters, the shell is never - * consulted, and the argument string is simply returned - * in a singleton namelist. - * - * In case of errors, xv_expand_name() writes an error message to - * stderr, and returns NONAMES. - * - * free_namelist - * The struct namelist is dynamically allocated, and should be - * freed after use by a call to free_namelist(). - */ - -EXTERN_FUNCTION (struct namelist *xv_expand_name, (char *str)); -EXTERN_FUNCTION (void free_namelist, (struct namelist *nl)); - -#endif /* ~xview_expand_name_DEFINED */ diff --git a/include/xview/font.h b/include/xview/font.h deleted file mode 100644 index 1df5b35acc5..00000000000 --- a/include/xview/font.h +++ /dev/null @@ -1,229 +0,0 @@ -/* @(#)font.h 20.32 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_font_DEFINED -#define xview_font_DEFINED - -/* - *********************************************************************** - * Include files - *********************************************************************** - */ - -#include -#ifdef OW_I18N -#include -#endif /*OW_I18N*/ - - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * Public #defines - */ -#ifndef XV_ATTRIBUTES_ONLY - -#ifdef OW_I18N -#define FONT_SET &xv_font_pkg -#define FONT FONT_SET -#else -#define FONT &xv_font_pkg -#endif /*OW_I18N*/ - - -/* - * font family/style values available - */ -#define FONT_FAMILY_DEFAULT "FONT_FAMILY_DEFAULT" -#define FONT_FAMILY_DEFAULT_FIXEDWIDTH "FONT_FAMILY_DEFAULT_FIXEDWIDTH" - -#define FONT_FAMILY_LUCIDA "FONT_FAMILY_LUCIDA" -#define FONT_FAMILY_LUCIDA_FIXEDWIDTH "FONT_FAMILY_LUCIDA_FIXEDWIDTH" - -#define FONT_FAMILY_ROMAN "FONT_FAMILY_ROMAN" -#define FONT_FAMILY_SERIF "FONT_FAMILY_SERIF" -#define FONT_FAMILY_COUR "FONT_FAMILY_COUR" -#define FONT_FAMILY_CMR "FONT_FAMILY_CMR" -#define FONT_FAMILY_GALLENT "FONT_FAMILY_GALLENT" -#define FONT_FAMILY_HELVETICA "FONT_FAMILY_HELVETICA" -#define FONT_FAMILY_OLGLYPH "FONT_FAMILY_OLGLYPH" -#define FONT_FAMILY_OLCURSOR "FONT_FAMILY_OLCURSOR" - -#ifdef OW_I18N -#define FONT_FAMILY_SANS_SERIF "FONT_FAMILY_SANS_SERIF" -#endif /*OW_I18N*/ - -#define FONT_STYLE_DEFAULT "FONT_STYLE_DEFAULT" -#define FONT_STYLE_NORMAL "FONT_STYLE_NORMAL" -#define FONT_STYLE_BOLD "FONT_STYLE_BOLD" -#define FONT_STYLE_ITALIC "FONT_STYLE_ITALIC" -#define FONT_STYLE_OBLIQUE "FONT_STYLE_OBLIQUE" -#define FONT_STYLE_BOLD_ITALIC "FONT_STYLE_BOLD_ITALIC" -#define FONT_STYLE_BOLD_OBLIQUE "FONT_STYLE_BOLD_OBLIQUE" - -#define FONT_SIZE_DEFAULT -99 -#define FONT_NO_SIZE -66 -#define FONT_NO_SCALE -55 -#define FONT_SCALE_DEFAULT -33 - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -/* - * OPEN LOOK Glyph font character definitions - */ -/* Note: Character 0 is used as a flag to indicate "no character" */ -#define OLG_VSB_ELEVATOR 1 -#define OLG_VSB_ELEVATOR_LINE_BACKWARD 2 -#define OLG_VSB_ELEVATOR_ABSOLUTE 3 -#define OLG_VSB_ELEVATOR_LINE_FORWARD 4 -#define OLG_VSB_REDUCED_ELEVATOR 5 -#define OLG_VSB_REDUCED_ELEVATOR_LINE_BACKWARD 6 -#define OLG_VSB_REDUCED_ELEVATOR_LINE_FORWARD 7 -#define OLG_VSB_ANCHOR 8 -#define OLG_VSB_ANCHOR_INVERTED 9 -#define OLG_HSB_ELEVATOR 10 -#define OLG_HSB_ELEVATOR_LINE_BACKWARD 11 -#define OLG_HSB_ELEVATOR_ABSOLUTE 12 -#define OLG_HSB_ELEVATOR_LINE_FORWARD 13 -#define OLG_HSB_REDUCED_ELEVATOR 14 -#define OLG_HSB_REDUCED_ELEVATOR_LINE_BACKWARD 15 -#define OLG_HSB_REDUCED_ELEVATOR_LINE_FORWARD 16 -#define OLG_HSB_ANCHOR 17 -#define OLG_HSB_ANCHOR_INVERTED 18 -#define OLG_MENU_PIN_OUT 19 -#define OLG_MENU_PIN_IN 20 -#define OLG_MENU_DEFAULT_PIN_OUT 21 -#define OLG_ABBREV_MENU_BUTTON 22 -#define OLG_ABBREV_MENU_BUTTON_INVERTED 23 -#define OLG_VSB_ELEVATOR_DIM_LINE_BACKWARD 166 -#define OLG_VSB_ELEVATOR_DIM_LINE_FORWARD 167 -#define OLG_VSB_ELEVATOR_INACTIVE 168 -#define OLG_HSB_ELEVATOR_DIM_LINE_BACKWARD 169 -#define OLG_HSB_ELEVATOR_DIM_LINE_FORWARD 170 -#define OLG_HSB_ELEVATOR_INACTIVE 171 -#define OLG_PANEL_MORE_TEXT 50 -#define OLG_PANEL_PULLDOWN_MENU 161 -#define OLG_PANEL_PULLRIGHT_MENU 160 - -/* - * Private #defines - */ -#define FONT_ATTR(type, ordinal) ATTR(ATTR_PKG_FONT, type, ordinal) -#define FONT_QUAD_ATTR ATTR_TYPE(ATTR_BASE_INT, 4) - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -/* - * Public types - */ -#ifndef XV_ATTRIBUTES_ONLY - -typedef Xv_opaque Xv_Font; -typedef Xv_opaque Xv_font; - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -typedef enum { - /* - * Public attributes. - */ - FONT_CHAR_WIDTH = FONT_ATTR(ATTR_CHAR, 1), /* G */ - FONT_CHAR_HEIGHT = FONT_ATTR(ATTR_CHAR, 5), /* G */ - -#ifdef OW_I18N - FONT_CHAR_WIDTH_WC = FONT_ATTR(ATTR_WCHAR, 6), /* G */ - FONT_CHAR_HEIGHT_WC = FONT_ATTR(ATTR_WCHAR, 7), /* G */ - FONT_NAMES = FONT_ATTR(ATTR_OPAQUE, 26), /* C-G */ - FONT_SET_SPECIFIER = FONT_ATTR(ATTR_STRING, 27), /* C-G */ -#endif /*OW_I18N*/ - - FONT_DEFAULT_CHAR_HEIGHT - = FONT_ATTR(ATTR_NO_VALUE, 10), /* G */ - FONT_DEFAULT_CHAR_WIDTH - = FONT_ATTR(ATTR_NO_VALUE, 15), /* G */ - FONT_FAMILY = FONT_ATTR(ATTR_STRING, 20), /* C-G */ - FONT_NAME = FONT_ATTR(ATTR_STRING, 25), /* C-G */ - FONT_RESCALE_OF = FONT_ATTR(ATTR_OPAQUE_PAIR, 30), /* F-C */ - FONT_SCALE = FONT_ATTR(ATTR_INT, 40), /* C-G */ - FONT_SIZE = FONT_ATTR(ATTR_INT, 45), /* C-G */ - FONT_SIZES_FOR_SCALE= ATTR(ATTR_PKG_FONT, - FONT_QUAD_ATTR, 50), /* C-S-G*/ - FONT_STRING_DIMS = FONT_ATTR(ATTR_OPAQUE_PAIR, 55), /* G */ - -#ifdef OW_I18N - FONT_STRING_DIMS_WC = FONT_ATTR(ATTR_OPAQUE_PAIR, 56), /* G */ -#endif /*OW_I18N*/ - - FONT_STYLE = FONT_ATTR(ATTR_STRING, 60), /* C-G */ - FONT_TYPE = FONT_ATTR(ATTR_ENUM, 65), /* C-S-G */ - FONT_PIXFONT = FONT_ATTR(ATTR_OPAQUE, 67), /* G */ - FONT_INFO = FONT_ATTR(ATTR_OPAQUE, 80), /* G */ - -#ifdef OW_I18N - FONT_LOCALE = FONT_ATTR(ATTR_STRING, 68), /* C-G */ - FONT_SET_ID = FONT_ATTR(ATTR_OPAQUE, 69), /* G */ -#endif /*OW_I18N*/ - - /* - * Private attributes. - */ - FONT_HEAD = FONT_ATTR(ATTR_INT, 70), /* Key */ - FONT_UNKNOWN_HEAD = FONT_ATTR(ATTR_INT, 75) /* Key */ - -} Font_attribute; - -typedef enum { - FONT_TYPE_TEXT = 0, - FONT_TYPE_CURSOR = 1, - FONT_TYPE_GLYPH = 2 -} Font_type; - -#ifndef XV_ATTRIBUTES_ONLY - -/* - * Got rid of pixfont struct - * It now exists in the private part where it will be allocated on demand - */ -typedef struct -{ - Xv_generic_struct parent_data; - Xv_opaque private_data; - /* - Xv_embedding embedding_data; - char *pixfont[2+(5*256)]; - */ -} -Xv_font_struct; - -typedef struct -{ - int width, height; -} -Font_string_dims; - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -#ifndef XV_ATTRIBUTES_ONLY -extern Xv_pkg xv_font_pkg; -#endif /* ~XV_ATTRIBUTES_ONLY */ - -#endif /* ~xview_font_DEFINED */ diff --git a/include/xview/frame.h b/include/xview/frame.h deleted file mode 100644 index 96851ff7071..00000000000 --- a/include/xview/frame.h +++ /dev/null @@ -1,268 +0,0 @@ -/* @(#)frame.h 20.67 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_frame_DEFINED -#define xview_frame_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define FRAME FRAME_BASE -#define FRAME_BASE &xv_frame_base_pkg -#define FRAME_CMD &xv_frame_cmd_pkg -#define FRAME_PROPS FRAME_CMD -#define FRAME_HELP &xv_frame_help_pkg -#define FRAME_CLASS &xv_frame_class_pkg - -#define ROOT_FRAME ((Frame)0) - -#define FRAME_SHOW_HEADER FRAME_SHOW_LABEL -#define FRAME_FOCUS_UP_WIDTH 13 -#define FRAME_FOCUS_UP_HEIGHT 13 -#define FRAME_FOCUS_RIGHT_WIDTH 13 -#define FRAME_FOCUS_RIGHT_HEIGHT 13 - -/* - * Utility Macros - */ - -#define frame_fit_all(frame) \ -{ \ - Xv_Window win; \ - int n = 0; \ - while (win = window_get(frame, FRAME_NTH_SUBWINDOW, n++, 0))\ - window_fit(win); \ - window_fit(frame); \ -} - -#define frame_done_proc(frame) \ - (((void (*)())window_get(frame, FRAME_DONE_PROC))(frame)) - -#define frame_default_done_proc(frame) \ - (((void (*)())window_get(frame, FRAME_DEFAULT_DONE_PROC))(frame)) - -/* - * PRIVATE #defines - */ - -#define FRAME_ATTR(type, ordinal) ATTR(ATTR_PKG_FRAME, type, ordinal) -#define FRAME_ATTR_LIST(ltype, type, ordinal) \ - FRAME_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - -/* - * BUG: maybe these should be attributes - */ - - -/* - * width of border around a frame - */ -#define FRAME_BORDER_WIDTH (0) -/* - * width of border around a subwindow - */ -#define FRAME_SUBWINDOW_SPACING (FRAME_BORDER_WIDTH) - - -/* - * PUBLIC #defines - * For SunView 1 Compatibility - */ - -#define FRAME_TYPE ATTR_PKG_FRAME - -#define FRAME_ARGS XV_INIT_ARGS -#define FRAME_ARGC_PTR_ARGV XV_INIT_ARGC_PTR_ARGV -#define FRAME_CMDLINE_HELP_PROC XV_USAGE_PROC -#define FRAME_LABEL XV_LABEL -#ifdef OW_I18N -#define FRAME_LABEL_WCS XV_LABEL_WCS -#endif -#define FRAME_OPEN_RECT WIN_RECT - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -typedef Xv_opaque Frame; -typedef Xv_opaque Frame_cmd; -typedef Xv_opaque Frame_props; -typedef Xv_opaque Frame_help; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_frame_class; - -typedef struct -{ - Xv_frame_class parent_data; - Xv_opaque private_data; -} -Xv_frame_base; - -typedef Xv_frame_base Xv_frame_cmd; -typedef Xv_frame_base Xv_frame_props; -typedef Xv_frame_base Xv_frame_help; - -typedef enum { - FRAME_FOCUS_UP, - FRAME_FOCUS_RIGHT -} Frame_focus_direction; - -typedef enum { /* do not change this order */ - FRAME_CMD_PIN_OUT, - FRAME_CMD_PIN_IN -} Frame_cmd_pin_state; - -typedef struct frame_accelerator -{ - short code; /* = event->ie_code */ - KeySym keysym; /* X keysym */ - void (*notify_proc)(); /* accelerator notify proc */ - Xv_opaque data; /* opaque data handle */ - struct frame_accelerator *next; -} -Frame_accelerator; - -typedef enum { - /* - * PUBLIC attributes - */ - FRAME_BACKGROUND_COLOR = FRAME_ATTR(ATTR_SINGLE_COLOR_PTR, 5), - FRAME_BUSY = FRAME_ATTR(ATTR_BOOLEAN, 10), - FRAME_CLOSED = FRAME_ATTR(ATTR_BOOLEAN, 15), - FRAME_CLOSED_RECT = FRAME_ATTR(ATTR_RECT_PTR, 20), - FRAME_WM_COMMAND_STRINGS= FRAME_ATTR_LIST(ATTR_NULL, ATTR_STRING, 21), - FRAME_WM_COMMAND_ARGC_ARGV - = FRAME_ATTR(ATTR_INT_PAIR, 22), - FRAME_WM_COMMAND_ARGV = FRAME_ATTR(ATTR_OPAQUE, 23), - FRAME_WM_COMMAND_ARGC = FRAME_ATTR(ATTR_INT, 24), - FRAME_CMD_PANEL = FRAME_ATTR(ATTR_OPAQUE, 25), - FRAME_CURRENT_RECT = FRAME_ATTR(ATTR_RECT_PTR, 35), - FRAME_OLD_RECT = FRAME_ATTR(ATTR_RECT_PTR, 36), - FRAME_DEFAULT_DONE_PROC = FRAME_ATTR(ATTR_FUNCTION_PTR, 40), - FRAME_DONE_PROC = FRAME_ATTR(ATTR_FUNCTION_PTR, 45), - FRAME_FOCUS_WIN = FRAME_ATTR(ATTR_INT_PAIR, 165), - FRAME_FOCUS_DIRECTION = FRAME_ATTR(ATTR_ENUM, 170), - FRAME_FOREGROUND_COLOR = FRAME_ATTR(ATTR_SINGLE_COLOR_PTR, 50), - FRAME_ICON = FRAME_ATTR(ATTR_OPAQUE, 55), - FRAME_INHERIT_COLORS = FRAME_ATTR(ATTR_BOOLEAN, 60), - FRAME_LEFT_FOOTER = FRAME_ATTR(ATTR_STRING, 65), -#ifdef OW_I18N - FRAME_LEFT_FOOTER_WCS = FRAME_ATTR(ATTR_WSTRING, 66), -#endif - FRAME_NEXT_PANE = FRAME_ATTR(ATTR_NO_VALUE, 67), - FRAME_NO_CONFIRM = FRAME_ATTR(ATTR_BOOLEAN, 70), - FRAME_NTH_SUBFRAME = FRAME_ATTR(ATTR_INT, 75), - FRAME_NTH_SUBWINDOW = FRAME_ATTR(ATTR_INT, 80), - FRAME_PREVIOUS_ELEMENT = FRAME_ATTR(ATTR_NO_VALUE, 81), - FRAME_PREVIOUS_PANE = FRAME_ATTR(ATTR_NO_VALUE, 82), - FRAME_PROPERTIES_PROC = FRAME_ATTR(ATTR_FUNCTION_PTR, 85), - FRAME_CMD_PUSHPIN_IN = FRAME_ATTR(ATTR_BOOLEAN, 105), - FRAME_CMD_DEFAULT_PIN_STATE = FRAME_ATTR(ATTR_ENUM, 106), - FRAME_CMD_PIN_STATE = FRAME_ATTR(ATTR_ENUM, 107), - FRAME_RIGHT_FOOTER = FRAME_ATTR(ATTR_STRING, 115), -#ifdef OW_I18N - FRAME_RIGHT_FOOTER_WCS = FRAME_ATTR(ATTR_WSTRING, 116), -#endif - FRAME_SHOW_FOOTER = FRAME_ATTR(ATTR_BOOLEAN, 125), - FRAME_SHOW_RESIZE_CORNER = FRAME_ATTR(ATTR_BOOLEAN, 128), - FRAME_SHOW_LABEL = FRAME_ATTR(ATTR_BOOLEAN, 130), - FRAME_GROUP_LEADER = FRAME_ATTR(ATTR_BOOLEAN, 135), - FRAME_MIN_SIZE = FRAME_ATTR(ATTR_INT_PAIR, 136), - FRAME_MAX_SIZE = FRAME_ATTR(ATTR_INT_PAIR, 137), - /* - * PRIVATE attributes - */ -#ifdef OW_I18N - FRAME_INPUT_WINDOW = FRAME_ATTR(ATTR_OPAQUE, 139), -#endif /* OW_I18N */ - FRAME_NEXT_CHILD = FRAME_ATTR(ATTR_OPAQUE, 140), - FRAME_PREVIOUS_CHILD = FRAME_ATTR(ATTR_OPAQUE, 142), - FRAME_SCALE_STATE = FRAME_ATTR(ATTR_INT, 145), - FRAME_SUBWINDOWS_ADJUSTABLE - = FRAME_ATTR(ATTR_BOOLEAN, 150), - FRAME_COUNT = FRAME_ATTR(ATTR_INT, 160), - FRAME_FOCUS_UP_IMAGE = FRAME_ATTR(ATTR_OPAQUE, 175), - FRAME_FOCUS_RIGHT_IMAGE = FRAME_ATTR(ATTR_OPAQUE, 180), - FRAME_FOCUS_GC = FRAME_ATTR(ATTR_OPAQUE, 185), - FRAME_ORPHAN_WINDOW = FRAME_ATTR(ATTR_INT, 190), - FRAME_FOOTER_WINDOW = FRAME_ATTR(ATTR_BOOLEAN, 195), -#ifdef OW_I18N - FRAME_IMSTATUS_WINDOW = FRAME_ATTR(ATTR_BOOLEAN, 196), -#endif - FRAME_ACCELERATOR = FRAME_ATTR(ATTR_INT_TRIPLE, 200), - FRAME_X_ACCELERATOR = FRAME_ATTR(ATTR_INT_TRIPLE, 205), -#ifdef OW_I18N - FRAME_LEFT_IMSTATUS_WCS = FRAME_ATTR(ATTR_WSTRING, 210), - FRAME_LEFT_IMSTATUS = FRAME_ATTR(ATTR_STRING, 215), - FRAME_RIGHT_IMSTATUS_WCS= FRAME_ATTR(ATTR_WSTRING, 220), - FRAME_RIGHT_IMSTATUS = FRAME_ATTR(ATTR_STRING, 225), - FRAME_SHOW_IMSTATUS = FRAME_ATTR(ATTR_BOOLEAN, 230), - FRAME_CMD_POINTER_WARP = FRAME_ATTR(ATTR_BOOLEAN, 240), -#endif - FRAME_COMPOSE_STATE = FRAME_ATTR(ATTR_BOOLEAN, 235) - -} Frame_attribute; - -#define FRAME_PROPS_PUSHPIN_IN FRAME_CMD_PUSHPIN_IN -#define FRAME_PROPS_PANEL FRAME_CMD_PANEL - -/* - * values for scale state - */ -#define Frame_rescale_state Window_rescale_state -#define FRAME_SCALE_SMALL WIN_SCALE_SMALL -#define FRAME_SCALE_MEDIUM WIN_SCALE_MEDIUM -#define FRAME_SCALE_LARGE WIN_SCALE_LARGE -#define FRAME_SCALE_EXTRALARGE WIN_SCALE_EXTRALARGE - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_frame_class_pkg; -extern Xv_pkg xv_frame_base_pkg; -extern Xv_pkg xv_frame_cmd_pkg; -extern Xv_pkg xv_frame_props_pkg; -extern Xv_pkg xv_frame_help_pkg; - -/* - * XView Private functions - */ -EXTERN_FUNCTION (void frame_cmdline_help, (char *name)); -EXTERN_FUNCTION (void frame_grant_extend_to_edge, (Frame frame, int to_right)); -EXTERN_FUNCTION (void frame_kbd_use, (Frame frame, Xv_Window sw, Xv_Window pw)); -EXTERN_FUNCTION (void frame_kbd_done, (Frame frame, Xv_Window sw)); - -#endif /* xview_frame_DEFINED */ - diff --git a/include/xview/fullscreen.h b/include/xview/fullscreen.h deleted file mode 100644 index 3270d4739eb..00000000000 --- a/include/xview/fullscreen.h +++ /dev/null @@ -1,144 +0,0 @@ -/* @(#)fullscreen.h 20.28 91/09/14 */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_fullscreen_DEFINED -#define xview_fullscreen_DEFINED - -#include /* needed for SV1 compat routines */ -#include /* needed for SV1 compat routines */ -#include /* needed for SV1 compat routines */ -#include /* needed for SV1 compat routines */ -#include - -/* - ********************************************************************** - * PUBLIC #defines - ********************************************************************** - */ - -#ifndef XV_ATTRIBUTES_ONLY -#define FULLSCREEN &xv_fullscreen_pkg -#endif /* ~XV_ATTRIBUTES_ONLY */ - -/* - * PRIVATE #defines - */ - -#define FULLSCREEN_ATTR(type, ordinal) ATTR(ATTR_PKG_FULLSCREEN, type, ordinal) - -/* - * ********************************************************************** - * Typedefs, Enumerations, and Structures - * ********************************************************************** - */ - -#ifndef XV_ATTRIBUTES_ONLY - -/* - * Public typedefs - */ - -typedef Xv_opaque Fullscreen; - -/* - * Public structures - */ - -/* - * struct fullscreen is For SunView 1 fullscreen compatibility only - */ - -struct fullscreen -{ - int fs_windowfd; - Rect fs_screenrect; - Xv_Window fs_rootwindow; - Inputmask inputmask; /* current mask */ - Xv_Cursor cursor; /* current cursor */ -}; - -typedef struct -{ - Xv_generic_struct parent; - Xv_opaque private_data; - Xv_embedding embedding_data; - struct fullscreen fullscreen_struct; -} -Xv_fullscreen; - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -typedef enum { - FULLSCREEN_SYNCHRONOUS = 0, - FULLSCREEN_ASYNCHRONOUS = 1 -} Fullscreen_grab_mode; - -typedef enum { - /* - * Public Attributes - */ - FULLSCREEN_CURSOR_WINDOW = FULLSCREEN_ATTR(ATTR_OPAQUE, 5), /* CG- */ - FULLSCREEN_INPUT_WINDOW = FULLSCREEN_ATTR(ATTR_OPAQUE, 10), /* CG- */ - FULLSCREEN_PAINT_WINDOW = FULLSCREEN_ATTR(ATTR_OPAQUE, 15), /* CG- */ - FULLSCREEN_RECT = FULLSCREEN_ATTR(ATTR_NO_VALUE, 20), /* -G- */ - FULLSCREEN_SYNC = FULLSCREEN_ATTR(ATTR_INT, 25), /* CGS */ - FULLSCREEN_ALLOW_SYNC_EVENT = FULLSCREEN_ATTR(ATTR_NO_VALUE, 30), /* --S */ - FULLSCREEN_ALLOW_EVENTS = FULLSCREEN_ATTR(ATTR_OPAQUE, 32), /* --S */ - FULLSCREEN_GRAB_KEYBOARD = FULLSCREEN_ATTR(ATTR_BOOLEAN, 35), /* CGS */ - FULLSCREEN_GRAB_POINTER = FULLSCREEN_ATTR(ATTR_BOOLEAN, 40), /* CGS */ - FULLSCREEN_GRAB_SERVER = FULLSCREEN_ATTR(ATTR_BOOLEAN, 45), /* CGS */ - FULLSCREEN_KEYBOARD_GRAB_PTR_MODE = - FULLSCREEN_ATTR(ATTR_OPAQUE, 50), /* CGS */ - FULLSCREEN_KEYBOARD_GRAB_KBD_MODE = - FULLSCREEN_ATTR(ATTR_OPAQUE, 55), /* CGS */ - FULLSCREEN_POINTER_GRAB_PTR_MODE = - FULLSCREEN_ATTR(ATTR_OPAQUE, 60), /* CGS */ - FULLSCREEN_POINTER_GRAB_KBD_MODE = - FULLSCREEN_ATTR(ATTR_OPAQUE, 65), /* CGS */ - FULLSCREEN_OWNER_EVENTS = FULLSCREEN_ATTR(ATTR_BOOLEAN, 60) /* CGS */ -} Fullscreen_attr; - -#define FULLSCREEN_ALLOW_ASYNC_EVENTS FULLSCREEN_SYNC, FALSE /* --S */ - -/* - * ********************************************************************** - * - * - * Globals ********************************************************************** - * - */ - -#ifndef XV_ATTRIBUTES_ONLY - -/* - * PUBLIC variables - */ - -extern Xv_pkg xv_fullscreen_pkg; - -/* - * PUBLIC functions - */ - -EXTERN_FUNCTION (struct fullscreen *fullscreen_init, (Xv_Window window)); -EXTERN_FUNCTION (int fullscreen_set_cursor, (struct fullscreen *fs, Xv_Cursor cursor)); -EXTERN_FUNCTION (int fullscreen_set_inputmask, (struct fullscreen *fs, Inputmask *im)); -EXTERN_FUNCTION (int fullscreen_destroy, (struct fullscreen *fs)); - -/* - * Global variables for debugging purposes - */ -extern int fullscreendebug; -extern int fullscreendebugserver; -extern int fullscreendebugptr; -extern int fullscreendebugkbd; - - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -#endif /* ~xview_fullscreen_DEFINED */ diff --git a/include/xview/generic.h b/include/xview/generic.h deleted file mode 100644 index 424dacfefef..00000000000 --- a/include/xview/generic.h +++ /dev/null @@ -1,304 +0,0 @@ -/* @(#)generic.h 20.40 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_generic_DEFINED -#define xview_generic_DEFINED - -/* - * Generic attributes fall into two classes: - * (1) Truly generic, implemented by attr_xxx.o or generic.o, use the - * package ATTR_PKG_GENERIC, shared with attr.h. - * (2) Common but not truly generic, implemented by .o's spread - * across many sub-systems, use the package ATTR_PKG_SV, shared with xview.h. - * Many of these common attributes pertain to server properties and thus only - * apply to objects with a window server component. - * - * Implementation dependent notes on generic X attributes: - * XV_XNAME has the format - * "::". - * XV_DEVICE_NUMBER is the XID of the underlying X object. XV_XID is - * provided when a piece of code wants to emphasize that the "X id" is what - * is needed, rather than an abstract "tree link". - * Most of these attributes are only supported on Drawable objects, - * but some, like XV_XID, are supported by all objects that have direct - * underlying X components, e.g. Fonts. - */ - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define XV_GENERIC_OBJECT &xv_generic_pkg - -/* XV_COPY is "magic" package xv_create checks for to distinguish - * creation of a new object from creation of a copy of an existing object. - */ -#define XV_COPY (Xv_pkg *)1 - -/* - * Accelerator for XV_HELP and HELP_STRING_FILENAME - */ -#define XV_HELP_DATA XV_KEY_DATA, XV_HELP -#define HELP_STRING_FILENAME XV_KEY_DATA, XV_HELP_STRING_FILENAME - -#define XV_XID XV_DEVICE_NUMBER - -#define XV_DUMMY_WINDOW 0x77777777 - -/* - * Focus Client Rank. Value is of type Xv_focus_rank. - * Referred to in the Mouseless Model Specification as "Focus Client Classes". - * Transient and Limited focus classes are Window Manager objects. - * An Ordinary Focus client has an XV_FOCUS_RANK of XV_FOCUS_SECONDARY. - * A First Class Focus client has an XV_FOCUS_RANK of XV_FOCUS_PRIMARY. - */ -#define XV_FOCUS_RANK XV_KEY_DATA, XV_FOCUS_RANK_KEY - -#define XV_RC_SPECIAL 0x20000 -#define XV_RESET_REF_COUNT XV_REF_COUNT, XV_RC_SPECIAL -#define XV_INCREMENT_REF_COUNT XV_REF_COUNT, XV_RC_SPECIAL+1 -#define XV_DECREMENT_REF_COUNT XV_REF_COUNT, XV_RC_SPECIAL-1 - - -/* - * PRIVATE #defines - */ -#define XV_ATTR(type, ordinal) ATTR(ATTR_PKG_SV, type, ordinal) - -#define XV_ATTR_LIST(ltype, type, ordinal) \ - XV_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef enum { - XV_FOCUS_SECONDARY = 0, /* default value (a.k.a., Ordinary Focus) */ - XV_FOCUS_PRIMARY = 1 /* a.k.a., First Class Focus */ -} Xv_focus_rank; - -/* - * WARNING: GENERIC_ATTR shared with attr.h (which claims [0..64)) - */ -typedef enum { - /* - * PUBLIC and Generic - */ - /* - * For "contexts": key & data (& optional destroy for data) - */ - XV_KEY_DATA = GENERIC_ATTR(ATTR_INT_PAIR, 64), - XV_KEY_DATA_COPY_PROC = GENERIC_ATTR(ATTR_OPAQUE_PAIR, 65), - XV_KEY_DATA_REMOVE = GENERIC_ATTR(ATTR_INT, 66), /* -S- */ - XV_KEY_DATA_REMOVE_PROC = GENERIC_ATTR(ATTR_OPAQUE_PAIR, 67), - /* - * For "reference count" on shared objects, e.g. fonts & menus - */ - XV_REF_COUNT = GENERIC_ATTR(ATTR_INT, 68), - /* - * Type of object - */ - XV_TYPE = GENERIC_ATTR(ATTR_OPAQUE, 69), /* --G */ - XV_IS_SUBTYPE_OF = GENERIC_ATTR(ATTR_OPAQUE, 70), /* --G */ - /* - * Miscellaneous - */ - XV_LABEL = GENERIC_ATTR(ATTR_STRING, 71), - XV_NAME = GENERIC_ATTR(ATTR_STRING, 72), - XV_STATUS = GENERIC_ATTR(ATTR_INT, 73), - XV_STATUS_PTR = GENERIC_ATTR(ATTR_OPAQUE, 74), - XV_HELP = GENERIC_ATTR(ATTR_STRING, 80), - XV_HELP_STRING_FILENAME = GENERIC_ATTR(ATTR_STRING, 82), - XV_SHOW = GENERIC_ATTR(ATTR_BOOLEAN, 81), -#ifdef OW_I18N - XV_LABEL_WCS = GENERIC_ATTR(ATTR_WSTRING, 164), - XV_NAME_WCS = GENERIC_ATTR(ATTR_WSTRING, 161), - XV_HELP_WCS = GENERIC_ATTR(ATTR_WSTRING, 162), - XV_HELP_STRING_FILENAME_WCS - = GENERIC_ATTR(ATTR_WSTRING, 163), -#endif /* OW_I18N */ - /* - * Required by package implementations, used only by xv_create - */ - XV_COPY_OF = GENERIC_ATTR(ATTR_OPAQUE, 75), /* -S- */ - XV_END_CREATE = GENERIC_ATTR(ATTR_NO_VALUE, 76), /* -S- */ - /* - * To simplify SunView1.X compatibility - */ - XV_SELF = GENERIC_ATTR(ATTR_OPAQUE, 77), /* --G */ - /* - * Managing (usually containing) object - */ - XV_OWNER = GENERIC_ATTR(ATTR_OPAQUE, 78), - /* - * Required by package implementations, used only by xv_find - */ - XV_AUTO_CREATE = GENERIC_ATTR(ATTR_INT, 79), /* C-- */ - /* - * PUBLIC but only Common - */ - /* - * For layout - */ - XV_FONT = XV_ATTR(ATTR_OPAQUE, 64), - XV_MARGIN = XV_ATTR(ATTR_INT, 65), - XV_LEFT_MARGIN = XV_ATTR(ATTR_INT, 66), - XV_TOP_MARGIN = XV_ATTR(ATTR_INT, 67), - XV_RIGHT_MARGIN = XV_ATTR(ATTR_INT, 68), - XV_BOTTOM_MARGIN = XV_ATTR(ATTR_INT, 69), - /* - * Origin is usually parent's most upper-left coord inside margins - */ - XV_X = XV_ATTR(ATTR_X, 70), - XV_Y = XV_ATTR(ATTR_Y, 71), - XV_WIDTH = XV_ATTR(ATTR_X, 72), - XV_HEIGHT = XV_ATTR(ATTR_Y, 73), - XV_RECT = XV_ATTR(ATTR_RECT_PTR, 74), - /* - * Server specific or dependent - */ - XV_XNAME = XV_ATTR(ATTR_STRING, 96), /* C-G */ - XV_DEVICE_NUMBER = XV_ATTR(ATTR_LONG, 97), /* C-G */ - XV_ROOT = XV_ATTR(ATTR_OPAQUE, 98), /* --G */ - XV_VISUAL = XV_ATTR(ATTR_OPAQUE, 125), /* C-G */ - XV_VISUAL_CLASS = XV_ATTR(ATTR_INT, 117), /* C-G */ - XV_DEPTH = XV_ATTR(ATTR_INT, 126), /* C-G */ - XV_DISPLAY = XV_ATTR(ATTR_OPAQUE, 110), /* --G */ - XV_SCREEN = XV_ATTR(ATTR_OPAQUE, 116), /* --G */ - /* - * Mouseless Model support - */ - XV_FOCUS_ELEMENT = XV_ATTR(ATTR_INT, 118), /* -S- */ - XV_FOCUS_RANK_KEY = XV_ATTR(ATTR_ENUM, 119), /* CSG */ - - /* - * Added to support the Xrm resource database - */ - XV_USE_DB = XV_ATTR_LIST(ATTR_RECURSIVE, ATTR_AV, 120), - XV_INSTANCE_NAME = XV_ATTR(ATTR_STRING, 125), - XV_INSTANCE_QLIST = XV_ATTR(ATTR_OPAQUE, 130), - XV_QUARK = XV_ATTR(ATTR_OPAQUE, 135), - XV_USE_INSTANCE_RESOURCES=XV_ATTR(ATTR_OPAQUE, 140), - -#ifdef OW_I18N - /* - * The I18N Level 4 attribute XV_IM goes here: - */ - XV_IM = XV_ATTR(ATTR_OPAQUE, 150), -#endif /* OW_I18N */ - - /* - * Added to support locale announcement - */ - XV_LC_BASIC_LOCALE = XV_ATTR(ATTR_STRING, 155), - XV_LC_DISPLAY_LANG = XV_ATTR(ATTR_STRING, 160), - XV_LC_INPUT_LANG = XV_ATTR(ATTR_STRING, 165), - XV_LC_NUMERIC = XV_ATTR(ATTR_STRING, 170), - XV_LC_TIME_FORMAT = XV_ATTR(ATTR_STRING, 175), - XV_LOCALE_DIR = XV_ATTR(ATTR_STRING, 180), - XV_USE_LOCALE = XV_ATTR(ATTR_BOOLEAN, 185), - - /* - * PRIVATE now, but ... - */ - XV_GC = XV_ATTR(ATTR_OPAQUE, 113) /* --G */ -} Xv_generic_attr; - -/* - * Generic package definition - */ -typedef struct -{ - Xv_base parent_data; - Xv_opaque private_data; -} -Xv_generic_struct; - -typedef enum { - - /* XXX: This is a hack to support V3 applications dropping on V2 apps. - * You ask what does XV_INIT_* have to do with dnd, well...We needed - * some way to tell the difference between a V2 client using V3 - * shared libs and a V3 client using V3 shared libs. By changing - * the value of the attr XV_INIT_ARGS{_PTR_ARGV} we could detect this. - * A V2 client using V3 libs will still have the old attr values - * compiled into them, while V3 client compiled under V3 header files - * will use the new value for these attrs. It's a hack, but it works. - * We can remove this for V4 as we only need to support one release - * back. Everything marked with DND_HACK can be removed generic.h - * xv_init.c, frame_init.c - */ - - /* XXX: This is a hack to support the navigator which shipped on - * pre-V3 FCS. The navigator has a bug in which it expects XView to - * send a WIN_RESIZE event when certain window objects are created. - * XView no longer sends bogus WIN_RESIZE events. This breaks the - * navigator. This hack can be removed in a future release of XView. - */ - - /* Private Attributes */ - - /* DND_HACK begin */ - /* The following two attributes are private to XView. Do not use them as - * they will be removed in a future release of the toolkit. - */ - XV_INIT_ARGS_FOR_DND = XV_ATTR(ATTR_INT_PAIR, 3), - XV_INIT_ARGC_PTR_ARGV_FOR_DND = XV_ATTR(ATTR_INT_PAIR, 6), /* -S- */ - /* DND_HACK end */ - - /* NAV_HACK begin */ - /* The following two attributes are private to XView. Do not use them as - * they will be removed in a future release of the toolkit. - */ - XV_INIT_ARGS_NAV = XV_ATTR(ATTR_INT_PAIR, 4), - XV_INIT_ARGC_PTR_ARGV_NAV = XV_ATTR(ATTR_INT_PAIR, 7), /* -S- */ - /* NAV_HACK end */ - - /* Public Attributes */ - - XV_INIT_ARGS = XV_ATTR(ATTR_INT_PAIR, 5), - XV_INIT_ARGC_PTR_ARGV = XV_ATTR(ATTR_INT_PAIR, 8), /* -S- */ - XV_USAGE_PROC = XV_ATTR(ATTR_FUNCTION_PTR, 9), /* -S- */ - XV_ERROR_PROC = XV_ATTR(ATTR_FUNCTION_PTR, 12), - XV_X_ERROR_PROC = XV_ATTR(ATTR_FUNCTION_PTR, 15) -} Xv_attr; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_generic_pkg; - -/* - * PUBLIC functions - */ - -EXTERN_FUNCTION (Xv_object xv_init, (Attr_attribute attr1, DOTDOTDOT)); -EXTERN_FUNCTION (Attr_attribute xv_unique_key, (void)); - -#endif /* ~xview_generic_DEFINED */ diff --git a/include/xview/icon.h b/include/xview/icon.h deleted file mode 100644 index a06159a8536..00000000000 --- a/include/xview/icon.h +++ /dev/null @@ -1,108 +0,0 @@ -/* @(#)icon.h 20.13 90/03/13 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_icon_DEFINED -#define xview_icon_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define ICON &xv_icon_pkg -#define ICON_TYPE ATTR_PKG_ICON - -#define ICON_WIDTH XV_WIDTH -#define ICON_HEIGHT XV_HEIGHT -#define ICON_LABEL XV_LABEL -#ifdef OW_I18N -#define ICON_LABEL_WCS XV_LABEL_WCS -#endif -#define ICON_FONT XV_FONT - -#define icon_attr_next(attr) (Icon_attribute *)attr_next((Xv_opaque *)attr) - -#define ICON_DEFAULT_WIDTH 64 -#define ICON_DEFAULT_HEIGHT 64 - - -/* - * PRIVATE #defines - */ - -#define ICON_ATTR(type, ordinal) ATTR(ATTR_PKG_ICON, type, ordinal) -#define ICON_ATTR_LIST(ltype, type, ordinal) \ - ICON_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - -/* - *********************************************************************** - * Typedefs, enumerations, and structures - *********************************************************************** - */ - -typedef Xv_opaque Icon; - -typedef enum { - ICON_IMAGE = ICON_ATTR(ATTR_PIXRECT_PTR, 5), - ICON_IMAGE_RECT = ICON_ATTR(ATTR_RECT_PTR, 10), - ICON_LABEL_RECT = ICON_ATTR(ATTR_RECT_PTR, 15), - ICON_TRANSPARENT = ICON_ATTR(ATTR_BOOLEAN, 20), - ICON_MASK_IMAGE = ICON_ATTR(ATTR_PIXRECT_PTR, 25), - ICON_TRANSPARENT_LABEL = ICON_ATTR(ATTR_STRING, 30) -#ifdef OW_I18N - , - ICON_TRANSPARENT_LABEL_WCS - = ICON_ATTR(ATTR_WSTRING, 35) -#endif /* OW_I18N */ -} Icon_attribute; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_icon; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Variables - */ -extern Xv_pkg xv_icon_pkg; - -/* - * PUBLIC Functions - * For Sunview 1 Compatibility - */ - -EXTERN_FUNCTION (Icon icon_create, (Attr_attribute attr1, DOTDOTDOT)); -EXTERN_FUNCTION (Xv_opaque icon_get, (Icon icon_public, Icon_attribute attr)); -EXTERN_FUNCTION (int icon_set, (Icon icon, DOTDOTDOT)); -EXTERN_FUNCTION (int icon_destroy, (Icon icon)); -EXTERN_FUNCTION (void icon_display, (Icon icon, int x, int y)); - -#endif /* ~xview_icon_DEFINED */ diff --git a/include/xview/icon_load.h b/include/xview/icon_load.h deleted file mode 100644 index e65cae9f778..00000000000 --- a/include/xview/icon_load.h +++ /dev/null @@ -1,170 +0,0 @@ -/* @(#)icon_load.h 20.16 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_icon_load_DEFINED -#define xview_icon_load_DEFINED - -#include - -#ifdef notdef -/* - * The format of an ASCII representation of an icon file is defined by: - * ::=
- *
::= - * ::= /* Format_version=1 - * ::= */ -/* ::= -* ::= | -* ::= Depth=1 -* | Height= -* | Width= -* | Valid_bits_per_item= -* ::= -* -* ::= -* | , -* -* Default values for header parameters are: -* Depth 1 -* Height 64 -* Width 64 -* Valid_bits_per_item 16 -* -* A sample icon file follows: -* -* Format_version=1, Width=16, Height=16, Depth=1, Valid_bits_per_item=16 -* This file is the template for all images in the cursor/icon library. -* The first line contains the information needed to properly interpret the -* actual bits, which are expected to be used directly by software that -* wants to do compile-time binding to an image via a #include. -* The actual bits must be specified in hex. -* The default interpretation of the bits below is specified by the -* behavior of mpr_static. -* Note that Valid_bits_per_item uses the least-significant bits. -* Description: An empty (clear) cursor -* Background: White -* -* 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, -* 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 -* -* -* The utilities available to read icon files are: -* -* int -* icon_load(icon, from_file, error_msg); -* register Icon icon; -* char *from_file, *error_msg; -* Loads the pixrect for the icon, and then copies information from the pixrect -* to initialize the icon. Information which cannot be specified in the -* current format is set to default values. -* See the following description of icon_load_mpr for details about the -* arguments other than icon. -* Returns 0 iff it managed to successfully initialize the icon. -* -* int -* icon_init_from_pr(icon, pr) -* register Icon icon; -* register struct pixrect *pr; -* Initializes the icon struct from the specified pr. -* Information, such as the font for any icon text, which cannot be ascertained -* from a pixrect, is set to default values. -* -* The return value is meaningless. -* -* struct pixrect * -* icon_load_mpr(from_file, error_msg) -* char *from_file, *error_msg; -* Loads the icon named by from_file into a dynamically allocated memory -* pixrect. -* If NULL is returned, which happens if the file cannot be accessed or if the -* file is not in a valid format, an appropriate error message is placed -* in error_msg, which should be at least IL_ERRORMSG_SIZE long. -* -* FILE * -* icon_open_header(from_file, error_msg, info) -* char *from_file, *error_msg; -* register icon_header_handle info; -* icon_open_header() allows a client to preserve extra descriptive material -* when rewriting an icon file. It is also the front-end routine used by -* icon_load_mpr (and thus icon_load). -* If NULL is returned, which happens if the file cannot be accessed or if the -* file is not in a valid format, an appropriate error message is placed -* in error_msg, which should be at least IL_ERRORMSG_SIZE long. -* info is mostly filled in with the information from the header options. The -* exception is that info->last_param_pos is filled in with the position -* immediately after the last header option that was read. -* The returned FILE * is left positioned at the end of the header, thus -* ftell(icon_open_header()) indicates where the actual bits of the image -* are expected to begin. Hence, the characters in the range -* [info->last_param_pos..ftell(icon_open_header())) should contain all extra -* descriptive material contained in the icon file's header. -* -* icon_read_pr is not a public routine -* int -* icon_read_pr(fd, header, pr) -* register FILE *fd; -* register icon_header_handle header; -* register struct pixrect *pr; -* Reads the actual bit pattern for the pixrect's image data from the specified -* fd using the parameters in the specified header. -* The fd is expected to be positioned to the beginning of the image data -* (usually by a prior call to icon_open_header). -* The fd is left positioned at the end of the image data, so that by doing an -* ftell(fd) before and after calling icon_read_pr, a caller can write out a -* modified version of the image data while keeping intact the surrounding -* commentary, declarations, etc. -* The return value is meaningless. -* CAVEAT: currently pr must be a memory pixrect. -* -*/ -#endif /* notdef */ - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -#define IL_ERRORMSG_SIZE 256 - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef struct icon_header_object -{ - int depth, - height, - format_version, - valid_bits_per_item, - width; - long last_param_pos; -} -Xv_icon_header_info; - -typedef Xv_icon_header_info *icon_header_handle; -typedef Xv_icon_header_info icon_header_object; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Public Functions - */ -EXTERN_FUNCTION (int icon_load, (Icon icon, char *from_file, char *error_msg)); -EXTERN_FUNCTION (int icon_init_from_pr, (Icon icon, struct pixrect *pr)); -EXTERN_FUNCTION (struct pixrect *icon_load_mpr, (char *from_file, char *error_msg)); -EXTERN_FUNCTION (Server_image icon_load_svrim, (char *from_file, char *error_msg)); -EXTERN_FUNCTION (FILE *icon_open_header, (char *from_file, char *error_msg, Xv_icon_header_info *info)); - -#endif /* xview_icon_load_DEFINED */ diff --git a/include/xview/notice.h b/include/xview/notice.h deleted file mode 100644 index 62ec38c085a..00000000000 --- a/include/xview/notice.h +++ /dev/null @@ -1,122 +0,0 @@ -/* @(#)notice.h 20.23 91/01/11 */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_notice_DEFINED -#define xview_notice_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define NOTICE &xv_notice_pkg - -/* - * the following constant, NOTICE_FAILED is returned if notice_prompt() - * failed for an unspecified reason. - */ -#define NOTICE_YES 1 -#define NOTICE_NO 0 -#define NOTICE_FAILED -1 -#define NOTICE_TRIGGERED -2 - -/* - * PRIVATE #defines - */ - -#define NOTICE_ATTR(type, ordinal) ATTR(ATTR_PKG_NOTICE, type, ordinal) -#define NOTICE_ATTR_LIST(ltype, type, ordinal) \ - NOTICE_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) -#define NOTICE_BUTTON_VALUE_PAIR ATTR_INT_PAIR - - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef Xv_opaque Xv_Notice; -typedef Xv_opaque Xv_notice; - -typedef enum { - /* - * Public attributes - */ - NOTICE_BUTTON = NOTICE_ATTR(NOTICE_BUTTON_VALUE_PAIR, 1), - NOTICE_BUTTON_NO = NOTICE_ATTR(ATTR_STRING, 5), - NOTICE_BUTTON_YES = NOTICE_ATTR(ATTR_STRING, 10), - NOTICE_FOCUS_XY = NOTICE_ATTR(ATTR_XY, 15), - NOTICE_FONT = NOTICE_ATTR(ATTR_PIXFONT_PTR, 20), - NOTICE_MESSAGE_STRINGS - = NOTICE_ATTR_LIST(ATTR_NULL, ATTR_STRING, 25), - NOTICE_MESSAGE_STRINGS_ARRAY_PTR = NOTICE_ATTR(ATTR_STRING, 30), - NOTICE_NO_BEEPING = NOTICE_ATTR(ATTR_BOOLEAN, 35), - NOTICE_TRIGGER = NOTICE_ATTR(ATTR_INT, 40), - NOTICE_MESSAGE_STRING = NOTICE_ATTR(ATTR_STRING, 45), -#ifdef OW_I18N - NOTICE_MESSAGE_STRINGS_WCS - = NOTICE_ATTR_LIST(ATTR_NULL, ATTR_STRING, 50), - NOTICE_MESSAGE_STRINGS_ARRAY_PTR_WCS - = NOTICE_ATTR(ATTR_STRING, 55), - NOTICE_MESSAGE_STRING_WCS - = NOTICE_ATTR(ATTR_STRING, 60), - NOTICE_BUTTON_WCS = NOTICE_ATTR(NOTICE_BUTTON_VALUE_PAIR, 65), - NOTICE_BUTTON_NO_WCS = NOTICE_ATTR(ATTR_STRING, 70), - NOTICE_BUTTON_YES_WCS = NOTICE_ATTR(ATTR_STRING, 75), -#endif - NOTICE_LOCK_SCREEN = NOTICE_ATTR(ATTR_BOOLEAN, 80), - NOTICE_TRIGGER_EVENT = NOTICE_ATTR(ATTR_INT, 85), - NOTICE_STATUS = NOTICE_ATTR(ATTR_OPAQUE, 95), - NOTICE_EVENT_PROC = NOTICE_ATTR(ATTR_FUNCTION_PTR, 100), - NOTICE_BUSY_FRAMES = NOTICE_ATTR_LIST(ATTR_NULL, ATTR_OPAQUE, 105), - NOTICE_BLOCK_THREAD = NOTICE_ATTR(ATTR_BOOLEAN, 110) -} Notice_attribute; - - -/* - * Notice public struct - */ -typedef struct -{ - Xv_generic_struct parent_data; - Xv_opaque private_data; -} -Xv_notice_struct; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Public Functions - */ -EXTERN_FUNCTION (int notice_prompt, (Xv_Window window, - Event *return_event, - DOTDOTDOT)); - -extern Xv_pkg xv_notice_pkg; - -#endif /* ~xview_notice_DEFINED */ diff --git a/include/xview/notify.h b/include/xview/notify.h deleted file mode 100644 index 9fd71dcd846..00000000000 --- a/include/xview/notify.h +++ /dev/null @@ -1,356 +0,0 @@ - -/* @(#)notify.h 20.30 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_notify_DEFINED -#define xview_notify_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include -#include -#include -#include -#ifdef SYSV_WAIT -#ifndef SunOS -#include -#endif -#endif -#ifdef SYSV_UCONTEXT -#include -#endif - -/* This is part of the hack to make fcntl work for SVR4. The problem -* is in short: because we are includeing the socket libarary, which -* has an unoverridable fcntl, this does not work anymore for SVR4. -* We have to redefine fcntl to xv_fcntl, and we have to replace the -* system call with a call to ther real fcntl. -* The argument to perror has not been changed. -* This hack works, as long as all the calls to fcntl have the same -* number of arguments. They do right now. [vmh - 7/31/90] -*/ -#ifdef XV_USE_XVFCNTL -#define fcntl(a,b,c) xv_fcntl(a,b,c) -#endif -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define NOTIFY_FUNC_NULL ((Notify_func)0) - -/* Macros to examine wait3/waitpid results provided for BSD rather - * than adding a lot of #ifdef'ed code in the .c's. Note that AT&T- - * style macros expect the status value (not a pointer to it). - * Also provide a dummy rusage structure in the non-BSD case. - */ -#if !(defined WTERMSIG) && !(defined SYSV_WAIT) -#define WTERMSIG(status) ((status).w_termsig) -#endif -#if !(defined WSTOPSIG) && !(defined SYSV_WAIT) -#define WSTOPSIG(status) ((status).w_stopsig) -#endif -#if !(defined WEXITSTATUS) && !(defined SYSV_WAIT) -#define WEXITSTATUS(status) ((status).w_retcode) -#endif -#if !(defined WCOREDUMP) && !(defined SYSV_WAIT) -#define WCOREDUMP(status) ((status).w_coredump) -#endif - -#ifdef POLL -#define notify_set_fd_func(nclient, func, poll_fd) \ - ndet_set_fd_func(nclient, func, poll_fd, NTFY_FD) -#endif /* POLL */ - - -/* - * PRIVATE #defines - */ - -#define NOTIFY_CLIENT_NULL ((Notify_client)0) -#define NOTIFY_COPY_NULL ((Notify_copy)0) -#define NOTIFY_RELEASE_NULL ((Notify_release)0) -#define NOTIFY_ARG_NULL ((Notify_arg)0) - -/* - * Mask bit generating macros (for prioritizer): - */ -#define SIG_BIT(sig) (1 << ((sig)-1)) - -/* - *********************************************************************** - * Typedefs, enumerations, and structures - *********************************************************************** - */ - -/* - * Opaque client handle. - */ -typedef Xv_opaque Notify_client; - -#ifndef _NOTIFY_MIN_SYMBOLS /* Hack to reduce symbols in libraries. */ - -/* - * Opaque client event. - */ -typedef Xv_opaque Notify_event; - -/* - * Opaque client event optional argument. - */ -typedef Xv_opaque Notify_arg; - -/* - * A pointer to a function returning a Notify_arg (used for client - * event additional argument copying). - */ -typedef Notify_arg (*Notify_copy)(); - -/* - * A pointer to a function returning void (used for client - * event additional argument storage releasing). - */ -typedef void (*Notify_release)(); - -/* - * For Debugging utility: - */ -typedef enum notify_dump_type { - NOTIFY_ALL=0, - NOTIFY_DETECT=1, - NOTIFY_DISPATCH=2 -} Notify_dump_type; - -#endif /* ~_NOTIFY_MIN_SYMBOLS */ - -/* - * Client notification function return values for notifier to client calls. - */ -typedef enum notify_value { - NOTIFY_DONE = 0, /* Handled notification */ - NOTIFY_IGNORED = 1, /* Did nothing about notification */ - NOTIFY_UNEXPECTED = 2 /* Notification not expected */ -} Notify_value; - -/* - * A pointer to a function returning a Notify_value. - */ -typedef Notify_value (*Notify_func)(); - -/* - * Error codes for client to notifier calls (returned when no other - * return value or stored in notify_errno when other return value - * indicates error condition). - */ -typedef enum notify_error { - NOTIFY_OK = 0, /* Success */ - NOTIFY_UNKNOWN_CLIENT = 1, /* Client argument unknown to notifier */ - NOTIFY_NO_CONDITION = 2, /* Client not registered for given - * condition - */ - NOTIFY_BAD_ITIMER = 3, /* Itimer type unknown */ - NOTIFY_BAD_SIGNAL = 4, /* Signal number out of range */ - NOTIFY_NOT_STARTED = 5, /* Notify_stop called & notifier not - * started - */ - NOTIFY_DESTROY_VETOED = 6, /* Some client didn't want to die when - * called notify_die(DESTROY_CHECKING) - */ - NOTIFY_INTERNAL_ERROR = 7, /* Something wrong in the notifier */ - NOTIFY_SRCH = 8, /* No such process */ - NOTIFY_BADF = 9, /* Bad file number */ - NOTIFY_NOMEM = 10, /* Not enough core */ - NOTIFY_INVAL = 11, /* Invalid argument */ - NOTIFY_FUNC_LIMIT = 12 /* Too many interposition functions */ -} Notify_error; - - -/* - * Argument types - */ -typedef enum notify_signal_mode { - NOTIFY_SYNC = 0, - NOTIFY_ASYNC = 1 -} Notify_signal_mode; - -typedef enum notify_event_type { - NOTIFY_SAFE = 0, - NOTIFY_IMMEDIATE = 1 -} Notify_event_type; - -typedef enum destroy_status { - DESTROY_PROCESS_DEATH = 0, - DESTROY_CHECKING = 1, - DESTROY_CLEANUP = 2, - DESTROY_SAVE_YOURSELF = 3 -} Destroy_status; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC variables - */ - -extern struct itimerval NOTIFY_POLLING_ITIMER; /* {{0,1},{0,1}} */ - -/* - * PRIVATE variables - */ - -extern Notify_error notify_errno; - -#ifndef _NOTIFY_MIN_SYMBOLS -extern struct itimerval NOTIFY_NO_ITIMER; /* {{0,0},{0,0}} */ -#endif /* ~_NOTIFY_MIN_SYMBOLS */ - -/* - * PUBLIC functions - */ - -#ifndef _NOTIFY_MIN_SYMBOLS - -#if defined(SYSV_WAIT) || defined(SunOS) -EXTERN_FUNCTION (Notify_value notify_default_wait3, (Notify_client nclient, int pid, int *status, struct rusage *rusage)); -#else -EXTERN_FUNCTION (Notify_value notify_default_wait3, (Notify_client nclient, int pid, union wait *status, struct rusage *rusage)); -#endif - -EXTERN_FUNCTION (Notify_error notify_dispatch, (void)); -EXTERN_FUNCTION (Notify_error notify_do_dispatch, (void)); -EXTERN_FUNCTION (Notify_error notify_itimer_value, (Notify_client nclient, int which, struct itimerval *value)); -EXTERN_FUNCTION (Notify_value notify_next_destroy_func, (Notify_client nclient, Destroy_status status)); -EXTERN_FUNCTION (Notify_value notify_next_event_func, (Notify_client nclient, Notify_event event, Notify_arg arg, Notify_event_type when)); -EXTERN_FUNCTION (Notify_error notify_no_dispatch, (void)); -EXTERN_FUNCTION (Notify_func notify_set_destroy_func, (Notify_client nclient, Notify_func func)); -EXTERN_FUNCTION (Notify_func notify_set_exception_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_func notify_set_input_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_func notify_set_itimer_func, (Notify_client nclient, Notify_func func, int which, struct itimerval *value, struct itimerval *ovalue)); -EXTERN_FUNCTION (Notify_func notify_set_output_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_func notify_set_signal_func, (Notify_client nclient, Notify_func func, int sig, Notify_signal_mode mode)); -EXTERN_FUNCTION (Notify_func notify_set_wait3_func, (Notify_client nclient, Notify_func func, int pid)); -EXTERN_FUNCTION (Notify_error notify_start, (void)); -EXTERN_FUNCTION (Notify_error notify_stop, (void)); -EXTERN_FUNCTION (Notify_error notify_veto_destroy, (Notify_client nclient)); -EXTERN_FUNCTION (void notify_perror, (char *str)); -EXTERN_FUNCTION (void notify_enable_rpc_svc, (int flag)); - -#endif /* ~_NOTIFY_MIN_SYMBOLS */ - -/* - * PRIVATE functions - */ - -EXTERN_FUNCTION (Notify_func notify_set_event_func, (Notify_client nclient, Notify_func func, Notify_event_type when)); -EXTERN_FUNCTION (Notify_error notify_remove, (Notify_client nclient)); - -#ifndef _NOTIFY_MIN_SYMBOLS - -EXTERN_FUNCTION (Notify_error notify_client, (Notify_client nclient)); -EXTERN_FUNCTION (Notify_error notify_destroy, (Notify_client nclient, Destroy_status status)); -EXTERN_FUNCTION (Notify_error notify_die, (Destroy_status status)); -EXTERN_FUNCTION (Notify_error notify_event, (Notify_client nclient, Notify_event event, Notify_arg arg)); -EXTERN_FUNCTION (Notify_error notify_exception, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (void notify_flush_pending, (Notify_client nclient)); -EXTERN_FUNCTION (Notify_func notify_get_destroy_func, (Notify_client)); -EXTERN_FUNCTION (Notify_func notify_get_event_func, (Notify_client nclient, Notify_event_type when)); -EXTERN_FUNCTION (Notify_func notify_get_exception_func, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_func notify_get_input_func, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_func notify_get_itimer_func, (Notify_client nclient, int which)); -EXTERN_FUNCTION (Notify_func notify_get_output_func, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_func notify_get_prioritizer_func, (Notify_client nclient)); -EXTERN_FUNCTION (Notify_func notify_get_scheduler_func, (void)); -EXTERN_FUNCTION (int notify_get_signal_code, (void)); - -#ifndef SYSV_UCONTEXT -EXTERN_FUNCTION (struct sigcontext *notify_get_signal_context, (void)); -#else -EXTERN_FUNCTION (ucontext_t *notify_get_signal_context, (void)); -#endif - -EXTERN_FUNCTION (Notify_func notify_get_signal_func, (Notify_client nclient, int signal, Notify_signal_mode mode)); -EXTERN_FUNCTION (Notify_func notify_get_wait3_func, (Notify_client nclient, int pid)); -EXTERN_FUNCTION (Notify_error notify_input, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_error notify_interpose_destroy_func, (Notify_client nclient, Notify_func func)); -EXTERN_FUNCTION (Notify_error notify_interpose_event_func, (Notify_client nclient, Notify_func func, Notify_event_type when)); -EXTERN_FUNCTION (Notify_error notify_interpose_exception_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_error notify_interpose_input_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_error notify_interpose_itimer_func, (Notify_client nclient, Notify_func func, int which)); -EXTERN_FUNCTION (Notify_error notify_interpose_output_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_error notify_interpose_signal_func, (Notify_client nclient, Notify_func func, int signal, Notify_signal_mode mode)); -EXTERN_FUNCTION (Notify_error notify_interpose_wait3_func, (Notify_client nclient, Notify_func func, int pid)); -EXTERN_FUNCTION (Notify_error notify_itimer, (Notify_client nclient, int which)); -EXTERN_FUNCTION (Notify_value notify_next_exception_func, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_value notify_next_input_func, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_value notify_next_itimer_func, (Notify_client nclient, int which)); -EXTERN_FUNCTION (Notify_value notify_next_output_func, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_value notify_next_signal_func, (Notify_client nclient, int signal, Notify_signal_mode mode)); - -#if defined(SYSV_WAIT) || defined(SunOS) -EXTERN_FUNCTION (Notify_value notify_next_wait3_func, (Notify_client nclient, int pid, int *status, struct rusage *rusage)); -#else -EXTERN_FUNCTION (Notify_value notify_next_wait3_func, (Notify_client nclient, int pid, union wait *status, struct rusage *rusage)); -#endif - -EXTERN_FUNCTION (Notify_value notify_nop, (void)); -EXTERN_FUNCTION (Notify_error notify_output, (Notify_client nclient, int fd)); -EXTERN_FUNCTION (Notify_error notify_post_destroy, (Notify_client nclient, Destroy_status status, Notify_event_type type)); -EXTERN_FUNCTION (Notify_error notify_post_event, (Notify_client nclient, Notify_event event, Notify_event_type when_hint)); - -/* vmh - 10/15/90: one argument was missing */ -EXTERN_FUNCTION (Notify_error notify_post_event_and_arg, (Notify_client nclient, Notify_event event, Notify_event_type when_hint, Notify_arg arg, Notify_copy copy_func, Notify_release release_func)); - -EXTERN_FUNCTION (Notify_error notify_remove_destroy_func, (Notify_client nclient, Notify_func func)); -EXTERN_FUNCTION (Notify_error notify_remove_event_func, (Notify_client nclient, Notify_func func, Notify_event_type when)); -EXTERN_FUNCTION (Notify_error notify_remove_exception_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_error notify_remove_input_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_error notify_remove_itimer_func, (Notify_client nclient, Notify_func func, int which)); -EXTERN_FUNCTION (Notify_error notify_remove_output_func, (Notify_client nclient, Notify_func func, int fd)); -EXTERN_FUNCTION (Notify_error notify_remove_signal_func, (Notify_client nclient, Notify_func func, int signal, Notify_signal_mode mode)); -EXTERN_FUNCTION (Notify_error notify_remove_wait3_func, (Notify_client nclient, Notify_func func, int pid)); -EXTERN_FUNCTION (Notify_func notify_set_prioritizer_func, (Notify_client nclient, Notify_func func)); -EXTERN_FUNCTION (Notify_func notify_set_scheduler_func, (Notify_func nclient)); -EXTERN_FUNCTION (Notify_error notify_signal, (Notify_client nclient, int sig)); -EXTERN_FUNCTION (Notify_error notify_wait3, (Notify_client nclient)); - -extern Notify_error notify_errno; - -/* - * FD manipulation functions - */ - -EXTERN_FUNCTION (int ntfy_fd_cmp_and, (fd_set *a, fd_set *b)); -EXTERN_FUNCTION (int ntfy_fd_cmp_or, (fd_set *a, fd_set *b)); -EXTERN_FUNCTION (int ntfy_fd_anyset, (fd_set *a)); -EXTERN_FUNCTION (fd_set * ntfy_fd_cpy_or, (fd_set *a, fd_set *b)); -EXTERN_FUNCTION (fd_set * ntfy_fd_cpy_and, (fd_set *a, fd_set *b)); -EXTERN_FUNCTION (fd_set * ntfy_fd_cpy_xor, (fd_set *a, fd_set *b)); - -/* - * Debugging Utility - */ - -EXTERN_FUNCTION (void notify_dump, (Notify_client nclient, Notify_dump_type type, FILE * file)); - -#endif /* ~_NOTIFY_MIN_SYMBOLS */ - -#endif /* ~xview_notify_DEFINED */ diff --git a/include/xview/openmenu.h b/include/xview/openmenu.h deleted file mode 100644 index 784a0ad52ed..00000000000 --- a/include/xview/openmenu.h +++ /dev/null @@ -1,292 +0,0 @@ -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_walkmenu_DEFINED -#define xview_walkmenu_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include -#include - - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define MENU &xv_command_menu_pkg -#define MENU_COMMAND_MENU &xv_command_menu_pkg -#define MENU_CHOICE_MENU &xv_choice_menu_pkg -#define MENU_TOGGLE_MENU &xv_toggle_menu_pkg -#define MENUITEM &xv_menu_item_pkg - -#define MENUITEM_SPACE MENUITEM, \ - MENU_STRING, "", \ - MENU_FEEDBACK, FALSE - -#define MENU_BUT ACTION_MENU -#define MENU_NULL ((Menu)0) -#define MENU_ITEM_NULL ((Menu_item)0) -#define MENU_NO_ITEM MENU_ITEM_NULL -#define MENU_NO_VALUE 0 - -#define MENU_DEFAULT_NOTIFY_PROC menu_return_value - -/* - * PRIVATE #defines - */ - -#define MENU_ATTR(type, ordinal) ATTR(ATTR_PKG_MENU, type, ordinal) -#define MENU_ATTR_LIST(ltype, type, ordinal) \ - MENU_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - -/* - * Fake types -- This should be resolved someday - */ -#define ATTR_MENU ATTR_OPAQUE -#define ATTR_IMAGE ATTR_OPAQUE -#define ATTR_MENU_ITEM ATTR_OPAQUE -#define ATTR_MENU_ITEM_PAIR ATTR_INT_PAIR -#define ATTR_STRING_VALUE_PAIR ATTR_INT_PAIR -#define ATTR_IMAGE_VALUE_PAIR ATTR_INT_PAIR -#define ATTR_STRING_MENU_PAIR ATTR_INT_PAIR -#define ATTR_IMAGE_MENU_PAIR ATTR_INT_PAIR -#define ATTR_STRING_FUNCTION_PAIR ATTR_INT_PAIR -#define ATTR_IMAGE_FUNCTION_PAIR ATTR_INT_PAIR -#define ATTR_INT_MENU_ITEM_PAIR ATTR_INT_PAIR - -/* Reserved for future use */ -#define MENU_ATTR_UNUSED_FIRST 0 -#define MENU_ATTR_UNUSED_LAST 31 - -#define MENU_BORDER 2 -#define MENU_PKG menu_pkg - -/* - * PUBLIC #defines - * For SunView 1 compatibility. - */ -#define menu_destroy(menu_public) xv_destroy(menu_public) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -typedef Xv_opaque Menu; -typedef Xv_opaque Menu_item; - -typedef enum { - MENU_ACTION_IMAGE = MENU_ATTR(ATTR_IMAGE_FUNCTION_PAIR, 1), - MENU_ACTION_ITEM = MENU_ATTR(ATTR_STRING_FUNCTION_PAIR, 3), - MENU_APPEND_ITEM = MENU_ATTR(ATTR_MENU_ITEM, 9), - MENU_CLASS = MENU_ATTR(ATTR_ENUM, 12), - MENU_COLOR = MENU_ATTR(ATTR_INT, 15), - MENU_COL_MAJOR = MENU_ATTR(ATTR_BOOLEAN, 18), - MENU_DEFAULT = MENU_ATTR(ATTR_INT, 21), - MENU_DEFAULT_ITEM = MENU_ATTR(ATTR_MENU_ITEM, 24), - MENU_DESCEND_FIRST = MENU_ATTR(ATTR_BOOLEAN, 27), - /*NYI*/ MENU_DISABLE_ITEM = MENU_ATTR(ATTR_ENUM, 30), - MENU_DONE_PROC = MENU_ATTR(ATTR_FUNCTION_PTR, 31), - MENU_FEEDBACK = MENU_ATTR(ATTR_BOOLEAN, 33), - /*--G*/ MENU_FIRST_EVENT = MENU_ATTR(ATTR_NO_VALUE, 36), - MENU_GEN_PIN_WINDOW = MENU_ATTR(ATTR_INT_PAIR, 39), - MENU_GEN_PROC = MENU_ATTR(ATTR_FUNCTION_PTR, 42), - MENU_GEN_PROC_IMAGE = MENU_ATTR(ATTR_IMAGE_FUNCTION_PAIR, 45), - MENU_GEN_PROC_ITEM = MENU_ATTR(ATTR_STRING_FUNCTION_PAIR, 48), - MENU_GEN_PULLRIGHT = MENU_ATTR(ATTR_FUNCTION_PTR, 51), - MENU_GEN_PULLRIGHT_IMAGE= MENU_ATTR(ATTR_IMAGE_FUNCTION_PAIR, 54), - MENU_GEN_PULLRIGHT_ITEM = MENU_ATTR(ATTR_STRING_FUNCTION_PAIR, 57), - MENU_IMAGE = MENU_ATTR(ATTR_IMAGE, 60), - MENU_IMAGES = MENU_ATTR_LIST(ATTR_NULL, ATTR_IMAGE, 63), - MENU_IMAGE_ITEM = MENU_ATTR(ATTR_IMAGE_VALUE_PAIR, 66), - MENU_INACTIVE = MENU_ATTR(ATTR_BOOLEAN, 69), - MENU_INSERT = MENU_ATTR(ATTR_INT_MENU_ITEM_PAIR, 81), - MENU_INSERT_ITEM = MENU_ATTR(ATTR_MENU_ITEM_PAIR, 84), - MENU_INVERT = MENU_ATTR(ATTR_BOOLEAN, 87), - MENU_ITEM = MENU_ATTR_LIST(ATTR_RECURSIVE, ATTR_AV, 90), - /*--G*/ MENU_LAST_EVENT = MENU_ATTR(ATTR_NO_VALUE, 99), - /* - * MENU_MENU is a fake attribute returned by MENU_TYPE - */ - MENU_MENU = MENU_ATTR(ATTR_NO_VALUE, 102), - MENU_NCOLS = MENU_ATTR(ATTR_INT, 105), - /*--G*/ MENU_NITEMS = MENU_ATTR(ATTR_NO_VALUE, 108), - MENU_NOTIFY_PROC = MENU_ATTR(ATTR_FUNCTION_PTR, 6), - MENU_NOTIFY_STATUS = MENU_ATTR(ATTR_INT, 111), - /* - * The origin for MENU_NTH_ITEM is 1 - */ - MENU_NTH_ITEM = MENU_ATTR(ATTR_INT, 114), - MENU_NROWS = MENU_ATTR(ATTR_INT, 117), - MENU_PARENT = MENU_ATTR(ATTR_OPAQUE, 119), - MENU_PIN = MENU_ATTR(ATTR_BOOLEAN, 120), - MENU_PIN_PROC = MENU_ATTR(ATTR_FUNCTION_PTR, 123), - MENU_PIN_WINDOW = MENU_ATTR(ATTR_OPAQUE, 126), - MENU_PULLRIGHT = MENU_ATTR(ATTR_MENU, 129), - MENU_PULLRIGHT_IMAGE = MENU_ATTR(ATTR_IMAGE_MENU_PAIR, 135), - MENU_PULLRIGHT_ITEM = MENU_ATTR(ATTR_STRING_MENU_PAIR, 138), - MENU_RELEASE = MENU_ATTR(ATTR_NO_VALUE, 141), - MENU_RELEASE_IMAGE = MENU_ATTR(ATTR_NO_VALUE, 144), - MENU_REMOVE = MENU_ATTR(ATTR_INT, 147), - MENU_REMOVE_ITEM = MENU_ATTR(ATTR_MENU_ITEM, 150), - MENU_REPLACE = MENU_ATTR(ATTR_INT_MENU_ITEM_PAIR, 153), - MENU_REPLACE_ITEM = MENU_ATTR(ATTR_MENU_ITEM_PAIR, 156), - MENU_SELECTED = MENU_ATTR(ATTR_INT, 159), - MENU_SELECTED_ITEM = MENU_ATTR(ATTR_MENU_ITEM, 162), - MENU_STRING = MENU_ATTR(ATTR_STRING, 165), - MENU_STRINGS = MENU_ATTR_LIST(ATTR_NULL, ATTR_STRING,168), - MENU_STRING_ITEM = MENU_ATTR(ATTR_STRING_VALUE_PAIR, 171), - MENU_TITLE = MENU_ATTR(ATTR_NO_VALUE, 174), - MENU_TITLE_IMAGE = MENU_ATTR(ATTR_IMAGE, 177), - MENU_TITLE_ITEM = MENU_ATTR(ATTR_STRING, 180), - /*--G*/ MENU_TYPE = MENU_ATTR(ATTR_NO_VALUE, 183), - MENU_VALID_RESULT = MENU_ATTR(ATTR_INT, 186), - MENU_VALUE = MENU_ATTR(ATTR_OPAQUE, 189), - /* - * Private Attributes - */ - MENU_BUSY_PROC = MENU_ATTR(ATTR_FUNCTION_PTR, 195), - MENU_BUTTON = MENU_ATTR(ATTR_INT, 198), - MENU_CURSOR = MENU_ATTR(ATTR_OPAQUE, 201), - MENU_ENABLE_RECT = MENU_ATTR(ATTR_INT, 207), - MENU_FD = MENU_ATTR(ATTR_INT, 210), - MENU_HORIZONTAL_LINE = MENU_ATTR(ATTR_INT, 213), - MENU_IE = MENU_ATTR(ATTR_INT, 216), - MENU_LINE_AFTER_ITEM = MENU_ATTR(ATTR_INT, 219), - MENU_POS = MENU_ATTR(ATTR_INT_PAIR, 222), - MENU_POSITION_RECT = MENU_ATTR(ATTR_INT, 225), - MENU_PULLDOWN = MENU_ATTR(ATTR_INT, 228), - MENU_SHADOW_MENU = MENU_ATTR(ATTR_OPAQUE, 230), - MENU_SHADOW_GC = MENU_ATTR(ATTR_OPAQUE, 231), - MENU_WINDOW_MENU = MENU_ATTR(ATTR_OPAQUE, 233), - MENU_VERTICAL_LINE = MENU_ATTR(ATTR_INT, 234), - /* - * For SunView 1 Compatibility - */ - MENU_ACTION = MENU_NOTIFY_PROC, - MENU_ACTION_PROC = MENU_NOTIFY_PROC, - MENU_CLIENT_DATA = MENU_ATTR(ATTR_OPAQUE, 15), - MENU_PULLRIGHT_DELTA = MENU_ATTR(ATTR_INT, 132) - - /********************************* - * Internationalization Attributes - *********************************/ -#ifdef OW_I18N - , - MENU_ACTION_ITEM_WCS = MENU_ATTR(ATTR_STRING_FUNCTION_PAIR, 4), - MENU_GEN_PIN_WINDOW_WCS = MENU_ATTR(ATTR_INT_PAIR, 40), - MENU_GEN_PROC_ITEM_WCS = MENU_ATTR(ATTR_STRING_FUNCTION_PAIR, 49), - MENU_GEN_PULLRIGHT_ITEM_WCS = MENU_ATTR(ATTR_STRING_FUNCTION_PAIR, - 58), - MENU_PULLRIGHT_ITEM_WCS = MENU_ATTR(ATTR_STRING_MENU_PAIR, 139), - MENU_STRING_WCS = MENU_ATTR(ATTR_STRING, 166), - MENU_STRINGS_WCS = MENU_ATTR_LIST(ATTR_NULL, ATTR_STRING,169), - MENU_STRING_ITEM_WCS = MENU_ATTR(ATTR_STRING_VALUE_PAIR, 172), - MENU_TITLE_ITEM_WCS = MENU_ATTR(ATTR_STRING, 181) -#endif /* OW_I18N */ - -} Menu_attribute; - -typedef enum { - MENU_COMMAND, - MENU_CHOICE, - MENU_TOGGLE -} Menu_class; - -typedef enum { - MENU_PROVIDE_FEEDBACK, /* not default, selected */ - MENU_REMOVE_FEEDBACK, /* not default, not selected */ - MENU_SELECTED_DEFAULT_FEEDBACK, /* default, selected */ - MENU_DEFAULT_FEEDBACK, /* default, not selected */ - MENU_BUSY_FEEDBACK /* 50% gray */ -} Menu_feedback; - -/* - * New generate names intended to be less confusing - */ -typedef enum { - MENU_DISPLAY, - MENU_DISPLAY_DONE, - MENU_NOTIFY, - MENU_NOTIFY_DONE -} Menu_generate; - -typedef struct -{ - Xv_generic_struct parent_data; - Xv_opaque private_data; -} -Xv_menu; - -typedef struct -{ - Xv_generic_struct parent_data; - Xv_opaque private_data; -} -Xv_menu_item; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC variables - */ - -extern Xv_pkg xv_command_menu_pkg; -extern Xv_pkg xv_choice_menu_pkg; -extern Xv_pkg xv_toggle_menu_pkg; -extern Xv_pkg xv_menu_item_pkg; - -/* - * PUBLIC variables - * for SunView 1 compatibility - */ - -extern struct pixrect menu_gray50_pr; - -/* - * PUBLIC functions - */ -EXTERN_FUNCTION (Xv_opaque menu_return_value, (Menu menu, Menu_item item)); -EXTERN_FUNCTION (Xv_opaque menu_return_item, (Menu menu, Menu_item item)); -EXTERN_FUNCTION (void menu_show, (Menu menu, Xv_Window win, Event *event, DOTDOTDOT)); - -/* - * PRIVATE functions - */ -EXTERN_FUNCTION (void menu_return_default, (Menu menu, int depth, Event *event)); -EXTERN_FUNCTION (void menu_select_default, (Menu menu)); - -/* - * PUBLIC functions - * for SunView 1 compatibility - */ - -EXTERN_FUNCTION (Menu menu_create, (Attr_attribute attr1, DOTDOTDOT)); -EXTERN_FUNCTION (Menu_item menu_create_item, (Attr_attribute attr1, DOTDOTDOT)); -EXTERN_FUNCTION (Menu_item menu_find, (Menu menu, DOTDOTDOT)); -EXTERN_FUNCTION (Xv_opaque menu_get, (Menu menu, Xv_opaque attr, Xv_opaque v1)); -EXTERN_FUNCTION (Xv_opaque menu_set, (Menu menu, DOTDOTDOT)); -EXTERN_FUNCTION (void menu_destroy_with_proc, (Menu menu, void (*proc)())); - -#endif /* xview_walkmenu_DEFINED */ diff --git a/include/xview/openwin.h b/include/xview/openwin.h deleted file mode 100644 index d638b0c214c..00000000000 --- a/include/xview/openwin.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_openwin_DEFINED -#define xview_openwin_DEFINED - -/* - * Module: openwin.h - * Product: SunView 2.0 - * - * Level: Public - * - * Description: - * - * Defines attributes for the window that implements a LAF - * subwindow. - * - */ - - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define OPENWIN &xv_openwin_pkg - -#define OPENWIN_SPLIT_NEWVIEW_IN_PLACE -1 -#define OPENWIN_CANNOT_EXPAND -1 - -#define OPENWIN_EACH_VIEW(openwin, view) \ - {int _view_cnt = 0; \ - while (((view) = (Xv_Window) xv_get((openwin), OPENWIN_NTH_VIEW, _view_cnt++)) != NULL) { \ - -#define OPENWIN_END_EACH }} - - -/* - * PRIVATE #defines - */ - -#ifndef ATTR_PKG_OPENWIN -#define ATTR_PKG_OPENWIN (ATTR_PKG_UNUSED_FIRST + 8) -#endif -#define OPENWIN_ATTR(type, ordinal) ATTR(ATTR_PKG_OPENWIN, type, ordinal) -#define OPENWIN_ATTR_LIST(ltype, type, ordinal) \ - OPENWIN_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - -#define OPENWIN_SET_GC 0 -#define OPENWIN_CLR_GC 1 -#define OPENWIN_TEXT_GC 2 -#define OPENWIN_BOLD_GC 3 -#define OPENWIN_GLYPH_GC 4 -#define OPENWIN_INACTIVE_GC 5 -#define OPENWIN_DIM_GC 6 -#define OPENWIN_INVERT_GC 7 -#define OPENWIN_NONSTD_GC 8 /* Color or non-standard font */ -#define OPENWIN_NBR_GCS 9 - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -typedef Xv_opaque Openwin; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_openwin; - -typedef enum { - OPENWIN_SPLIT_HORIZONTAL, - OPENWIN_SPLIT_VERTICAL -} Openwin_split_direction; - -typedef enum { - /* - * Public Attributes - */ - OPENWIN_ADJUST_FOR_HORIZONTAL_SCROLLBAR - = OPENWIN_ATTR(ATTR_BOOLEAN, 1), - OPENWIN_ADJUST_FOR_VERTICAL_SCROLLBAR - = OPENWIN_ATTR(ATTR_BOOLEAN, 5), - OPENWIN_AUTO_CLEAR = OPENWIN_ATTR(ATTR_BOOLEAN, 10), - OPENWIN_HORIZONTAL_SCROLLBAR = OPENWIN_ATTR(ATTR_OPAQUE, 15), - OPENWIN_NVIEWS = OPENWIN_ATTR(ATTR_INT, 20), - OPENWIN_NO_MARGIN = OPENWIN_ATTR(ATTR_BOOLEAN, 25), - OPENWIN_NTH_VIEW = OPENWIN_ATTR(ATTR_OPAQUE, 30), - OPENWIN_SELECTED_VIEW = OPENWIN_ATTR(ATTR_OPAQUE, 35), - OPENWIN_SHOW_BORDERS = OPENWIN_ATTR(ATTR_BOOLEAN, 40), - OPENWIN_SPLIT = OPENWIN_ATTR_LIST(ATTR_RECURSIVE, ATTR_AV, 45), - OPENWIN_SPLIT_DIRECTION = OPENWIN_ATTR(ATTR_ENUM, 50), - OPENWIN_SPLIT_POSITION = OPENWIN_ATTR(ATTR_X, 55), - OPENWIN_SPLIT_VIEW = OPENWIN_ATTR(ATTR_OPAQUE, 60), - OPENWIN_SPLIT_VIEW_START = OPENWIN_ATTR(ATTR_X, 65), - OPENWIN_VERTICAL_SCROLLBAR = OPENWIN_ATTR(ATTR_OPAQUE, 70), - OPENWIN_VIEW_ATTRS = OPENWIN_ATTR_LIST(ATTR_RECURSIVE, ATTR_AV, 75), - OPENWIN_SPLIT_INIT_PROC = OPENWIN_ATTR(ATTR_FUNCTION_PTR, 76), - OPENWIN_SPLIT_DESTROY_PROC = OPENWIN_ATTR(ATTR_FUNCTION_PTR, 77), - /* - * Private Attributes - */ - OPENWIN_VIEW_CLASS = OPENWIN_ATTR(ATTR_OPAQUE, 80) -} Openwin_attribute; - - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_openwin_pkg; - -#endif /* ~xview_openwin_DEFINED */ diff --git a/include/xview/panel.h b/include/xview/panel.h deleted file mode 100644 index 58fed892b5d..00000000000 --- a/include/xview/panel.h +++ /dev/null @@ -1,737 +0,0 @@ -/* @(#)panel.h 20.89 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_panel_DEFINED -#define xview_panel_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ -#define PANEL &xv_panel_pkg -#define PANEL_ABBREV_MENU_BUTTON &xv_panel_ambtn_pkg -#define PANEL_BUTTON &xv_panel_button_pkg -#define PANEL_CHOICE &xv_panel_choice_pkg -#define PANEL_DROP_TARGET &xv_panel_drop_pkg -#define PANEL_GAUGE &xv_panel_gauge_pkg -#define PANEL_ITEM &xv_panel_item_pkg -#define PANEL_LIST &xv_panel_list_pkg -#define PANEL_MESSAGE &xv_panel_message_pkg -#define PANEL_MULTILINE_TEXT &xv_panel_multiline_text_pkg -#define PANEL_NUMERIC_TEXT &xv_panel_num_text_pkg -#define PANEL_SLIDER &xv_panel_slider_pkg -#define PANEL_TEXT &xv_panel_text_pkg -#define PANEL_VIEW &xv_panel_view_pkg - -#define SCROLLABLE_PANEL &xv_scrollable_panel_pkg - -#define PANEL_CHOICE_STACK \ - PANEL_CHOICE, PANEL_DISPLAY_LEVEL, PANEL_CURRENT - -#define PANEL_CYCLE PANEL_CHOICE, PANEL_DISPLAY_LEVEL, PANEL_CURRENT - -#define PANEL_TOGGLE PANEL_CHOICE, PANEL_CHOOSE_ONE, FALSE -#define PANEL_CHECK_BOX PANEL_TOGGLE, PANEL_FEEDBACK, PANEL_MARKED - -#define PANEL_CHECK_BOX_VALUE PANEL_TOGGLE_VALUE - - -/* - * Various utility macros - */ -#define panel_get_value(ip) xv_get((ip), PANEL_VALUE) -#define panel_set_value(ip, val) xv_set((ip), PANEL_VALUE, (val), 0) -#ifdef OW_I18N -#define panel_get_value_wcs(ip) xv_get((ip), PANEL_VALUE_WCS) -#define panel_set_value_wcs(ip, val) xv_set((ip), PANEL_VALUE_WCS, (val), 0) -#endif /* OW_I18N */ - -/* Note: In PANEL_EACH_ITEM, we need "_next" since the current item - * (ip) may be destroyed from within the for loop. - */ -#define PANEL_EACH_ITEM(panel, ip) \ - { Panel_item _next; \ - for ((ip) = xv_get((panel), PANEL_FIRST_ITEM); \ - (ip); \ - (ip) = _next) { \ - _next = xv_get((ip), PANEL_NEXT_ITEM); \ - if (xv_get(ip, PANEL_ITEM_OWNER)) \ - continue; \ - { - -#define PANEL_END_EACH }}} - -/* - * Miscellaneous constants - */ -#define PANEL_ITEM_X_START 4 /* offset from left edge */ -#define PANEL_ITEM_Y_START 4 /* offset from top edge */ - -/* Panel defined events. - * These are given to the Panel's or Panel_item's event proc - */ -#define PANEL_EVENT_FIRST vuid_first(PANEL_DEVID) /* 32000 */ -#define PANEL_EVENT_CANCEL (PANEL_EVENT_FIRST + 0) /* 32000 */ - -/* - * PRIVATE #defines - */ - -#define PANEL_ATTR(type, ordinal) ATTR(ATTR_PKG_PANEL, type, ordinal) - -/* - * panel specific attribute types - */ -#define PANEL_INDEX_STRING ATTR_TYPE(ATTR_BASE_UNUSED_FIRST, 2) -#define PANEL_INDEX_PIXRECT_PTR ATTR_TYPE(ATTR_BASE_UNUSED_FIRST + 1, 2) -#define PANEL_INDEX_BOOLEAN ATTR_TYPE(ATTR_BASE_UNUSED_FIRST + 2, 2) -#define PANEL_INDEX_FONT ATTR_TYPE(ATTR_BASE_UNUSED_FIRST + 3, 2) -#define PANEL_INDEX_CLIENT_DATA ATTR_TYPE(ATTR_BASE_UNUSED_FIRST + 4, 2) - - -#define PANEL_FONT WIN_FONT -#define PANEL_TYPE ATTR_PKG_PANEL - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -typedef struct -{ - Xv_canvas parent_data; - Xv_opaque private_data; -} -Xv_panel_or_item; /* scrollable_panel, panel or item */ - - -/* - * Typedefs - */ -typedef Xv_opaque Panel; -typedef Xv_opaque Scrollable_panel; -typedef Xv_opaque Panel_item; -typedef Xv_opaque Panel_attribute_value; -typedef Xv_panel_or_item Xv_panel; -typedef Xv_panel_or_item Xv_item; -typedef Xv_opaque Panel_view; -typedef Xv_item Xv_panel_message; - -typedef Panel_item Panel_abbrev_menu_button_item; -typedef Panel_item Panel_button_item; -typedef Panel_item Panel_choice_item; -typedef Panel_item Panel_drop_target_item; -typedef Panel_item Panel_gauge_item; -typedef Panel_item Panel_list_item; -typedef Panel_item Panel_message_item; -typedef Panel_item Panel_slider_item; -typedef Panel_item Panel_text_item; -typedef Panel_item Panel_numeric_text_item; -typedef Panel_item Panel_multiline_text_item; - -/* - * Enumerations - */ -typedef enum { - /********************* - * Public Attributes - *********************/ - - /* Panel and Panel_item attributes */ - PANEL_ACCEPT_KEYSTROKE = PANEL_ATTR(ATTR_BOOLEAN, 1), - PANEL_CLIENT_DATA = PANEL_ATTR(ATTR_OPAQUE, 36), - PANEL_EVENT_PROC = PANEL_ATTR(ATTR_FUNCTION_PTR, 44), - PANEL_GINFO = PANEL_ATTR(ATTR_OPAQUE, 45), - /* PANEL_ITEM_X and PANEL_ITEM_Y must still be supported in addition - * to XV_X and XV_Y because they can be used on the panel. When used - * on the panel, PANEL_ITEM_X != XV_X. - */ - PANEL_ITEM_X = PANEL_ATTR(ATTR_X, 63), - PANEL_ITEM_Y = PANEL_ATTR(ATTR_Y, 64), - PANEL_ITEM_X_GAP = PANEL_ATTR(ATTR_X, 65), - PANEL_ITEM_Y_GAP = PANEL_ATTR(ATTR_Y, 66), - PANEL_LAYOUT = PANEL_ATTR(ATTR_ENUM, 82), - PANEL_PAINT = PANEL_ATTR(ATTR_ENUM, 160), - - /* Panel attributes */ - PANEL_BACKGROUND_PROC = PANEL_ATTR(ATTR_FUNCTION_PTR, 2), - PANEL_BLINK_CARET = PANEL_ATTR(ATTR_BOOLEAN, 4), - PANEL_BOLD_FONT = PANEL_ATTR(ATTR_PIXFONT_PTR, 6), - PANEL_CARET_ITEM = PANEL_ATTR(ATTR_OPAQUE, 8), - PANEL_CURRENT_ITEM = PANEL_ATTR(ATTR_OPAQUE, 9), - PANEL_DEFAULT_ITEM = PANEL_ATTR(ATTR_OPAQUE, 38), - PANEL_FOCUS_PW = PANEL_ATTR(ATTR_OPAQUE, 39), - PANEL_EXTRA_PAINT_HEIGHT = PANEL_ATTR(ATTR_Y, 46), - PANEL_EXTRA_PAINT_WIDTH = PANEL_ATTR(ATTR_X, 48), - PANEL_FIRST_ITEM = PANEL_ATTR(ATTR_OPAQUE, 52), - PANEL_FIRST_PAINT_WINDOW = PANEL_ATTR(ATTR_OPAQUE, 35), - PANEL_ITEM_X_POSITION = PANEL_ATTR(ATTR_INT, 47), - PANEL_ITEM_Y_POSITION = PANEL_ATTR(ATTR_INT, 49), - PANEL_NO_REDISPLAY_ITEM = PANEL_ATTR(ATTR_BOOLEAN, 43), - PANEL_PRIMARY_FOCUS_ITEM = PANEL_ATTR(ATTR_OPAQUE, 51), - PANEL_REPAINT_PROC = PANEL_ATTR(ATTR_FUNCTION_PTR, 164), - PANEL_STATUS = PANEL_ATTR(ATTR_OPAQUE, 166), - - /* Panel_item attributes */ - PANEL_BUSY = PANEL_ATTR(ATTR_BOOLEAN, 7), - PANEL_CHILD_CARET_ITEM = PANEL_ATTR(ATTR_OPAQUE, 81), - PANEL_INACTIVE = PANEL_ATTR(ATTR_BOOLEAN, 54), - PANEL_ITEM_CLASS = PANEL_ATTR(ATTR_OPAQUE, 56), - PANEL_ITEM_COLOR = PANEL_ATTR(ATTR_INT, 58), - PANEL_ITEM_CREATED = PANEL_ATTR(ATTR_BOOLEAN, 59), - PANEL_ITEM_DEAF = PANEL_ATTR(ATTR_BOOLEAN, 57), - PANEL_ITEM_LABEL_RECT = PANEL_ATTR(ATTR_RECT_PTR, 55), - PANEL_ITEM_MENU = PANEL_ATTR(ATTR_OPAQUE, 60), - PANEL_ITEM_NTH_WINDOW = PANEL_ATTR(ATTR_OPAQUE, 77), - PANEL_ITEM_NWINDOWS = PANEL_ATTR(ATTR_INT, 79), - PANEL_ITEM_RECT = PANEL_ATTR(ATTR_RECT_PTR, 62), - PANEL_ITEM_VALUE_RECT = PANEL_ATTR(ATTR_RECT_PTR, 71), - PANEL_ITEM_WANTS_ADJUST = PANEL_ATTR(ATTR_BOOLEAN, 61), - PANEL_ITEM_WANTS_ISO = PANEL_ATTR(ATTR_BOOLEAN, 69), - PANEL_LABEL_BOLD = PANEL_ATTR(ATTR_BOOLEAN, 68), - PANEL_LABEL_FONT = PANEL_ATTR(ATTR_PIXFONT_PTR, 70), - PANEL_LABEL_IMAGE = PANEL_ATTR(ATTR_PIXRECT_PTR, 72), - PANEL_LABEL_STRING = PANEL_ATTR(ATTR_STRING, 74), - PANEL_LABEL_WIDTH = PANEL_ATTR(ATTR_INT, 76), - PANEL_LABEL_X = PANEL_ATTR(ATTR_X, 78), - PANEL_LABEL_Y = PANEL_ATTR(ATTR_Y, 80), - PANEL_NEXT_COL = PANEL_ATTR(ATTR_INT, 145), - PANEL_NEXT_ITEM = PANEL_ATTR(ATTR_OPAQUE, 146), - PANEL_NEXT_ROW = PANEL_ATTR(ATTR_INT, 147), - PANEL_NOTIFY_PROC = PANEL_ATTR(ATTR_FUNCTION_PTR, 154), - PANEL_NOTIFY_STATUS = PANEL_ATTR(ATTR_INT, 156), - PANEL_OPS_VECTOR = PANEL_ATTR(ATTR_OPAQUE, 157), - PANEL_VALUE_X = PANEL_ATTR(ATTR_X, 190), - PANEL_VALUE_Y = PANEL_ATTR(ATTR_Y, 192), - - /* Panel_choice_item attributes */ - PANEL_CHOICES_BOLD = PANEL_ATTR(ATTR_BOOLEAN, 10), - PANEL_CHOICE_COLOR = PANEL_ATTR(ATTR_INT_PAIR, 11), - PANEL_CHOICE_FONT = PANEL_ATTR(PANEL_INDEX_FONT, 12), - PANEL_CHOICE_FONTS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_PIXFONT_PTR), 14), - PANEL_CHOICE_IMAGE = PANEL_ATTR(PANEL_INDEX_PIXRECT_PTR, 16), - PANEL_CHOICE_IMAGES = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_PIXRECT_PTR), 18), - PANEL_CHOICE_NCOLS = PANEL_ATTR(ATTR_INT, 19), - PANEL_CHOICE_NROWS = PANEL_ATTR(ATTR_INT, 21), - PANEL_CHOICE_RECT = PANEL_ATTR(ATTR_INT, 73), - PANEL_CHOICE_STRING = PANEL_ATTR(PANEL_INDEX_STRING, 20), - PANEL_CHOICE_STRINGS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_STRING), 22), - PANEL_CHOICE_X = PANEL_ATTR(ATTR_INDEX_X, 26), - PANEL_CHOICE_XS = PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_X), 28), - PANEL_CHOICE_Y = PANEL_ATTR(ATTR_INDEX_Y, 30), - PANEL_CHOICE_YS = PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_Y), 32), - PANEL_DEFAULT_VALUE = PANEL_ATTR(ATTR_OPAQUE, 40), - PANEL_DISPLAY_LEVEL = PANEL_ATTR(ATTR_ENUM, 42), - PANEL_FEEDBACK = PANEL_ATTR(ATTR_ENUM, 50), - PANEL_MARK_IMAGE = PANEL_ATTR(PANEL_INDEX_PIXRECT_PTR, 124), - PANEL_MARK_IMAGES = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_PIXRECT_PTR),126), - PANEL_MARK_X = PANEL_ATTR(ATTR_INDEX_X, 128), - PANEL_MARK_XS = PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_X),130), - PANEL_MARK_Y = PANEL_ATTR(ATTR_INDEX_Y, 132), - PANEL_MARK_YS = PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_Y),134), - PANEL_NCHOICES = PANEL_ATTR(ATTR_INT, 143), - PANEL_NOMARK_IMAGE = PANEL_ATTR(PANEL_INDEX_PIXRECT_PTR, 148), - PANEL_NOMARK_IMAGES = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_PIXRECT_PTR),150), - PANEL_TOGGLE_VALUE = PANEL_ATTR(PANEL_INDEX_BOOLEAN, 178), - - /* Panel_choice_item, Panel_gauge_item, Panel_multiline_text_item, - * Panel_numeric_text_item, Panel_slider_item and Panel_text_item - * attributes. - */ - PANEL_VALUE = PANEL_ATTR(ATTR_INT, 180), - - /* Panel_choice_item and Panel_list_item attributes */ - PANEL_CHOOSE_NONE = PANEL_ATTR(ATTR_BOOLEAN, 33), - PANEL_CHOOSE_ONE = PANEL_ATTR(ATTR_BOOLEAN, 34), - - /* Panel_drop_target_item attributes */ - PANEL_DROP_BUSY_GLYPH = PANEL_ATTR(ATTR_OPAQUE, 3), - PANEL_DROP_DND = PANEL_ATTR(ATTR_OPAQUE, 5), - PANEL_DROP_FULL = PANEL_ATTR(ATTR_BOOLEAN, 13), - PANEL_DROP_GLYPH = PANEL_ATTR(ATTR_OPAQUE, 15), - PANEL_DROP_HEIGHT = PANEL_ATTR(ATTR_INT, 17), - PANEL_DROP_SEL_REQ = PANEL_ATTR(ATTR_OPAQUE, 25), - PANEL_DROP_SITE_DEFAULT = PANEL_ATTR(ATTR_BOOLEAN, 83), - PANEL_DROP_WIDTH = PANEL_ATTR(ATTR_INT, 27), - - /* Panel_gauge_item attributes */ - PANEL_GAUGE_WIDTH = PANEL_ATTR(ATTR_INT, 53), - - /* Panel_gauge_item, Panel_numeric_text_item and - * Panel_slider_item attributes - */ - PANEL_MAX_VALUE = PANEL_ATTR(ATTR_INT, 138), - PANEL_MIN_VALUE = PANEL_ATTR(ATTR_INT, 144), - - /* Panel_gauge_item and Panel_slider_item attributes */ - PANEL_DIRECTION = PANEL_ATTR(ATTR_ENUM, 41), - PANEL_MAX_TICK_STRING = PANEL_ATTR(ATTR_STRING, 137), - PANEL_MIN_TICK_STRING = PANEL_ATTR(ATTR_STRING, 140), - PANEL_SHOW_RANGE = PANEL_ATTR(ATTR_BOOLEAN, 172), - PANEL_TICKS = PANEL_ATTR(ATTR_INT, 177), - - /* Panel_list_item attributes */ - PANEL_LIST_CLIENT_DATA = PANEL_ATTR(PANEL_INDEX_CLIENT_DATA, 88), - PANEL_LIST_CLIENT_DATAS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_OPAQUE), 90), - PANEL_LIST_DELETE = PANEL_ATTR(ATTR_INT, 92), - PANEL_LIST_DELETE_ROWS = PANEL_ATTR(ATTR_INT_PAIR, 93), - PANEL_LIST_DELETE_SELECTED_ROWS = PANEL_ATTR(ATTR_NO_VALUE, 97), - PANEL_LIST_DISPLAY_ROWS = PANEL_ATTR(ATTR_INT, 94), - PANEL_LIST_FIRST_SELECTED = PANEL_ATTR(ATTR_NO_VALUE, 95), - PANEL_LIST_FONT = PANEL_ATTR(PANEL_INDEX_FONT, 96), - PANEL_LIST_FONTS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_PIXFONT_PTR), 98), - PANEL_LIST_GLYPH = PANEL_ATTR(PANEL_INDEX_PIXRECT_PTR, 100), - PANEL_LIST_GLYPHS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_PIXRECT_PTR),102), - PANEL_LIST_INSERT = PANEL_ATTR(ATTR_INT, 106), - PANEL_LIST_INSERT_DUPLICATE = PANEL_ATTR(ATTR_BOOLEAN, 105), - PANEL_LIST_INSERT_GLYPHS = PANEL_ATTR(ATTR_OPAQUE_PAIR, 107), - PANEL_LIST_INSERT_STRINGS = PANEL_ATTR(ATTR_OPAQUE_PAIR, 109), - PANEL_LIST_MODE = PANEL_ATTR(ATTR_ENUM, 119), - PANEL_LIST_NEXT_SELECTED = PANEL_ATTR(ATTR_INT, 29), - PANEL_LIST_NROWS = PANEL_ATTR(ATTR_INT, 108), - PANEL_LIST_ROW_HEIGHT = PANEL_ATTR(ATTR_INT, 110), - PANEL_LIST_SCROLLBAR = PANEL_ATTR(ATTR_OPAQUE, 111), - PANEL_LIST_SELECT = PANEL_ATTR(ATTR_INT_PAIR, 112), - PANEL_LIST_SELECTED = PANEL_ATTR(ATTR_INT, 113), - PANEL_LIST_SORT = PANEL_ATTR(ATTR_ENUM, 117), - PANEL_LIST_STRING = PANEL_ATTR(PANEL_INDEX_STRING, 114), - PANEL_LIST_STRINGS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_STRING), 116), - PANEL_LIST_TITLE = PANEL_ATTR(ATTR_STRING, 31), - PANEL_LIST_WIDTH = PANEL_ATTR(ATTR_INT, 122), - - /* Panel_list_item, Panel_multiline_text_item, - * Panel_numeric_text_item, Panel_slider_item and - * Panel_text_item attributes - */ - PANEL_READ_ONLY = PANEL_ATTR(ATTR_BOOLEAN, 162), - - /* Panel_multiline_text_item attributes */ - PANEL_LINE_BREAK_ACTION = PANEL_ATTR(ATTR_ENUM, 84), - - /* Panel_multiline_text_item, Panel_numeric_text_item, - * Panel_slider_item and Panel_text_item attributes - */ - PANEL_NOTIFY_LEVEL = PANEL_ATTR(ATTR_ENUM, 152), - PANEL_VALUE_DISPLAY_LENGTH = PANEL_ATTR(ATTR_INT, 182), - - /* Panel_multiline_text_item, Panel_numeric_text_item and - * Panel_text_item attributes - */ - PANEL_NOTIFY_STRING = PANEL_ATTR(ATTR_STRING, 158), - PANEL_VALUE_DISPLAY_WIDTH = PANEL_ATTR(ATTR_INT, 183), - PANEL_VALUE_STORED_LENGTH = PANEL_ATTR(ATTR_INT, 186), - - /* Panel_numeric_text_item and Panel_slider_item attributes */ - PANEL_JUMP_DELTA = PANEL_ATTR(ATTR_INT, 67), - PANEL_VALUE_FONT = PANEL_ATTR(ATTR_PIXFONT_PTR, 184), - - /* Panel_numeric_text_item and Panel_text_item attributes */ - PANEL_MASK_CHAR = PANEL_ATTR(ATTR_CHAR, 136), - PANEL_VALUE_UNDERLINED = PANEL_ATTR(ATTR_BOOLEAN, 188), - - /* Panel_slider_item attributes */ - PANEL_MAX_VALUE_STRING = PANEL_ATTR(ATTR_STRING, 139), - PANEL_MIN_VALUE_STRING = PANEL_ATTR(ATTR_STRING, 142), - PANEL_SHOW_VALUE = PANEL_ATTR(ATTR_BOOLEAN, 174), - PANEL_SLIDER_END_BOXES = PANEL_ATTR(ATTR_BOOLEAN, 175), - PANEL_SLIDER_WIDTH = PANEL_ATTR(ATTR_X, 176), - - /* Panel_text_item attributes */ - PANEL_TEXT_SELECT_LINE = PANEL_ATTR(ATTR_NO_VALUE, 210), - - /********************* - * Private Attributes - *********************/ - PANEL_CHOICE_OFFSET = PANEL_ATTR(ATTR_INT, 196), - PANEL_ITEM_OWNER = PANEL_ATTR(ATTR_OPAQUE, 197), - PANEL_LABEL_BOXED = PANEL_ATTR(ATTR_BOOLEAN, 198), - PANEL_LABEL_INVERTED = PANEL_ATTR(ATTR_BOOLEAN, 200), - PANEL_LIST_ROW_HIGHLIGHTED = PANEL_ATTR(ATTR_BOOLEAN, 202), - PANEL_MENU_ITEM = PANEL_ATTR(ATTR_BOOLEAN, 204), - PANEL_NUM_TXT = PANEL_ATTR(ATTR_OPAQUE, 205), - PANEL_TEXT_CURSOR = PANEL_ATTR(ATTR_OPAQUE, 206) - -#ifdef OW_I18N - /**************************************** - * Internationalization Public Attributes - ****************************************/ - , - PANEL_LABEL_STRING_WCS = PANEL_ATTR(ATTR_STRING, 75), - PANEL_NOTIFY_PROC_WCS = PANEL_ATTR(ATTR_FUNCTION_PTR, 155), - PANEL_CHOICE_STRING_WCS = PANEL_ATTR(PANEL_INDEX_STRING, 23), - PANEL_CHOICE_STRINGS_WCS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_STRING), 24), - PANEL_VALUE_WCS = PANEL_ATTR(ATTR_INT, 181), - PANEL_LIST_INSERT_STRINGS_WCS = - PANEL_ATTR(ATTR_OPAQUE_PAIR, 165), - PANEL_LIST_STRING_WCS = PANEL_ATTR(PANEL_INDEX_STRING, 115), - PANEL_LIST_STRINGS_WCS = - PANEL_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_STRING), 118), - PANEL_LIST_TITLE_WCS = PANEL_ATTR(ATTR_STRING, 163), - PANEL_MASK_CHAR_WC = PANEL_ATTR(ATTR_CHAR, 161), - PANEL_NOTIFY_STRING_WCS = PANEL_ATTR(ATTR_STRING, 159), - PANEL_MAX_TICK_STRING_WCS = PANEL_ATTR(ATTR_STRING, 141), - PANEL_MIN_TICK_STRING_WCS = PANEL_ATTR(ATTR_STRING, 149), - PANEL_MAX_VALUE_STRING_WCS = PANEL_ATTR(ATTR_STRING, 151), - PANEL_MIN_VALUE_STRING_WCS = PANEL_ATTR(ATTR_STRING, 153), - - /****************************************** - * Internationalization Private Attributes - ******************************************/ - - PANEL_TEXT_IGNORE_IM = PANEL_ATTR(ATTR_INT, 167) -#endif /* OW_I18N */ -} Panel_attr; - -#define PANEL_PARENT_PANEL XV_OWNER -#define PANEL_SHOW_ITEM XV_SHOW -#define PANEL_DISPLAY_ROWS PANEL_LIST_DISPLAY_ROWS - -typedef enum { - PANEL_LIST_OP_DESELECT, - PANEL_LIST_OP_SELECT, - PANEL_LIST_OP_VALIDATE, - PANEL_LIST_OP_DELETE -} Panel_list_op; - -typedef enum { - PANEL_LIST_READ, - PANEL_LIST_EDIT -} Panel_list_mode; - -typedef struct panel_ops -{ - void (*panel_op_handle_event)(); - void (*panel_op_begin_preview)(); - void (*panel_op_update_preview)(); - void (*panel_op_cancel_preview)(); - void (*panel_op_accept_preview)(); - void (*panel_op_accept_menu)(); - void (*panel_op_accept_key)(); - void (*panel_op_clear)(); - void (*panel_op_paint)(); - void (*panel_op_resize)(); - void (*panel_op_remove)(); - void (*panel_op_restore)(); - void (*panel_op_layout)(); - void (*panel_op_accept_kbd_focus)(); - void (*panel_op_yield_kbd_focus)(); - void *panel_op_extension; /* for future extensions */ -} -Panel_ops; - -typedef struct panel_pw_struct -{ - Xv_Window pw; - Xv_Window view; - struct panel_pw_struct *next; -} -Panel_paint_window; - -/* - * Panel status flags. (Used in panel->status) - * - * Note: These values are readable but not settable at the Panel_item level. - */ -typedef struct panel_status -{ -unsigned blinking : - 1; -unsigned current_item_active : - 1; -unsigned destroying : - 1; -unsigned focus_item_set : - 1; - /* The keyboard focus item has been set when the panel paint window - * did not have the keyboard focus. When the panel paint window - * receives the KBD_USE event, don't change the kbd_focus to the - * primary focus item. Instead, just clear the flag. - */ -unsigned has_input_focus : - 1; -unsigned mouseless : - 1; -unsigned nonstd_cursor : - 1; /* cursor is not basic pointer */ -unsigned painted : - 1; -unsigned pointer_grabbed : - 1; -unsigned quick_move : - 1; /* quick move pending */ -unsigned select_displays_menu : - 1; -unsigned three_d : - 1; -} -Panel_status; - - -/* - * Values for LEVEL attributes - */ -typedef enum { - PANEL_CLEAR, /* painting */ - PANEL_NO_CLEAR, /* painting */ - PANEL_NONE, /* text notify, menu, display, painting */ - PANEL_ALL, /* text notify, slider notify, display */ - PANEL_NON_PRINTABLE, /* text notify */ - PANEL_SPECIFIED, /* text notify */ - PANEL_CURRENT, /* display */ - PANEL_DONE, /* slider notify */ - PANEL_MARKED, /* feedback */ - PANEL_VERTICAL, /* layout, slider direction */ - PANEL_HORIZONTAL, /* layout, slider direction */ - PANEL_INVERTED, /* feedback */ - /* - * values returnable by notify routines - */ - PANEL_INSERT, - PANEL_NEXT, - PANEL_PREVIOUS, - /* - * mouse state - */ - PANEL_NONE_DOWN, /* no buttons are down */ - PANEL_LEFT_DOWN, /* left button is down */ - PANEL_MIDDLE_DOWN, /* middle button is down */ - PANEL_RIGHT_DOWN, /* right button is down */ - PANEL_CHORD_DOWN, /* chord of buttons are down */ - /* - * PANEL_LIST sort keys - */ - PANEL_FORWARD, /* forward alphabetic sort */ - PANEL_REVERSE, /* reverse alphabetic sort */ - /* - * PANEL_LINE_BREAK_ACTION values - */ - PANEL_WRAP_AT_CHAR, - PANEL_WRAP_AT_WORD -} Panel_setting; - -/* - * Types of items - */ -typedef enum { - PANEL_MESSAGE_ITEM, - PANEL_BUTTON_ITEM, - PANEL_CHOICE_ITEM, - PANEL_TOGGLE_ITEM, - PANEL_TEXT_ITEM, - PANEL_NUMERIC_TEXT_ITEM, - PANEL_SLIDER_ITEM, - PANEL_LIST_ITEM, - PANEL_GAUGE_ITEM, - PANEL_ABBREV_MENU_BUTTON_ITEM, - PANEL_EXTENSION_ITEM, - PANEL_MULTILINE_TEXT_ITEM, - PANEL_DROP_TARGET_ITEM -} Panel_item_type; - -typedef struct -{ - Xv_canvas_view parent_data; - Xv_opaque private_data; -} -Xv_panel_view; - -/* - * Structures - */ - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_choice; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_gauge; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_slider; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_text; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_num_text; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_multiline_text; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_ambtn; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_button; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_drop; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_list; - -typedef struct -{ - Xv_item parent_data; - Xv_opaque private_data; -} -Xv_panel_extension_item; - -/* - * For SunView 1 compatibility - */ -typedef Panel_attr Panel_attribute; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Variables - */ -extern Xv_pkg xv_panel_pkg; -extern Xv_pkg xv_panel_ambtn_pkg; -extern Xv_pkg xv_panel_button_pkg; -extern Xv_pkg xv_panel_choice_pkg; -extern Xv_pkg xv_panel_drop_pkg; -extern Xv_pkg xv_panel_gauge_pkg; -extern Xv_pkg xv_panel_item_pkg; -extern Xv_pkg xv_panel_list_pkg; -extern Xv_pkg xv_panel_message_pkg; -extern Xv_pkg xv_panel_multiline_text_pkg; -extern Xv_pkg xv_panel_num_text_pkg; -extern Xv_pkg xv_panel_slider_pkg; -extern Xv_pkg xv_panel_text_pkg; -extern Xv_pkg xv_panel_view_pkg; -extern Xv_pkg xv_scrollable_panel_pkg; - -/* - * Public Functions - */ - -/* - * Panel routines - */ -EXTERN_FUNCTION (Panel_item panel_advance_caret, (Panel panel)); -EXTERN_FUNCTION (Panel_item panel_backup_caret, (Panel panel)); -EXTERN_FUNCTION (void panel_show_focus_win, (Panel_item item, Frame frame, int x, int y)); - -/* - * event mapping routines - */ -EXTERN_FUNCTION (int panel_handle_event, (Panel_item item, Event *event)); -EXTERN_FUNCTION (void panel_default_handle_event, (Panel_item item, Event *event)); -EXTERN_FUNCTION (int panel_cancel, (Panel_item item, Event *event)); - -/* - * Panel_item action routines - */ -EXTERN_FUNCTION (int panel_begin_preview, (Panel_item item, Event * event)); -EXTERN_FUNCTION (int panel_update_preview, (Panel_item item, Event *event)); -EXTERN_FUNCTION (int panel_accept_preview, (Panel_item item, Event *event)); -EXTERN_FUNCTION (int panel_cancel_preview, (Panel_item item, Event *event)); -EXTERN_FUNCTION (int panel_accept_menu, (Panel_item item, Event *event)); -EXTERN_FUNCTION (int panel_accept_key, (Panel_item item, Event *event)); - -/* - * utilities - */ -EXTERN_FUNCTION (Panel_setting panel_text_notify, (Panel_item item, Event *event)); -EXTERN_FUNCTION (void panel_paint_label, (Panel_item item)); -EXTERN_FUNCTION (struct pixrect *panel_button_image, (Panel panel, char *string, int width, Xv_opaque font)); -EXTERN_FUNCTION (void panel_default_clear_item, (Panel_item item)); - -/* routines to translate event coordinates - * Note that struct inputevent * is the same as - * Event *, this is used for compatibility with previous - * releases. - */ -EXTERN_FUNCTION (Event * panel_window_event, (Panel panel, Event *event)); -EXTERN_FUNCTION (Event * panel_event, (Panel panel, Event *event)); - -/* - * For SunView 1 Compatibility Only - */ - -/* - * Panel & Panel_item routines in XView should use xv_ routines instead. - */ -EXTERN_FUNCTION (Panel_attribute_value panel_get, (Panel panel, Panel_attr attr, DOTDOTDOT)); -EXTERN_FUNCTION (int panel_set, (Panel panel, DOTDOTDOT)); -EXTERN_FUNCTION (int panel_paint, (Panel panel, Panel_setting flag)); -EXTERN_FUNCTION (int panel_free, (Panel panel)); -EXTERN_FUNCTION (int panel_destroy_item, (Panel_item item)); -EXTERN_FUNCTION (Panel_item panel_create_item, (Panel panel, Xv_pkg *item_type, DOTDOTDOT)); - -#endif /* ~xview_panel_DEFINED */ diff --git a/include/xview/pixwin.h b/include/xview/pixwin.h deleted file mode 100644 index 4cb8f122375..00000000000 --- a/include/xview/pixwin.h +++ /dev/null @@ -1,160 +0,0 @@ -/* @(#)pixwin.h 20.25 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_pixwin_DEFINED -#define xview_pixwin_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ -#include -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ -#define PIX_MAX_PLANE_GROUPS 1 -#define PW_PIXEL_CACHE_NULL ((Pw_pixel_cache *)0) - -#define XV_DEFAULT_FG_BG 0 -#define XV_INVERTED_FG_BG 1 -#define XV_USE_OP_FG 0 -#define XV_USE_CMS_FG 1 - -#define PW_ROP_NULL_SRC 0 -#define PW_VECTOR 1 -#define PW_LINE 2 -#define PW_POLYLINE 3 -#define PW_TEXT 4 -#define PW_STENCIL 5 -#define PW_POLYGON2 6 -#define PW_POLYPOINT 7 -#define PW_ROP 8 -#define PW_REPLROP 9 -#define PW_NUM_OPS 10 - -/* - * SV1 compatibility definitions. - */ -#define pw_copy(dpw, dx, dy, w, h, op, spw, sx, sy) \ - xv_rop(dpw, dx, dy, w, h, op, (Pixrect *)spw, sx, sy) - -#define pw_read(dpr, dx, dy, w, h, op, spw, sx, sy) \ - xv_read(dpr, dx, dy, w, h, op, spw, sx, sy) - -#define pw_replrop(dpw, xw, yw, width, height, op, pr, xr, yr) \ - xv_replrop(dpw, xw, yw, width, height, op, pr, xr, yr) - -#define pw_rop(dpw, dx, dy, w, h, op, sp, sx, sy) \ - xv_rop(dpw, dx, dy, w, h, op, (Pixrect *)sp, sx, sy) - -#define pw_setcmsname(pw, name) xv_set(pw, WIN_CMS_NAME, name, 0) - -#define pw_stencil(dpw, x, y, w, h, op, stpr, stx, sty, spr, sy, sx) \ - xv_stencil(dpw, x, y, w, h, op, stpr, stx, sty, spr, sy, sx) - -#define pw_text(window, xbasew, ybasew, op, pixfont, str) \ - xv_text(window, xbasew, ybasew, op, pixfont, str) - -#define pw_ttext(pw, xbasew, ybasew, op, pixfont, str) \ - xv_ttext(pw, xbasew, ybasew, op, pixfont, str) - -#define pw_vector(window, x0, y0, x1, y1, op, cms_index) \ - xv_vector(window, x0, y0, x1, y1, op, cms_index) - -#define pw_write(dpw, dx, dy, w, h, op, spr, sx, sy) \ - xv_rop(dpw, dx, dy, w, h, op, (Pixrect *)spr, sx, sy) - -#define pw_writebackground(dpw, dx, dy, w, h, op) \ - xv_rop(dpw, dx, dy, w, h, op, (Pixrect *)NULL, 0, 0) - -/* - * Obsolete SV1 pixwin functions. - */ -#define pw_batch(pw, type) -#define pw_batch_off(pw) -#define pw_batch_on(pw) -#define pw_close(pw) -#define pw_dbl_access(pw) -#define pw_dbl_flip(pw) -#define pw_dbl_release(pw) -#define pw_dbl_get(pw, attrs) -#define pw_dbl_set(pw, attrs) -#define pw_get_region_rect(pw, r) -#define pw_get_x_offset(pw) -#define pw_get_y_offset(pw) -#define pw_lock(pixwin, rect) -#define pw_region(pw, x, y, w, h) -#define pw_set_region_rect(pw, r, use_same_pr) -#define pw_set_xy_offset(pw, x_offset, y_offset) -#define pw_set_x_offset(pw, x_offset) -#define pw_set_y_offset(pw, y_offset) -#define pw_show(pw) -#define pw_unlock(pixwin) -#define pw_use_fast_monochrome(pw) - - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ -typedef struct pw_pixel_cache -{ - Rect r; - struct pixrect * plane_group[PIX_MAX_PLANE_GROUPS]; -} -Pw_pixel_cache; - -typedef struct pixwin -{ - char dummy; /* dummy field for compatibility */ -} -Pixwin; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC functions - */ - -EXTERN_FUNCTION (Pw_pixel_cache * pw_save_pixels, (Xv_opaque pw, Rect *rect)); -EXTERN_FUNCTION (void pw_restore_pixels, (Xv_opaque ps, Pw_pixel_cache *pc)); - -/* - * For SunView Pixrect/Pixwin Graphics Compatibility - */ - -EXTERN_FUNCTION (int xv_read, (Pixrect *pr, int op, int x, int y, int width, int height, Xv_opaque window, int sx, int sy)); -EXTERN_FUNCTION (int xv_replrop, (Xv_opaque window, int op, int xw, int yw, int width, int height, Pixrect *pr, int xr, int yr)); -EXTERN_FUNCTION (int xv_rop, (Xv_opaque window, int op, int x, int y, int width, int height, Pixrect *pr, int xr, int yr)); -EXTERN_FUNCTION (int xv_stencil, (Xv_opaque window, int op, int dx, int dy, int width, int height, Pixrect *stpr, int stx, int sty, Pixrect *spr, int sx, int sy)); -EXTERN_FUNCTION (int xv_text, (Xv_opaque window, int op, int xbasew, int ybasew, Xv_opaque font, char *str)); -EXTERN_FUNCTION (int xv_ttext, (Xv_opaque window, int xbasew, int ybasew, int op, Xv_opaque font, char *str)); -EXTERN_FUNCTION (int xv_vector, (Xv_opaque window, int x0, int y0, int x1, int y1, int op, int cms_index)); -EXTERN_FUNCTION (int pw_batchrop, (Pixwin *pw, int x, int y, int op, struct pr_prpos *sbp, int m)); -EXTERN_FUNCTION (int pw_get, (Xv_opaque xv_drawable, int x, int y)); -EXTERN_FUNCTION (int pw_put, (Xv_opaque pw, int x, int y, int val)); -EXTERN_FUNCTION (int pw_putattributes, (Xv_opaque pw, int *planes)); -EXTERN_FUNCTION (int pw_getattributes, (Xv_opaque pw, int *planes)); -EXTERN_FUNCTION (int pw_putcolormap, (Xv_opaque pw, int index, int count, unsigned char *red, unsigned char *green, unsigned char *blue)); -EXTERN_FUNCTION (int pw_getcolormap, (Xv_opaque pw, int index, int count, unsigned char *red, unsigned char *green, unsigned char *blue)); -EXTERN_FUNCTION (struct pixfont * pw_pfsysopen, (void)); -EXTERN_FUNCTION (int pw_pfsysclose, (void)); - -#endif /* ~xview_pixwin_DEFINED */ diff --git a/include/xview/pkg.h b/include/xview/pkg.h deleted file mode 100644 index 7d5f6075489..00000000000 --- a/include/xview/pkg.h +++ /dev/null @@ -1,108 +0,0 @@ -/* @(#)pkg.h 20.22 91/03/19 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - * Of interest to package implementors only. - */ - -#ifndef xview_pkg_DEFINED -#define xview_pkg_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -/* Don't include notify.h - it is not actually used by very many modules, and - * generates too many symbols in the libraries. - */ - -#include -#include - -#ifdef __STDC__ -#include -#else -#include -#endif - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PRIVATE #defines (for package implementors only) - */ - -#ifndef MAX_NESTED_PKGS -#define MAX_NESTED_PKGS 20 -#endif - -/* - * Conversion macros for package implementors (public <=> private) - */ - -/* - * FIXME: put debugging checks here when implemented - */ -#define XV_PRIVATE(private_type, public_type, obj) \ - ((private_type *)((public_type *) (obj))->private_data) -#define XV_PUBLIC(obj) \ - ((obj)->public_self) - -/* set procs can return XV_SET_DONE if xv_super_set_avlist() - * has been called. This will end the set. Note that - * other possible set proc return values are XV_OK or an attribute. - */ -#define XV_SET_DONE ((Xv_opaque) 2) - -#define Sv1_public extern /* SunView1 compatibility only; part of the -* client interface - */ -#define Xv_public extern /* Part of the client interface */ -#define Xv_public_data /* Part of the client interface */ -#define Xv_private extern /* Should only be used by Sv toolkit */ -#define Xv_private_data /* Should only be used by Sv toolkit */ -#define Pkg_private extern /* Should only be used by same pkg */ - - typedef struct _xview_pkg - { - char *name; - Attr_attribute attr_id; - unsigned size_of_object; - struct _xview_pkg *parent_pkg; - int (*init)(); - Xv_opaque (*set)(); - Xv_opaque (*get)(); - int (*destroy)(); - Xv_object (*find)(); - } -Xv_pkg; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PRIVATE functions for package implementors only - */ - -EXTERN_FUNCTION (Xv_object xv_create_avlist, (Xv_opaque parent, Xv_pkg *pkg, Attr_attribute *avlist)); -EXTERN_FUNCTION (Xv_opaque xv_set_avlist, (Xv_opaque passed_object, Attr_avlist avlist)); -EXTERN_FUNCTION (Xv_opaque xv_super_set_avlist, (Xv_opaque object, Xv_pkg *pkg, Attr_avlist avlist)); -EXTERN_FUNCTION (int xv_destroy_status, (Xv_object passed_object, Destroy_status status)); -EXTERN_FUNCTION (int xv_check_bad_attr, (Xv_pkg *pkg, Attr_attribute attr)); -EXTERN_FUNCTION (Xv_opaque xv_get_varargs, (Xv_opaque passed_object, Attr_attribute attr, va_list valist)); - - -#endif /* ~xview_pkg_DEFINED */ diff --git a/include/xview/pkg_public.h b/include/xview/pkg_public.h deleted file mode 100644 index e914bc72e56..00000000000 --- a/include/xview/pkg_public.h +++ /dev/null @@ -1,92 +0,0 @@ -/* @(#)pkg_public.h 20.24 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_pkg_public_DEFINED -#define xview_pkg_public_DEFINED - - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include - - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - * - * SunView pkg. definition - */ - -/* - * PRIVATE structures for pkg implementors only - */ - -/* - * Last field before "embedded" struct in an "embedding object". - */ -typedef long unsigned Xv_embedding; - - -/* - * Base instance for all objects - */ -typedef struct -{ - long unsigned seal; /* Has "special" value meaning "am object" */ - Xv_pkg *pkg; /* Always points to pkg chain for an object */ -} -Xv_base; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC General interface functions - */ -EXTERN_FUNCTION (Xv_object xv_create, (Xv_opaque owner, Xv_pkg *pkg, DOTDOTDOT)); -EXTERN_FUNCTION (Xv_object xv_find, (Xv_opaque owner, Xv_pkg *pkg, DOTDOTDOT)); -EXTERN_FUNCTION (Xv_opaque xv_set, (Xv_opaque object, DOTDOTDOT)); -EXTERN_FUNCTION (Xv_opaque xv_get, (Xv_opaque object, Attr_attribute attr, DOTDOTDOT)); -EXTERN_FUNCTION (int xv_destroy_safe, (Xv_object object)); -EXTERN_FUNCTION (int xv_destroy_check, (Xv_object object)); -EXTERN_FUNCTION (int xv_destroy, (Xv_object object)); -EXTERN_FUNCTION (int xv_destroy_immediate,(Xv_object object)); - -/* - * PRIVATE functions for pkg implementors only - */ - -EXTERN_FUNCTION (Xv_opaque xv_object_to_standard, (Xv_object object, const char *caller)); - -#if !(defined(__STDC__) || defined(__cplusplus) || defined(c_plusplus)) -#define const -#endif -extern const char *xv_notptr_str; -#define XV_OBJECT_SEAL 0xF0A58142 -#define XV_OBJECT_TO_STANDARD(_passed_object, _caller, _object)\ -{\ - if (!_passed_object) {\ - xv_error(NULL, ERROR_INVALID_OBJECT,xv_notptr_str,\ - ERROR_STRING, _caller,\ - 0);\ - _object = ((Xv_opaque)0);\ - }\ - else\ - _object = (((Xv_base *)_passed_object)->seal == XV_OBJECT_SEAL) ? _passed_object : xv_object_to_standard(_passed_object, _caller);\ -} - -#endif /* xview_pkg_public_DEFINED */ diff --git a/include/xview/rect.h b/include/xview/rect.h deleted file mode 100644 index 46a66091358..00000000000 --- a/include/xview/rect.h +++ /dev/null @@ -1,146 +0,0 @@ -/* @(#)rect.h 20.19 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - * Defines the interface to the geometric object - * called a Rect which is a rectangle. - */ - -#ifndef xview_rect_DEFINED -#define xview_rect_DEFINED - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define RECT_NULL ((Rect *)0) - -#ifndef coord -#define coord short -#endif - -/* - * Rectangle sort ordering. - */ -#define RECTS_TOPTOBOTTOM 0 -#define RECTS_BOTTOMTOTOP 1 -#define RECTS_LEFTTORIGHT 2 -#define RECTS_RIGHTTOLEFT 3 - -#define RECTS_UNSORTED -1 -#define RECTS_SORTS 4 - -/* - * Rect Geometry macros - */ -#define rect_right(rect) ((rect)->r_left+(rect)->r_width-1) -#define rect_bottom(rect) ((rect)->r_top+(rect)->r_height-1) - -#define rect_print(rect) \ - (void)fprintf(stderr,"[left: %d, top: %d, width: %d, height: %d]\n", \ - (rect)->r_left, (rect)->r_top, (rect)->r_width, (rect)->r_height) - -#define rect_marginadjust(r,m) \ - { (r)->r_left-=(m);(r)->r_top-=(m); \ - (r)->r_width+=(m)+(m);(r)->r_height+=(m)+(m);} - -#define rect_borderadjust(r,m) \ - { (r)->r_width+=(m)+(m);(r)->r_height+=(m)+(m);} - -#define rect_construct(r,x,y,w,h) \ - {(r)->r_left=(x);(r)->r_top=(y);(r)->r_width=(w);(r)->r_height=(h);} - -/* - * Rect Predicate macros - */ -#define rect_equal(r1,r2) \ - ((r1)->r_left==(r2)->r_left && (r1)->r_width==(r2)->r_width && \ - (r1)->r_top==(r2)->r_top && (r1)->r_height==(r2)->r_height) - -#define rect_sizes_differ(r1, r2) \ - ((r1)->r_width != (r2)->r_width || (r1)->r_height != (r2)->r_height) - -#define rect_isnull(r) ((r)->r_width == 0 || (r)->r_height == 0) - -#define rect_includespoint(r,x,y) \ - ((x) >= (r)->r_left && (y) >= (r)->r_top && \ - (x)<(r)->r_left+(r)->r_width && (y)<(r)->r_top+(r)->r_height) - -#define rect_includesrect(r1, r2) \ - ((r1)->r_left <= (r2)->r_left && (r1)->r_top <= (r2)->r_top && \ - (r1)->r_left+(r1)->r_width >= (r2)->r_left+(r2)->r_width && \ - (r1)->r_top+(r1)->r_height >= (r2)->r_top+(r2)->r_height) - -#define rect_intersectsrect(r1,r2) \ - ((r1)->r_left<(r2)->r_left+(r2)->r_width && \ - (r1)->r_top<(r2)->r_top+(r2)->r_height && \ - (r2)->r_left<(r1)->r_left+(r1)->r_width && \ - (r2)->r_top<(r1)->r_top+(r1)->r_height) - -/* - * Rect Transformation macros used for passing rects up/down embedded - * coordinate systems. - */ -#define rect_passtoparent(x,y,rect) \ - {(rect)->r_left=(rect)->r_left+(x); (rect)->r_top=(rect)->r_top+(y);} - -#define rect_passtochild(x,y,rect) \ - {(rect)->r_left=(rect)->r_left-(x); (rect)->r_top=(rect)->r_top-(y);} - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -/* - * PUBLIC structures - */ - -typedef struct rect -{ - coord r_left, r_top; - short r_width, r_height; -} -Rect; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC variables - */ -extern struct rect rect_null; - -/* - * PUBLIC Functions - */ - -EXTERN_FUNCTION (struct rect rect_bounding, (Rect *r1, Rect *r2)); -EXTERN_FUNCTION (unsigned rect_clipvector, (Rect *rect, int *x1arg, int *y1arg, int *x2arg, int *y2arg)); -EXTERN_FUNCTION (unsigned rect_order, (Rect *rl, Rect *r2, int sortorder)); -EXTERN_FUNCTION (int rect_right_of, (Rect *rect1, Rect *rect2)); -EXTERN_FUNCTION (int rect_below, (Rect *rect1, Rect *rect2)); -#ifdef _OTHER_RECT_FUNCTIONS - -EXTERN_FUNCTION (void rect_intersection, (Rect *rl, Rect *r2, Rect *r)); -EXTERN_FUNCTION (int rect_distance, (Rect *rect, int x, int y, int * x_used, int * y_used)); -#endif /* _OTHER_RECT_FUNCTIONS */ - -#endif /* ~xview_rect_DEFINED */ diff --git a/include/xview/rectlist.h b/include/xview/rectlist.h deleted file mode 100644 index 871fae0a784..00000000000 --- a/include/xview/rectlist.h +++ /dev/null @@ -1,125 +0,0 @@ -/* @(#)rectlist.h 20.15 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_rectlist_DEFINED -#define xview_rectlist_DEFINED - -#include - -/* - * Defines the interface to the data structure called - * a rectlist which is a list of rectangles. - * - * A rectlist has an offset (rl_x, rl_y) assoicated with it that is used - * to efficiently pass this data structure from one embedded coordinate - * system to another without changing the offsets of all the rectangles in - * the list. - * - * Rl_bound is the rectangle that bounds all the rectangles in the list - * and is maintained to facilitate efficient rectangle algebra. - */ - - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define RECTNODE_NULL ((Rectnode *)0) -#define RECTLIST_NULL ((Rectlist *)0) - -/* - * Rectlist Transformation macros used for passing rectlists up/down embedded - * coordinate systems. - */ -#define rl_passtoparent(x,y,rl) \ - {(rl)->rl_x=(rl)->rl_x+(x); (rl)->rl_y=(rl)->rl_y+(y);} - -#define rl_passtochild(x,y,rl) \ - {(rl)->rl_x=(rl)->rl_x-(x); (rl)->rl_y=(rl)->rl_y-(y);} - -/* - * Rectlist Offset Adjustment macros - */ -#define rl_rectoffset(rl,r1,r) \ - {*(r)= *(r1); (r)->r_left+=(rl)->rl_x; (r)->r_top+=(rl)->rl_y;} - -#define rl_coordoffset(rl,x,y) {*(x)-=(rl)->rl_x;*(y)-=(rl)->rl_y;} - - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -/* - * PUBLIC structures - */ - -typedef struct rectnode -{ - struct rectnode *rn_next; /* Pointer to next rectnode */ - struct rect rn_rect; -} -Rectnode; - - -typedef struct rectlist -{ - coord rl_x, rl_y; /* Offset to apply to each rect - in list including bound */ - struct rectnode *rl_head; /* Pointer to first rectnode */ - struct rectnode *rl_tail; /* Pointer to last rectnode */ - struct rect rl_bound; /* Describes bounding rect of - all rects in list */ -} -Rectlist; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC functions - */ -extern struct rectlist rl_null; - -EXTERN_FUNCTION (unsigned rl_empty, (Rectlist *rl)); -EXTERN_FUNCTION (unsigned rl_equal, (Rectlist *rl1, Rectlist *rl2)); -EXTERN_FUNCTION (unsigned rl_boundintersectsrect, (Rect *r, Rectlist *rl)); -EXTERN_FUNCTION (unsigned rl_rectintersects, (Rect *r, Rectlist *rl)); -EXTERN_FUNCTION (unsigned rl_equalrect, (Rect *r, Rectlist *rl)); -EXTERN_FUNCTION (unsigned rl_includespoint, (Rectlist *r, int x, int y)); - -#ifdef xview_other_rl_funcs - -EXTERN_FUNCTION (void rl_rectintersection, (Rect *r, Rectlist *rl1, Rectlist *rl)); -EXTERN_FUNCTION (void rl_rectunion, (Rect *r, Rectlist *rl1, Rectlist *rl)); -EXTERN_FUNCTION (void rl_rectdifference, (Rect *r, Rectlist *rl1, Rectlist *rl)); -EXTERN_FUNCTION (void rl_intersection, (Rectlist *rl1, Rectlist *rl2, Rectlist *rl)); -EXTERN_FUNCTION (void rl_sort, (Rectlist *rl1, Rectlist *rl, int sortorder)); -EXTERN_FUNCTION (void rl_union, (Rectlist *rl1, Rectlist *rl2, Rectlist *rl)); -EXTERN_FUNCTION (void rl_difference, (Rectlist *rl1, Rectlist *rl2, Rectlist *rl)); -EXTERN_FUNCTION (void rl_initwithrect, (Rect *r, Rectlist *rl)); -EXTERN_FUNCTION (void rl_copy, (Rectlist *rl1, Rectlist *rl)); -EXTERN_FUNCTION (void rl_free, (Rectlist *rl)); -EXTERN_FUNCTION (void rl_coalesce, (Rectlist *rl)); -EXTERN_FUNCTION (void rl_normalize, (Rectlist *rl)); -EXTERN_FUNCTION (void rl_print, (Rectlist *rl, char *tag)); - -#endif /* xview_other_rl_funcs */ - -#endif /* ~xview_rectlist_DEFINED */ diff --git a/include/xview/screen.h b/include/xview/screen.h deleted file mode 100644 index 9fa4d4ae8fb..00000000000 --- a/include/xview/screen.h +++ /dev/null @@ -1,125 +0,0 @@ -/* @(#)screen.h 20.35 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_screen_DEFINED -#define xview_screen_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -#ifndef XV_ATTRIBUTES_ONLY - -/* - * PUBLIC #defines - */ - -#define SCREEN &xv_screen_pkg - -/* - * PRIVATE #defines - */ - -#define SCREEN_TYPE ATTR_PKG_SCREEN - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -#define SCREEN_ATTR(type, ordinal) ATTR(ATTR_PKG_SCREEN, type, ordinal) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -#ifndef XV_ATTRIBUTES_ONLY - -typedef Xv_opaque Xv_Screen; -typedef Xv_opaque Xv_screen; - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -typedef enum { - /* - * Public attributes - */ - SCREEN_NUMBER = SCREEN_ATTR(ATTR_INT, 10), - SCREEN_SERVER = SCREEN_ATTR(ATTR_OPAQUE, 15), - /* - * Private attributes - */ - SCREEN_DEFAULT_VISUAL = SCREEN_ATTR(ATTR_OPAQUE, 75), /* G-- */ - SCREEN_VISUAL = SCREEN_ATTR(ATTR_OPAQUE, 80), /* G-- */ - /* Format: xv_get(screen, SCREEN_VISUAL, vinfo_template, vinfo_mask); */ - SCREEN_IMAGE_VISUAL = SCREEN_ATTR(ATTR_OPAQUE, 85), /* G-- */ - /* Format: xv_get(screen, SCREEN_IMAGE_VISUAL, xid, depth); */ - SCREEN_DEFAULT_CMS = SCREEN_ATTR(ATTR_OPAQUE, 30), - SCREEN_RETAIN_WINDOWS = SCREEN_ATTR(ATTR_BOOLEAN, 40), - SCREEN_BG1_PIXMAP = SCREEN_ATTR(ATTR_OPAQUE, 50), - SCREEN_BG2_PIXMAP = SCREEN_ATTR(ATTR_OPAQUE, 55), - SCREEN_BG3_PIXMAP = SCREEN_ATTR(ATTR_OPAQUE, 60), - SCREEN_GINFO = SCREEN_ATTR(ATTR_OPAQUE, 65), - SCREEN_OLGC_LIST = SCREEN_ATTR(ATTR_OPAQUE, 70), /* G-- */ - SCREEN_SUN_WINDOW_STATE = SCREEN_ATTR(ATTR_BOOLEAN, 90), - SCREEN_SELECTION_STATE = SCREEN_ATTR(ATTR_LONG, 95) - -} Screen_attr; - -/* Define the different types of GC available in the GC list */ -#define SCREEN_SET_GC 0 -#define SCREEN_CLR_GC 1 -#define SCREEN_TEXT_GC 2 -#define SCREEN_BOLD_GC 3 -#define SCREEN_GLYPH_GC 4 -#define SCREEN_INACTIVE_GC 5 -#define SCREEN_DIM_GC 6 -#define SCREEN_INVERT_GC 7 -#define SCREEN_NONSTD_GC 8 /* Color or non-standard font */ -#define SCREEN_RUBBERBAND_GC 9 -#define SCREEN_OLGC_LIST_SIZE 10 - -#ifndef XV_ATTRIBUTES_ONLY - -typedef struct -{ - Xv_generic_struct parent; - Xv_opaque private_data; -} -Xv_screen_struct; - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC Variables - */ - -extern Xv_Screen xv_default_screen; - -/* - * PRIVATE Variables - */ - -extern Xv_pkg xv_screen_pkg; - -#endif /* ~xview_screen_DEFINED */ diff --git a/include/xview/scrollbar.h b/include/xview/scrollbar.h deleted file mode 100644 index 38e94c63e75..00000000000 --- a/include/xview/scrollbar.h +++ /dev/null @@ -1,157 +0,0 @@ -/* @(#)scrollbar.h 1.35 91/03/19 */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_scrollbar_DEFINED -#define xview_scrollbar_DEFINED - -/* - * Module: scrollbar.h - * Library: libxview.a - * - * Level: public - * - * Description: Describes attributes for scrollbar - * - */ - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define SCROLLBAR &xv_scrollbar_pkg - -#define SCROLLBAR_FIRST vuid_first(SCROLL_DEVID) /* 32256 */ -#define SCROLLBAR_REQUEST (SCROLLBAR_FIRST+0) /* 32256 */ - -/* SunView1 Compatiblity */ -#define SCROLL_LINE_HEIGHT SCROLLBAR_PIXELS_PER_UNIT - -/* - * PRIVATE #defines - */ - -#define SCROLLBAR_ATTR(type, ordinal) ATTR(ATTR_PKG_SCROLLBAR, type, ordinal) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -typedef Xv_opaque Scrollbar; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_scrollbar; - -typedef enum { - /* - * Public Attributes - */ - SCROLLBAR_COMPUTE_SCROLL_PROC = SCROLLBAR_ATTR(ATTR_FUNCTION_PTR, 6), - SCROLLBAR_DIRECTION = SCROLLBAR_ATTR(ATTR_ENUM, 8), - SCROLLBAR_INACTIVE = SCROLLBAR_ATTR(ATTR_BOOLEAN, 13), - SCROLLBAR_LAST_VIEW_START = SCROLLBAR_ATTR(ATTR_INT, 10), - SCROLLBAR_MENU = SCROLLBAR_ATTR(ATTR_OPAQUE, 11), - SCROLLBAR_NORMALIZE_PROC = SCROLLBAR_ATTR(ATTR_FUNCTION_PTR, 5), - SCROLLBAR_NOTIFY_CLIENT = SCROLLBAR_ATTR(ATTR_OPAQUE, 9), - SCROLLBAR_OBJECT_LENGTH = SCROLLBAR_ATTR(ATTR_INT, 1), - SCROLLBAR_OVERSCROLL = SCROLLBAR_ATTR(ATTR_INT, 12), - SCROLLBAR_PAGE_LENGTH = SCROLLBAR_ATTR(ATTR_INT, 4), - SCROLLBAR_PERCENT_OF_DRAG_REPAINTS = SCROLLBAR_ATTR(ATTR_INT, 14), - SCROLLBAR_PIXELS_PER_UNIT = SCROLLBAR_ATTR(ATTR_INT, 0), - SCROLLBAR_SPLITTABLE = SCROLLBAR_ATTR(ATTR_BOOLEAN, 7), - SCROLLBAR_VIEW_START = SCROLLBAR_ATTR(ATTR_INT, 2), - SCROLLBAR_VIEW_LENGTH = SCROLLBAR_ATTR(ATTR_INT, 3) -} Scrollbar_attribute; - - -typedef enum { - /* - * absolute motion - */ - SCROLLBAR_ABSOLUTE, - /* - * forward motions - */ - SCROLLBAR_POINT_TO_MIN, - SCROLLBAR_PAGE_FORWARD, - SCROLLBAR_LINE_FORWARD, - /* - * backward motions - */ - SCROLLBAR_MIN_TO_POINT, - SCROLLBAR_PAGE_BACKWARD, - SCROLLBAR_LINE_BACKWARD, - /* - * first last motions - */ - SCROLLBAR_TO_END, - SCROLLBAR_TO_START, - SCROLLBAR_PAGE_ALIGNED, - /* - * no scrolling - */ - SCROLLBAR_NONE -} Scroll_motion; - -typedef enum { - SCROLLBAR_VERTICAL, - SCROLLBAR_HORIZONTAL -} Scrollbar_setting; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_scrollbar_pkg; - -/* - * Public functions - */ - -EXTERN_FUNCTION (void scrollbar_default_compute_scroll_proc, (Scrollbar sb, int pos, int length, Scroll_motion motion, unsigned long *offset, unsigned long *object_length)); - -EXTERN_FUNCTION (void scrollbar_paint, (Scrollbar sb)); - -/* - * XView-private functions - */ -EXTERN_FUNCTION (int scrollbar_width_for_scale, (Window_rescale_state scale)); - -/* - * For SunView 1 Compatibility - */ -EXTERN_FUNCTION (Scrollbar scrollbar_create, (Attr_attribute attr1, DOTDOTDOT)); -EXTERN_FUNCTION (int scrollbar_set, (Scrollbar sb, DOTDOTDOT)); -EXTERN_FUNCTION (Xv_opaque scrollbar_get, (Scrollbar sb, Scrollbar_attribute attr)); -EXTERN_FUNCTION (int scrollbar_destroy, (Scrollbar sb)); -EXTERN_FUNCTION (void scrollbar_scroll_to, (Scrollbar sb, unsigned long new_start)); - -#endif /* ~xview_scrollbar_DEFINED */ diff --git a/include/xview/sel_attrs.h b/include/xview/sel_attrs.h deleted file mode 100644 index d7bda62d26b..00000000000 --- a/include/xview/sel_attrs.h +++ /dev/null @@ -1,119 +0,0 @@ -/* @(#)sel_attrs.h 20.20 91/09/14 */ - -#ifndef xview_selection_attributes_DEFINED -#define xview_selection_attributes_DEFINED - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PRIVATE #defines - */ - -/* - * Common requests a client may send to a selection-holder - */ -#define ATTR_PKG_SELN ATTR_PKG_SELN_BASE - -#define SELN_ATTR(type, n) ATTR(ATTR_PKG_SELN, type, n) - -#define SELN_ATTR_LIST(list_type, type, n) \ - ATTR(ATTR_PKG_SELN, ATTR_LIST_INLINE(list_type, type), n) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -/* - * Public Enumerations - */ - -/* - * Attributes of selections - * The numbering scheme has to match the scheme of Sunview selection_attributes.h - */ -typedef enum { - /* - * Public Attributes - */ - SELN_REQ_BYTESIZE = SELN_ATTR(ATTR_INT, 1), - SELN_REQ_COMMIT_PENDING_DELETE - = SELN_ATTR(ATTR_NO_VALUE, 65), - SELN_REQ_CONTENTS_ASCII = SELN_ATTR_LIST(ATTR_NULL, ATTR_CHAR, 2), - -#ifdef OW_I18N - SELN_REQ_CONTENTS_WCS = SELN_ATTR_LIST(ATTR_NULL, ATTR_WCHAR, 202), - SELN_REQ_CHARSIZE = SELN_ATTR(ATTR_INT, 204), - SELN_REQ_FILE_NAME_WCS = SELN_ATTR_LIST(ATTR_NULL, ATTR_WCHAR, 205), -#endif /*OW_I18N*/ - - SELN_REQ_CONTENTS_PIECES= SELN_ATTR_LIST(ATTR_NULL, ATTR_CHAR, 3), - SELN_REQ_DELETE = SELN_ATTR(ATTR_NO_VALUE, 66), - SELN_REQ_END_REQUEST = SELN_ATTR(ATTR_NO_VALUE, 253), - SELN_REQ_FAILED = SELN_ATTR(ATTR_INT, 255), - SELN_REQ_FAKE_LEVEL = SELN_ATTR(ATTR_INT, 98), - SELN_REQ_FILE_NAME = SELN_ATTR_LIST(ATTR_NULL, ATTR_CHAR, 9), - SELN_REQ_FIRST = SELN_ATTR(ATTR_INT, 4), - SELN_REQ_FIRST_UNIT = SELN_ATTR(ATTR_INT, 5), - SELN_REQ_LAST = SELN_ATTR(ATTR_INT, 6), - SELN_REQ_LAST_UNIT = SELN_ATTR(ATTR_INT, 7), - SELN_REQ_LEVEL = SELN_ATTR(ATTR_INT, 8), - SELN_REQ_RESTORE = SELN_ATTR(ATTR_NO_VALUE, 67), - SELN_REQ_SET_LEVEL = SELN_ATTR(ATTR_INT, 99), - SELN_REQ_UNKNOWN = SELN_ATTR(ATTR_INT, 254), - SELN_REQ_YIELD = SELN_ATTR(ATTR_ENUM, 97), - /* - * Private Attributes - */ -#ifdef OW_I18N - SELN_REQ_CONTENTS_CT = SELN_ATTR_LIST(ATTR_NULL, ATTR_CHAR, 203), -#endif /*OW_I18N*/ - - SELN_AGENT_INFO = SELN_ATTR(ATTR_OPAQUE, 100), - SELN_REQ_FUNC_KEY_STATE = SELN_ATTR(ATTR_INT, 101), - SELN_REQ_SELECTED_WINDOWS= SELN_ATTR_LIST(ATTR_NULL, ATTR_INT, 102), - SELN_REQ_CONTENTS_OBJECT= SELN_ATTR_LIST(ATTR_NULL, ATTR_CHAR, 103), - SELN_REQ_OBJECT_SIZE = SELN_ATTR(ATTR_INT, 104), - SELN_REQ_IS_READONLY = SELN_ATTR(ATTR_BOOLEAN, 105), - SELN_TRACE_ACQUIRE = SELN_ATTR(ATTR_BOOLEAN, 193), - SELN_TRACE_DONE = SELN_ATTR(ATTR_BOOLEAN, 194), - SELN_TRACE_DUMP = SELN_ATTR(ATTR_ENUM, 200), - SELN_TRACE_HOLD_FILE = SELN_ATTR(ATTR_BOOLEAN, 195), - SELN_TRACE_INFORM = SELN_ATTR(ATTR_BOOLEAN, 196), - SELN_TRACE_INQUIRE = SELN_ATTR(ATTR_BOOLEAN, 197), - SELN_TRACE_STOP = SELN_ATTR(ATTR_BOOLEAN, 199), - SELN_TRACE_YIELD = SELN_ATTR(ATTR_BOOLEAN, 198) -} Seln_attribute; - -/* Meta-levels available for use with SELN_REQ_FAKE/SET_LEVEL. - * SELN_LEVEL_LINE is "text line bounded by newline characters, - * including only the terminating newline" - */ -typedef enum { - SELN_LEVEL_FIRST = 0x40000001, - SELN_LEVEL_LINE = 0x40000101, - SELN_LEVEL_ALL = 0x40008001, - SELN_LEVEL_NEXT = 0x4000F001, - SELN_LEVEL_PREVIOUS = 0x4000F002 -} Seln_level; - -#endif /* ~xview_selection_attributes_DEFINED */ diff --git a/include/xview/sel_compat.h b/include/xview/sel_compat.h deleted file mode 100644 index 0e70b71de8d..00000000000 --- a/include/xview/sel_compat.h +++ /dev/null @@ -1,46 +0,0 @@ -/* @(#)sel_compat.h 1.16 91/09/14 */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_selection_compat_DEFINED -#define xview_selection_compat_DEFINED - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - * For Compatibility with SunView 1 - */ - -#define seln_acquire(seln_client, asked) \ - selection_acquire(xv_default_server, seln_client, asked) -#define seln_done(seln_client, rank) \ - selection_done(xv_default_server, seln_client, rank) -#define seln_inform(seln_client, which, down) \ - selection_inform(xv_default_server, seln_client, which, down) -#define seln_get_function_state(func) \ - selection_get_function_state(server, func) -#define seln_inquire(which) \ - selection_inquire(xv_default_server, which) -#define seln_clear_functions() \ - selection_clear_functions(xv_default_server) -#define seln_request(holder, buffer) \ - selection_request(xv_default_server, holder, buffer) -#define seln_send_yield(rank, holder) \ - selection_send_yield(xv_default_server, rank, holder) -#define seln_function_pending() \ - selection_function_pending(xv_default_sever) -#define seln_report_event(seln_client, event) \ - selection_report_event(xv_default_server, seln_client, event) - -#endif ~xview_selection_compat_DEFINED diff --git a/include/xview/sel_pkg.h b/include/xview/sel_pkg.h deleted file mode 100644 index d312c5644af..00000000000 --- a/include/xview/sel_pkg.h +++ /dev/null @@ -1,243 +0,0 @@ -#ifndef lint -#ifdef sccs -static char sccsid[] = "@(#)sel_pkg.h 1.5 90/11/13"; -#endif -#endif - -/* - * (c) Copyright 1990 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_selection_DEFINED -#define xview_selection_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include -#include -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * Package definitions - */ -#define SELECTION &xv_sel_pkg -#define SELECTION_OWNER &xv_sel_owner_pkg -#define SELECTION_REQUESTOR &xv_sel_requestor_pkg -#define SELECTION_ITEM &xv_sel_item_pkg - - -/* - * Various utility macros - */ - - -/* - * Public constants - */ - - -/* - * PRIVATE #defines - */ - -#define SEL_ATTR(type, ordinal) ATTR(ATTR_PKG_SELECTION, type, ordinal) -#define SEL_ATTR_LIST(ltype, type, ordinal) \ - SEL_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - - -/* Errors */ -#define SEL_ERROR -1 - -#define SEL_BEGIN_MULTIPLE 2 -#define SEL_END_MULTIPLE 4 -#define SEL_MULTIPLE 8 - -#define SEL_BAD_TIME 0 -#define SEL_BAD_WIN_ID 1 -#define SEL_BAD_PROPERTY 2 -#define SEL_BAD_CONVERSION 3 -#define SEL_TIMEDOUT 4 -#define SEL_PROPERTY_DELETED 5 -#define SEL_BAD_PROPERTY_EVENT 6 - -#define SEL_INCREMENT 2 -#define SEL_EMPTY 1 -#define SEL_PROPERTY_DATA 1 - -#define SEL_BUSY 1 -#define SEL_LOSE 2 -#define SEL_LOCAL_PROCESS 4 -#define SEL_ADD_PROP_NOTIFY 8 -#define SEL_INTERNAL_ERROR 16 - -#define OLD_SEL_CLIENT 2 -#define NEW_SEL_CLIENT 4 - - -#define MAX_NUM_INCR 20 - -#define MAX_SEL_BUFF_SIZE(dpy) ( XMaxRequestSize(dpy) ) -#define BYTE_SIZE( len, format ) ( ( len * format ) >> 3 ) - - -/* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -/* - * Typedefs - */ -typedef Xv_opaque Selection; -typedef Selection Selection_owner; -typedef Selection Selection_requestor; -typedef Xv_opaque Selection_item; - -/* - * Enumerations - */ -typedef enum -{ - - /* - * Public Attributes - */ - /* Common Selection package attributes */ - SEL_DATA = SEL_ATTR(ATTR_OPAQUE, 5), - SEL_TYPE = SEL_ATTR(ATTR_LONG, 10), - SEL_TYPE_NAME = SEL_ATTR(ATTR_STRING, 15), - - /* Selection object attributes */ - SEL_RANK = SEL_ATTR(ATTR_LONG, 20), - SEL_RANK_NAME = SEL_ATTR(ATTR_STRING, 25), - SEL_TIME = SEL_ATTR(ATTR_OPAQUE, 30), - SEL_TIMEOUT_VALUE = SEL_ATTR(ATTR_INT, 35), - - /* Selection_owner object attributes */ - SEL_CONVERT_PROC = SEL_ATTR(ATTR_FUNCTION_PTR, 40), - SEL_DONE_PROC = SEL_ATTR(ATTR_FUNCTION_PTR, 45), - SEL_FIRST_ITEM = SEL_ATTR(ATTR_OPAQUE, 50), - SEL_LOSE_PROC = SEL_ATTR(ATTR_FUNCTION_PTR, 55), - SEL_NEXT_ITEM = SEL_ATTR(ATTR_OPAQUE, 60), - SEL_OWN = SEL_ATTR(ATTR_BOOLEAN, 65), - SEL_PROP_INFO = SEL_ATTR(ATTR_OPAQUE, 70), - SEL_PROPERTY = SEL_ATTR(ATTR_LONG, 75), - - /* Selection_requestor object attributes */ - SEL_REPLY_PROC = SEL_ATTR(ATTR_FUNCTION_PTR, 80), - SEL_TYPES = SEL_ATTR_LIST(ATTR_NULL, ATTR_LONG, 85), - SEL_TYPE_NAMES = SEL_ATTR_LIST(ATTR_NULL, ATTR_STRING, 90), - SEL_PROP_DATA = SEL_ATTR(ATTR_OPAQUE, 95), - SEL_PROP_FORMAT = SEL_ATTR(ATTR_INT, 100), - SEL_PROP_LENGTH = SEL_ATTR(ATTR_LONG, 105), - SEL_PROP_TYPE = SEL_ATTR(ATTR_LONG, 110), - SEL_PROP_TYPE_NAME = SEL_ATTR(ATTR_STRING, 115), - SEL_TYPE_INDEX = SEL_ATTR(ATTR_INT, 120), - SEL_APPEND_TYPES = SEL_ATTR_LIST(ATTR_NULL, ATTR_LONG, 125), - SEL_APPEND_TYPE_NAMES = SEL_ATTR_LIST(ATTR_NULL, ATTR_STRING, 130), - /* Selection_item object attributes */ - SEL_COPY = SEL_ATTR(ATTR_BOOLEAN, 135), - SEL_FORMAT = SEL_ATTR(ATTR_INT, 140), - SEL_LENGTH = SEL_ATTR(ATTR_LONG, 145) - - /* - * Private Attributes - */ -} -Selection_attr; - -/* - * Structures - */ - -typedef struct -{ - Xv_generic_struct parent_data; - Xv_opaque private_data; -} -Xv_sel; - -typedef struct -{ - Xv_sel parent_data; - Xv_opaque private_data; -} -Xv_sel_owner; - -typedef struct -{ - Xv_sel parent_data; - Xv_opaque private_data; -} -Xv_sel_requestor; - -typedef struct -{ - Xv_sel_owner parent_data; - Xv_opaque private_data; -} -Xv_sel_item; - - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * Package Structures - */ -extern Xv_pkg xv_sel_pkg; -extern Xv_pkg xv_sel_owner_pkg; -extern Xv_pkg xv_sel_requestor_pkg; -extern Xv_pkg xv_sel_item_pkg; - -/* - * Public Functions - */ - -EXTERN_FUNCTION (Bool sel_convert_proc, (Selection_owner sel_owner, Atom * type, Xv_opaque *data, unsigned long *length, int *format)); -EXTERN_FUNCTION (void sel_post_request, (Selection_requestor sel_req)); - - -typedef struct sel_prop_info -{ - Xv_opaque data; - int format; /* data element size: 8, 16 or 32 bits */ - unsigned long length; /* nbr of elements in data */ - Atom type; - char *typeName; -} -Sel_prop_info; - - -typedef struct sel_compat_info -{ - Window owner; - Atom selection; - int clientType; - struct sel_compat_info *next; -} -Sel_cmpat_info; - -extern XContext cmpatCtx; - -#endif /* ~xview_selection_DEFINED */ diff --git a/include/xview/sel_svc.h b/include/xview/sel_svc.h deleted file mode 100644 index a173342569c..00000000000 --- a/include/xview/sel_svc.h +++ /dev/null @@ -1,314 +0,0 @@ -/* @(#)sel_svc.h 20.34 91/09/14 SMI */ - -#ifndef xview_selection_svc_DEFINED -#define xview_selection_svc_DEFINED - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#ifdef TRUE -#undef TRUE -#define TRUE 1 -#endif - -#ifdef FALSE -#undef FALSE -#define FALSE 0 -#endif - -#define SELN_REPORT(event) seln_report_event(0, event) - -/* - * routines & data for keeping track of the state of the function keys - */ - -#define selection_function_pending(server) \ - server_get_seln_function_pending(server) -#define seln_function_clear(server) \ - server_set_seln_function_pending(server, 0) - -/* - * possibly useful predicates - */ -#define seln_holder_is_me(client, holder) \ - (seln_holder_same_client(client, holder)) - -/* - * PRIVATE #defines - */ - -#define SELN_FUNCTION_WORD_COUNT 8 /* 256 bits should last a while */ - -#define SELN_RPC_BUFSIZE 2048 -#define SELN_BUFSIZE (SELN_RPC_BUFSIZE \ - - 128 \ - - sizeof(Seln_replier_data *) \ - - sizeof(Seln_requester) \ - - sizeof(char *) \ - - sizeof(Seln_rank) \ - - sizeof(Seln_result) \ - - sizeof(unsigned)) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -/* - * Seln_client: opaque handle returned to client from create - */ -typedef char *Seln_client; - -/* - * PUBLIC enums - */ - -/* - * Seln_result: Standard return codes - */ -typedef enum { - SELN_FAILED, SELN_SUCCESS, /* the basic all-around uses */ - SELN_NON_EXIST, SELN_DIDNT_HAVE, SELN_WRONG_RANK, /* special cases */ - SELN_CONTINUED, SELN_CANCEL, SELN_UNRECOGNIZED, - SELN_OVER -} Seln_result; - -/* - * Seln_rank: Selection identifiers - */ -typedef enum { - SELN_UNKNOWN = 0, - SELN_CARET = 1, - SELN_PRIMARY = 2, - SELN_SECONDARY = 3, - SELN_SHELF = 4, - SELN_UNSPECIFIED = 5 -} Seln_rank; - -/* - * Seln_function: Modes which affect rank of selection, - * controlled by function-keys or their programmatic equivalents - */ -typedef enum { - SELN_FN_ERROR = 0, - SELN_FN_STOP = 1, SELN_FN_AGAIN = 2, - SELN_FN_PROPS = 3, SELN_FN_UNDO = 4, - SELN_FN_FRONT = 5, SELN_FN_PUT = 6, - SELN_FN_OPEN = 7, SELN_FN_GET = 8, - SELN_FN_FIND = 9, SELN_FN_DELETE = 10 -} Seln_function; - -#define SELN_FN_COPY SELN_FN_PUT -#define SELN_FN_PASTE SELN_FN_GET -#define SELN_FN_CUT SELN_FN_DELETE - -/* - * Seln_state: States a selection (or its holder) may be in - */ -typedef enum { - SELN_NONE, SELN_EXISTS, SELN_FILE -} Seln_state; - -/* - * Seln_response: possible appropriate responses to a Seln_function_buffer - */ -typedef enum { - SELN_IGNORE, SELN_REQUEST, SELN_FIND, SELN_SHELVE, SELN_DELETE -} Seln_response; - -/* - * PUBLIC structs - */ - -/* - * Seln_access for SunView 1 compatibility - * (cannot be moved below because Seln_holder depends upon it) - */ -typedef struct -{ - int pid; - int program; - struct sockaddr_in tcp_address; - struct sockaddr_in udp_address; - char *client; -} -Seln_access; - -typedef struct -{ - Seln_rank rank; - Seln_state state; - Seln_access access; -} -Seln_holder; - -typedef struct -{ - Seln_holder caret; - Seln_holder primary; - Seln_holder secondary; - Seln_holder shelf; -} -Seln_holders_all; - -typedef struct -{ - Seln_function function; - Seln_rank addressee_rank; - Seln_holder caret; - Seln_holder primary; - Seln_holder secondary; - Seln_holder shelf; -} -Seln_function_buffer; - -typedef struct -{ - char *client_data; - Seln_rank rank; - char *context; - char **request_pointer; - char **response_pointer; - -} -Seln_replier_data; - -typedef struct -{ - Seln_result (*consume)(); - char *context; -} -Seln_requester; - -typedef struct -{ - Seln_replier_data *replier; - Seln_requester requester; - char *addressee; - Seln_rank rank; - Seln_result status; - unsigned buf_size; - char data[SELN_BUFSIZE]; -} -Seln_request; - -/* - * PUBLIC structs - * For SunView 1 compatibility - */ - -typedef struct -{ - Seln_rank rank; - char *pathname; -} -Seln_file_info; - -typedef struct -{ - Seln_holder holder; - Seln_function function; - int down; -} -Seln_inform_args; - -typedef struct -{ - unsigned data[SELN_FUNCTION_WORD_COUNT]; -} -Seln_functions_state; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC variables - */ - -/* - * null structs for initialization & easy reference - */ -extern Seln_function_buffer - seln_null_function; -extern Seln_holder seln_null_holder; -extern Seln_request seln_null_request; - -/* - * PUBLIC functions - */ - -EXTERN_FUNCTION (Seln_rank selection_acquire, (Xv_Server server, Seln_client seln_client, Seln_rank asked)); -EXTERN_FUNCTION (Seln_request * selection_ask, (Xv_Server server, Seln_holder *holder, DOTDOTDOT)); -EXTERN_FUNCTION (void selection_clear_functions, (Xv_Server server)); -EXTERN_FUNCTION (Seln_client selection_create, (Xv_Server server, void (*func)(Xv_opaque, Seln_function_buffer *), Seln_result (*request_proc)( Seln_attribute, Seln_replier_data *, int), char *client_data)); -EXTERN_FUNCTION (void selection_destroy, (Xv_Server server, Seln_client client)); -EXTERN_FUNCTION (Seln_result selection_done, (Xv_Server server, Seln_client seln_client, Seln_rank rank)); -EXTERN_FUNCTION (Seln_response selection_figure_response, (Xv_Server server, Seln_function_buffer *buffer, Seln_holder **holder)); -EXTERN_FUNCTION (Seln_result selection_hold_file, (Xv_Server server, Seln_rank rank, char *path)); -EXTERN_FUNCTION (Seln_function_buffer selection_inform, (Xv_Server server, Seln_client seln_client, Seln_function which, int down)); -EXTERN_FUNCTION (void selection_init_request, (Xv_Server server, Seln_request *buffer, Seln_holder *holder, DOTDOTDOT)); -EXTERN_FUNCTION (Seln_holder selection_inquire, (Xv_Server server, Seln_rank which)); -EXTERN_FUNCTION (Seln_holders_all selection_inquire_all, (Xv_Server server)); -EXTERN_FUNCTION (Seln_result selection_query, (Xv_Server server, Seln_holder *holder, Seln_result (*reader)(Seln_request *), char *context, DOTDOTDOT)); -EXTERN_FUNCTION (void selection_report_event, (Xv_Server server, Seln_client seln_client, Event *event)); -EXTERN_FUNCTION (Seln_result selection_request, (Xv_Server server, Seln_holder *holder, Seln_request *buffer)); -EXTERN_FUNCTION (void selection_use_timeout, (Xv_Server server, int seconds)); -EXTERN_FUNCTION (void selection_yield_all, (Xv_Server server)); - -EXTERN_FUNCTION (Seln_client seln_create, (void (*func_proc)(), Seln_result (*request_proc)(), char *client_data)); -EXTERN_FUNCTION (Seln_function_buffer seln_inform, (Seln_client seln_client, Seln_function which, int down)); -EXTERN_FUNCTION (Seln_holder seln_inquire, (Seln_rank which)); -EXTERN_FUNCTION (Seln_holders_all seln_inquire_all, (void)); -EXTERN_FUNCTION (Seln_rank seln_acquire, (Seln_client seln_client, Seln_rank asked)); -EXTERN_FUNCTION (Seln_request *seln_ask, (Seln_holder *holder, DOTDOTDOT)); -EXTERN_FUNCTION (Seln_response seln_figure_response, (Seln_function_buffer *buffer, Seln_holder **holder)); -EXTERN_FUNCTION (Seln_result seln_done, (Seln_client seln_client, Seln_rank rank)); -EXTERN_FUNCTION (Seln_result seln_hold_file, (Seln_rank rank, char *path)); -EXTERN_FUNCTION (Seln_result seln_query, (Seln_holder *holder, Seln_result (*reader)(), char *context, DOTDOTDOT)); -EXTERN_FUNCTION (Seln_result seln_request, (Seln_holder *holder, Seln_request *buffer)); -EXTERN_FUNCTION (void seln_report_event, (Seln_client seln_client, Event *event)); -EXTERN_FUNCTION (void seln_yield_all, (void)); -EXTERN_FUNCTION (void seln_destroy, (Seln_client client)); -EXTERN_FUNCTION (int seln_holder_same_client, (Seln_holder *holder, char *client_data)); -EXTERN_FUNCTION (int seln_holder_same_process, (Seln_holder *holder)); -EXTERN_FUNCTION (int seln_secondary_made, (Seln_function_buffer *buffer)); -EXTERN_FUNCTION (int seln_secondary_exists, (Seln_function_buffer *buffer)); -EXTERN_FUNCTION (void seln_init_request, (Seln_request *buffer, Seln_holder *holder, DOTDOTDOT)); -EXTERN_FUNCTION (void seln_clear_functions, (void)); -EXTERN_FUNCTION (void seln_use_timeout, (int seconds)); - - -#endif /* ~xview_selection_svc_DEFINED */ diff --git a/include/xview/selection.h b/include/xview/selection.h deleted file mode 100644 index dbc3638c5a3..00000000000 --- a/include/xview/selection.h +++ /dev/null @@ -1,104 +0,0 @@ -/* @(#)selection.h 20.17 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_seln_DEFINED -#define xview_seln_DEFINED - -#include - -/* - * ********************************************************************** - * - * Definitions and Macros - * - * ********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -/* - * sel_type values - */ -#define SELTYPE_NULL 0 -#define SELTYPE_CHAR 1 - -/* - * sel_itembytes values - */ -#define SEL_UNKNOWNITEMS -1 /* Don't know how many items */ - -/* - * sel_pubflags values - */ -#define SEL_PRIMARY 0X01 /* Primary selection */ -#define SEL_SECONDARY 0X02 /* Secondary selection */ - - -/* - * ********************************************************************** - * - * Typedefs, Enumerations, and Structures ********************************************************************** - * - */ - -struct selection -{ - int sel_type, sel_items, sel_itembytes, sel_pubflags; - caddr_t sel_privdata; -}; - -/* - * ********************************************************************** - * - * Globals ********************************************************************** - * - */ - -/* - * Public variables - */ - -extern struct selection selnull; - -/* - * Public Functions - */ - -#ifdef xview_other_selection_funcs - -/* - * Create the selection - */ -EXTERN_FUNCTION (void selection_set, (struct selection *sel, int (*sel_write) (), int (*sel_clear) (), Xv_opaque window)); -/* - * Fetch the selection - */ -EXTERN_FUNCTION (void selection_get, (int (*sel_read) (), Xv_opaque window)); -/* - * Clear the selection - */ -EXTERN_FUNCTION (void selection_clear, (Xv_opaque window)); -/* - * Write the bits of the selection - */ -EXTERN_FUNCTION (void sel_write, (struct selection * sel, FILE * file)); -/* - * Read the bits of the selection - */ -EXTERN_FUNCTION (void sel_read, (struct selection * sel, FILE * file)); -/* - * As the owner of the selection you should clear your hiliting because you - * are no longer the selection owner. - */ -EXTERN_FUNCTION (void sel_clear, (struct selection * sel, int window)); - -#endif /* xview_other_selection_funcs */ - -#endif /* ~xview_seln_DEFINED */ diff --git a/include/xview/seln.h b/include/xview/seln.h deleted file mode 100644 index e22ff0aa2cd..00000000000 --- a/include/xview/seln.h +++ /dev/null @@ -1,21 +0,0 @@ -/* @(#)seln.h 20.12 91/09/14 */ - -#ifndef xview_seln_DEFINED -#define xview_seln_DEFINED - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include - -#endif /* ~xview_seln_DEFINED */ diff --git a/include/xview/server.h b/include/xview/server.h deleted file mode 100644 index cd3c91c7a67..00000000000 --- a/include/xview/server.h +++ /dev/null @@ -1,177 +0,0 @@ -/* @(#)server.h 20.53 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_server_DEFINED -#define xview_server_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#ifndef XV_ATTRIBUTES_ONLY -#define SERVER &xv_server_pkg -#endif /* ~XV_ATTRIBUTES_ONLY */ - -/* - * PRIVATE #defines - */ - -#define RECT_STRUCT_SIZE 4 -#define SERVER_ATTR(type, ordinal) ATTR(ATTR_PKG_SERVER, type, ordinal) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -typedef enum kbd_cmds_values { - KBD_CMDS_SUNVIEW1 = 0, - KBD_CMDS_BASIC = 1, - KBD_CMDS_FULL = 2 -} Kbd_cmds_value; - -#ifndef XV_ATTRIBUTES_ONLY - -typedef Xv_opaque Xv_Server; -typedef Xv_opaque Xv_server; - -typedef struct -{ - Xv_generic_struct parent; - Xv_opaque private_data; -} -Xv_server_struct; - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -typedef enum { - /* Public attributes */ - SERVER_ATOM = SERVER_ATTR(ATTR_LONG, 108), - SERVER_ATOM_NAME = SERVER_ATTR(ATTR_OPAQUE, 109), - SERVER_ATOM_DATA = SERVER_ATTR(ATTR_OPAQUE, 113), - SERVER_CHORDING_TIMEOUT = SERVER_ATTR(ATTR_INT, 242), - SERVER_CHORD_MENU = SERVER_ATTR(ATTR_INT, 244), - SERVER_EXTENSION_PROC = SERVER_ATTR(ATTR_FUNCTION_PTR,4), - SERVER_NTH_SCREEN = SERVER_ATTR(ATTR_INT_PAIR, 2), - SERVER_RESOURCE_DB = SERVER_ATTR(ATTR_OPAQUE, 246), - SERVER_SYNC = SERVER_ATTR(ATTR_BOOLEAN, 32), - SERVER_SYNC_AND_PROCESS_EVENTS = SERVER_ATTR(ATTR_NO_VALUE, 33), - SERVER_EXTERNAL_XEVENT_PROC = SERVER_ATTR(ATTR_OPAQUE_PAIR, 20), - SERVER_EXTERNAL_XEVENT_MASK = SERVER_ATTR(ATTR_OPAQUE_TRIPLE, 22), - - /* Private attributes */ - SERVER_ASCII_KEYSTATE = SERVER_ATTR(ATTR_OPAQUE, 7), - SERVER_ASCII_MAP = SERVER_ATTR(ATTR_OPAQUE, 12), - SERVER_ASCII_TO_KEYCODE_MAP = SERVER_ATTR(ATTR_OPAQUE, 6), - SERVER_CUT_KEYSYM = SERVER_ATTR(ATTR_INT, 10), - SERVER_FONT_WITH_NAME = SERVER_ATTR(ATTR_STRING, 11), - SERVER_JOURNAL_SYNC_EVENT = SERVER_ATTR(ATTR_INT, 38), - SERVER_JOURNALLING = SERVER_ATTR(ATTR_BOOLEAN, 36), - SERVER_KEY_EVENTS_MAP = SERVER_ATTR(ATTR_OPAQUE, 5), - SERVER_NONASCII_KEYSTATE = SERVER_ATTR(ATTR_OPAQUE, 8), - SERVER_PASTE_KEYSYM = SERVER_ATTR(ATTR_INT, 16), - SERVER_SEMANTIC_MAP = SERVER_ATTR(ATTR_OPAQUE, 14), - SERVER_XV_MAP = SERVER_ATTR(ATTR_OPAQUE, 13), - SERVER_COMPOSE_STATUS = SERVER_ATTR(ATTR_OPAQUE, 15), - SERVER_PRIVATE_XEVENT_PROC = SERVER_ATTR(ATTR_OPAQUE_PAIR, 23), - SERVER_PRIVATE_XEVENT_MASK = SERVER_ATTR(ATTR_OPAQUE_TRIPLE, 24), - - /* Private attributes that may be deleted in future revisions */ - SERVER_WM_RESCALE = SERVER_ATTR(ATTR_OPAQUE, 25), - SERVER_WM_RESCALE_STATE = SERVER_ATTR(ATTR_OPAQUE, 17), - SERVER_WM_STATE = SERVER_ATTR(ATTR_OPAQUE, 21), - SERVER_WM_TAKE_FOCUS = SERVER_ATTR(ATTR_OPAQUE, 30), - SERVER_WM_WINDOW_MOVED = SERVER_ATTR(ATTR_OPAQUE, 28), - SERVER_WM_WIN_ATTR = SERVER_ATTR(ATTR_OPAQUE, 34), - SERVER_WM_ADD_DECOR = SERVER_ATTR(ATTR_OPAQUE, 35), - SERVER_WM_DELETE_DECOR = SERVER_ATTR(ATTR_OPAQUE, 40), - SERVER_WM_DECOR_CLOSE = SERVER_ATTR(ATTR_OPAQUE, 45), - SERVER_WM_DECOR_FOOTER = SERVER_ATTR(ATTR_OPAQUE, 55), - SERVER_WM_DECOR_RESIZE = SERVER_ATTR(ATTR_OPAQUE, 60), - SERVER_WM_DECOR_HEADER = SERVER_ATTR(ATTR_OPAQUE, 65), - SERVER_WM_DECOR_OK = SERVER_ATTR(ATTR_OPAQUE, 70), - SERVER_WM_DECOR_PIN = SERVER_ATTR(ATTR_OPAQUE, 75), - SERVER_WM_SCALE_SMALL = SERVER_ATTR(ATTR_OPAQUE, 80), - SERVER_WM_SCALE_MEDIUM = SERVER_ATTR(ATTR_OPAQUE, 85), - SERVER_WM_SCALE_LARGE = SERVER_ATTR(ATTR_OPAQUE, 90), - SERVER_WM_SCALE_XLARGE = SERVER_ATTR(ATTR_OPAQUE, 95), - SERVER_WM_PIN_STATE = SERVER_ATTR(ATTR_OPAQUE, 100), - SERVER_WM_WIN_BUSY = SERVER_ATTR(ATTR_OPAQUE, 105), - SERVER_DND_ACK_KEY = SERVER_ATTR(ATTR_INT, 107), - SERVER_WM_WINMSG_STATE = SERVER_ATTR(ATTR_OPAQUE, 110), - SERVER_WM_WINMSG_ERROR = SERVER_ATTR(ATTR_OPAQUE, 115), - SERVER_WM_WT_BASE = SERVER_ATTR(ATTR_OPAQUE, 121), - SERVER_WM_WT_CMD = SERVER_ATTR(ATTR_OPAQUE, 125), - SERVER_WM_WT_PROP = SERVER_ATTR(ATTR_OPAQUE, 130), - SERVER_WM_WT_HELP = SERVER_ATTR(ATTR_OPAQUE, 135), - SERVER_WM_WT_NOTICE = SERVER_ATTR(ATTR_OPAQUE, 140), - SERVER_WM_WT_OTHER = SERVER_ATTR(ATTR_OPAQUE, 145), - SERVER_WM_MENU_FULL = SERVER_ATTR(ATTR_OPAQUE, 150), - SERVER_WM_MENU_LIMITED = SERVER_ATTR(ATTR_OPAQUE, 155), - SERVER_WM_NONE = SERVER_ATTR(ATTR_OPAQUE, 160), - SERVER_WM_PIN_IN = SERVER_ATTR(ATTR_OPAQUE, 165), - SERVER_WM_PIN_OUT = SERVER_ATTR(ATTR_OPAQUE, 170), - SERVER_DO_DRAG_MOVE = SERVER_ATTR(ATTR_OPAQUE, 120), - SERVER_DO_DRAG_COPY = SERVER_ATTR(ATTR_OPAQUE, 122), - SERVER_DO_DRAG_LOAD = SERVER_ATTR(ATTR_OPAQUE, 123), - SERVER_JOURNAL_SYNC_ATOM = SERVER_ATTR(ATTR_INT, 125), - SERVER_WM_DISMISS = SERVER_ATTR(ATTR_OPAQUE, 200), - SERVER_WM_SAVE_YOURSELF = SERVER_ATTR(ATTR_OPAQUE, 210), - SERVER_WM_DEFAULT_BUTTON = SERVER_ATTR(ATTR_OPAQUE, 220), - SERVER_WM_PROTOCOLS = SERVER_ATTR(ATTR_OPAQUE, 225), - SERVER_WM_DELETE_WINDOW = SERVER_ATTR(ATTR_OPAQUE, 230), - SERVER_WM_COMMAND = SERVER_ATTR(ATTR_OPAQUE, 235), - SERVER_WM_CHANGE_STATE = SERVER_ATTR(ATTR_OPAQUE, 240), - SERVER_MOUSE_BUTTONS = SERVER_ATTR(ATTR_SHORT, 250), - SERVER_BUTTON2_MOD = SERVER_ATTR(ATTR_INT, 252), - SERVER_BUTTON3_MOD = SERVER_ATTR(ATTR_INT, 254), - SERVER_META_MOD_MASK = SERVER_ATTR(ATTR_INT, 9), - SERVER_ALT_MOD_MASK = SERVER_ATTR(ATTR_INT, 248), - SERVER_NUM_LOCK_MOD_MASK = SERVER_ATTR(ATTR_INT, 247), - SERVER_SEL_MOD_MASK = SERVER_ATTR(ATTR_INT, 251), - SERVER_FOCUS_TIMESTAMP = SERVER_ATTR(ATTR_INT, 203) -#ifdef OW_I18N - , - SERVER_COMPOUND_TEXT = SERVER_ATTR(ATTR_OPAQUE, 249) -#endif /* OW_I18N */ -} Server_attr; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC variables - */ -extern Xv_Server xv_default_server; - -/* - * PRIVATE variables - */ -#ifndef XV_ATTRIBUTES_ONLY -extern Xv_pkg xv_server_pkg; -#endif /* ~XV_ATTRIBUTES_ONLY */ - -#endif /* ~xview_server_DEFINED */ diff --git a/include/xview/str_utils.h b/include/xview/str_utils.h deleted file mode 100644 index 2e4ab07b5fd..00000000000 --- a/include/xview/str_utils.h +++ /dev/null @@ -1,148 +0,0 @@ -/* @(#)str_utils.h 20.16 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_string_utils_DEFINED -#define xview_string_utils_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include /* defines TRUE, FALSE */ -#include - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -/* - * CharClass and CharAction are also defined in io_stream.h - */ - -#ifndef CHARCLASS -#define CHARCLASS -enum CharClass {Break, Sepr, Other}; -#endif /* ~CHARCLASS */ - -#ifndef CHARACTION -#define CHARACTION -struct CharAction -{ - Bool stop; - Bool include; -}; -#endif /* ~CHARACTION */ - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -/* - * PUBLIC Functions - */ - -#ifndef WHITESPACE -#define WHITESPACE -/* - * xv_white_space is also defined in io_stream.h - * returns sepr for blanks, newlines, and tabs, other for everything else - */ -EXTERN_FUNCTION (ENUM_TYPE(enum,CharClass) xv_white_space, (int c)); -#endif - -EXTERN_FUNCTION (int string_find, (char *s, char *target, Bool case_matters)); -/* int string_find(s, target, case_matters) - * char *s, *target; - * Bool case_matters; - * strfind searches one instance of a string for another. - * If successful, returns the position in the string where the match began, - * otherwise -1. - * If case_matters = FALSE, 'a' will match with 'a' or 'A'. - */ - -EXTERN_FUNCTION (Bool string_equal, (char *s1, char *s2, Bool case_matters)); -/* Bool string_equal(s1, s2, case_matters) - * char *s1, *s2; - * Bool case_matters; - * strequal compares two strings. - * If case_matters = FALSE, 'a' will match with 'a' or 'A'. - * either s1 or s2 can be NULL without harm. - */ - -EXTERN_FUNCTION (Bool xv_substrequal, (char *s1, int start1, char *s2, int start2, int n, Bool case_matters)); -/* Bool xv_substrequal(s1, start1, s2, start2, n, case_matters) - * char *s1, *s2; - * int start1, start2, n; - * Bool case_matters; - * xv_substrequal compares two substrings without having to construct them. - * If case_matters = FALSE, 'a' will match with 'a' or 'A'. - */ - -EXTERN_FUNCTION (char *string_get_token, (char *s, int *index, char *dest, ENUM_TYPE(enum,CharClass) (*charproc)(int))); -/* char *s; - * int *index; - * char *dest; - * enum CharClass (*charproc) (char c); - - * string_get_token is used for tokenizing input, where more degree of - * flexibility is required than simply delimiting tokens by white spaces - * characters are divided into three classes, Break, Sepr, and Other. - * separators (Sepr) serve to delimit a token. Leading separators are skipped. - * think of separators as white space. Break characters delimit tokens, and - * are themselves tokens. Thus, if a break character is the first thing seen - * it is returned as the token. If any non-separator characters have been seen, - * then they are returned as the token, and the break character will be the - * returned as the result of the next call to get_token. - * for example, if charproc returns Sepr for space, and Break for '(' and ')' - * and Other for all alphabetic characters, then the string "now (is) the" - * will yield five tokens consisting of "now" "(" "is" ")" and "the" - - * get_token stores the token that it constructs into dest, - * which is also returned as its value. - * index marks the current position in the string to "begin reading from" - * it is updated so that the client program does not have to keep track of - * how many characters have been read. - - * get_token returns NULL, rather than the empty string, corresponding to - * the case where the token is empty - */ - -EXTERN_FUNCTION (char *string_get_sequence, (char *s, int *index, char *dest, struct CharAction (*charproc)(void))); -/* char *s; - * int *index; - * char *dest; - * struct CharAction (*charproc) (); - - * string_get_sequence is a more primitive tokenizer than get_token. - * it takes a procedure which for each character specifies whether the - * character is to terminate the sequence, and whether or not the - * character is to be included in the sequence. - * (If the character terminates the sequence, but is not included, then - * it will be seen again on the next call.) - * For example, having seen a \"\, to read to the matching \"\, call - * get_sequence with an action procedure that returns {TRUE, TRUE} for \"\ - * and {FALSE, TRUE} for everything else. (If you want to detect the - * case where a " is preceded by a \\, simply save the last character - * and modify the procedure accordingly. - - * Note that gettoken can be defined in terms of get_sequence by - * having Other characters return {FALSE, TRUE}, and also noticing whether - * any have been seen yet, having Seprs return - * {(seen_some_others ? TRUE : FALSE), FALSE} - * and Break characters return {TRUE, (seen_some_others ? FALSE : TRUE)} - - * returns NULL for the empty sequence - */ - -#endif /* ~xview_string_utils_DEFINED */ diff --git a/include/xview/sun.h b/include/xview/sun.h deleted file mode 100644 index edde9c5ee9e..00000000000 --- a/include/xview/sun.h +++ /dev/null @@ -1,52 +0,0 @@ -/* @(#)sun.h 20.20 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef sunwindow_sun_DEFINED -#define sunwindow_sun_DEFINED - -#include -#include -#include - -#ifndef FALSE -#define FALSE 0 -#endif -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef Bool_DEFINED -#define Bool int -#define True 1 -#define False 0 -#endif - -#define strequal(s1, s2) (strcmp(s1, s2) == 0) -#define STRDUP(str) (strcpy(xv_malloc((unsigned) strlen(str) + 1), str)) -/* - * Get some storage and copy a string. Note that str is evaluated twice, - * so no side effects. - */ -#define ord(e) ((int) (e)) -/* - * Make an enum usable as an integer - * Successor or predecessor macros might also be convenient, but - * much less so. - */ - -#define FOREVER for (;;) - -#ifndef MIN -#define MIN(x, y) ( ((x) < (y)) ? (x) : (y) ) -#endif - -#ifndef MAX -#define MAX(x, y) ( ((x) > (y)) ? (x) : (y) ) -#endif - -#endif diff --git a/include/xview/svrimage.h b/include/xview/svrimage.h deleted file mode 100644 index 93465275e3b..00000000000 --- a/include/xview/svrimage.h +++ /dev/null @@ -1,105 +0,0 @@ -/* @(#)svrimage.h 20.23 91/09/14 SMI */ - -#ifndef xview_server_image_DEFINED -#define xview_server_image_DEFINED - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include -#include /* needed for pixrect.h */ -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define SERVER_IMAGE &xv_server_image_pkg - -#define server_image_begin_bits(name) unsigned short name[] = { -#define server_image_end_bits(name) }; - -/* - * PRIVATE #defines - */ - -#define SERVER_IMAGE_ATTR(type, ordinal) \ - ATTR(ATTR_PKG_SERVER_IMAGE, type, ordinal) - -#define SERVER_IMAGE_TYPE ATTR_PKG_SERVER_IMAGE - -#define SERVER_IMAGE_ATTR_LIST(ltype, type, ordinal) \ - SERVER_IMAGE_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -typedef Xv_opaque Server_image; - -typedef enum { - /* - * Public attributes - */ - SERVER_IMAGE_DEPTH = SERVER_IMAGE_ATTR(ATTR_INT, 1), - SERVER_IMAGE_BITS = SERVER_IMAGE_ATTR(ATTR_OPAQUE, 2), - SERVER_IMAGE_X_BITS = SERVER_IMAGE_ATTR(ATTR_OPAQUE, 3), - SERVER_IMAGE_COLORMAP = SERVER_IMAGE_ATTR(ATTR_STRING, 4), - SERVER_IMAGE_BITMAP_FILE= SERVER_IMAGE_ATTR(ATTR_STRING, 5), - SERVER_IMAGE_PIXMAP = SERVER_IMAGE_ATTR(ATTR_OPAQUE, 6), - SERVER_IMAGE_SAVE_PIXMAP= SERVER_IMAGE_ATTR(ATTR_BOOLEAN, 7), -#ifdef OW_I18N - SERVER_IMAGE_BITMAP_FILE_WCS= SERVER_IMAGE_ATTR(ATTR_STRING, 8), -#endif - SERVER_IMAGE_CMS = SERVER_IMAGE_ATTR(ATTR_OPAQUE, 9) -} Server_image_attribute; - -typedef struct -{ - Xv_drawable_struct parent_data; - Xv_opaque private_data; - Xv_embedding embedding_data; - Pixrect pixrect; -} -Xv_server_image; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -Xv_public Xv_pkg xv_server_image_pkg; - -/* - * PUBLIC functions - */ -EXTERN_FUNCTION (int server_image_rop, (Xv_opaque dest, int dx, int dy, int dw, int dh, unsigned long op, Xv_opaque src, int sx, int sy)); -EXTERN_FUNCTION (int server_image_stencil, (Xv_opaque dest, int dx, int dy, int dw, int dh, unsigned long op, Xv_opaque st, int stx, int dty, Xv_opaque src, int sx, int sy)); -EXTERN_FUNCTION (int server_image_destroy, (Pixrect *pr)); -EXTERN_FUNCTION (int server_image_get, (Xv_opaque dest, int x, int y)); -EXTERN_FUNCTION (int server_image_put, (Xv_opaque dest, int x, int y, int value)); -EXTERN_FUNCTION (int server_image_vector, (Xv_opaque dest, int x0, int y0, int x1, int y1, int op, int value)); -EXTERN_FUNCTION (Pixrect *server_image_region, (Xv_opaque dest, int x, int y, int w, int h)); -EXTERN_FUNCTION (int server_image_colormap, (Xv_opaque dest, int index, int count, unsigned char *red, unsigned char *green, unsigned char *blue)); - -#endif /* xview_server_image_DEFINED */ diff --git a/include/xview/termsw.h b/include/xview/termsw.h deleted file mode 100644 index e5edadcd8bf..00000000000 --- a/include/xview/termsw.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * @(#)termsw.h 20.17 91/09/14 SMI - * - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_termsw_DEFINED -#define xview_termsw_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#ifdef XV_ATTRIBUTES_ONLY -#include - -#else -#include - -#endif /* XV_ATTRIBUTES_ONLY */ - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#ifndef XV_ATTRIBUTES_ONLY - -#define TERMSW &xv_termsw_pkg -#define TERMSW_VIEW &xv_termsw_view_pkg - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -/* - * PRIVATE #defines - */ - -#define TERMSW_TYPE ATTR_PKG_TERMSW -#define TERMSW_VIEW_TYPE ATTR_PKG_TERMSW_VIEW -#define TERMSW_ATTR(type, ordinal) ATTR(ATTR_PKG_TERMSW, type, ordinal) - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -#ifndef XV_ATTRIBUTES_ONLY - -typedef Xv_opaque Termsw; -typedef Xv_opaque Termsw_view; - -typedef struct -{ - /* - * This isn't really a textsw, only shares few attrs - */ - Xv_textsw parent_data; - Xv_opaque private_data; - Xv_opaque private_text; - Xv_opaque private_tty; -} -Xv_termsw; - -typedef struct -{ - /* - * This isn't really a textsw view, only shares few attrs - */ - Xv_textsw_view parent_data; - Xv_opaque private_data; - Xv_opaque private_text; - Xv_opaque private_tty; -} -Xv_termsw_view; - -#endif /* ~XV_ATTRIBUTES_ONLY */ - -typedef enum { - TERMSW_MODE_TYPE, - TTYSW_MODE_TYPE -} Termsw_mode; - -typedef enum { - /* - * Public attributes. - */ - TERMSW_MODE = TERMSW_ATTR(ATTR_INT, 1) /* --G */ -} Termsw_attribute; - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_termsw_pkg; -extern Xv_pkg xv_termsw_view_pkg; - -#endif /* ~xview_termsw_DEFINED */ diff --git a/include/xview/text.h b/include/xview/text.h deleted file mode 100644 index 3ad5f847225..00000000000 --- a/include/xview/text.h +++ /dev/null @@ -1,42 +0,0 @@ -/* @(#)text.h 20.12 91/09/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -/* - * The entire contents of this file are for - * SunView 1 compatibility only -- THIS IS GOING AWAY - */ - -#ifndef xview_text_DEFINED -#define xview_text_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -#define TEXT_TYPE ATTR_PKG_TEXTSW -#define TEXT textsw_window_object, WIN_COMPATIBILITY - -/* - *********************************************************************** - * Typedefs - *********************************************************************** - */ - -typedef Textsw Text; - -#endif /* ~xview_text_DEFINED */ diff --git a/include/xview/textsw.h b/include/xview/textsw.h deleted file mode 100644 index 5fcc84dfa40..00000000000 --- a/include/xview/textsw.h +++ /dev/null @@ -1,539 +0,0 @@ -/* @(#)textsw.h 20.39 90/12/14 SMI */ - -/* - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_textsw_DEFINED -#define xview_textsw_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -/* - * Programmatic interface to textsw - */ -#include -#include -#include - -/* - * New window_create() defs - */ -#include -#include -#include -#include -#include -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define TEXTSW &xv_textsw_pkg -#define TEXTSW_VIEW &xv_textsw_view_pkg - -#define TEXTSW_NULL ((Textsw)0) - -#define TEXTSW_INFINITY ((Textsw_index)0x77777777) -#define TEXTSW_CANNOT_SET ((Textsw_index)0x80000000) -#define TEXTSW_UNIT_IS_CHAR SELN_LEVEL_FIRST -#define TEXTSW_UNIT_IS_WORD SELN_LEVEL_FIRST+1 -#define TEXTSW_UNIT_IS_LINE SELN_LEVEL_LINE - -#define TEXTSW_FONT XV_FONT -/* - * fields flags - */ -#define TEXTSW_NOT_A_FIELD 0 /* This tells the field code don't -* do the search, only do a match. - */ -#define TEXTSW_FIELD_FORWARD 1 -#define TEXTSW_FIELD_BACKWARD 2 -#define TEXTSW_FIELD_ENCLOSE 3 -#define TEXTSW_DELIMITER_FORWARD 4 -#define TEXTSW_DELIMITER_BACKWARD 5 -#define TEXTSW_DELIMITER_ENCLOSE 6 - - /* - * Support for marking of positions in the textsw - */ -#define TEXTSW_NULL_MARK ((Textsw_mark)0) - - /* - * Flags for use with textsw_add_mark - */ -#define TEXTSW_MARK_DEFAULTS 0x0 -#define TEXTSW_MARK_MOVE_AT_INSERT 0x1 -#define TEXTSW_MARK_READ_ONLY 0x2 - - /* - * PRIVATE #defines - */ - -#define TEXTSW_ATTR(type, ordinal) ATTR(ATTR_PKG_TEXTSW, type, ordinal) -#define TEXTSW_ATTR_LIST(ltype, type, ordinal) \ - TEXTSW_ATTR(ATTR_LIST_INLINE((ltype), (type)), (ordinal)) - - /* - * A special scrollbar value for TEXTSW_VIEW_SCROLLBAR - */ -#define TEXTSW_DEFAULT_SCROLLBAR ((caddr_t)1) - - /* - * Flag values for TEXTSW_NOTIFY_LEVEL attribute. - */ -#define TEXTSW_NOTIFY_NONE 0x00 -#define TEXTSW_NOTIFY_DESTROY_VIEW 0x01 -#define TEXTSW_NOTIFY_EDIT_DELETE 0x02 -#define TEXTSW_NOTIFY_EDIT_INSERT 0x04 -#define TEXTSW_NOTIFY_EDIT (TEXTSW_NOTIFY_EDIT_DELETE | \ - TEXTSW_NOTIFY_EDIT_INSERT) -#define TEXTSW_NOTIFY_PAINT 0x08 -#define TEXTSW_NOTIFY_REPAINT 0x10 -#define TEXTSW_NOTIFY_SCROLL 0x20 -#define TEXTSW_NOTIFY_SPLIT_VIEW 0x40 -#define TEXTSW_NOTIFY_STANDARD 0x80 -#define TEXTSW_NOTIFY_ALL (TEXTSW_NOTIFY_DESTROY_VIEW | \ - TEXTSW_NOTIFY_EDIT | \ - TEXTSW_NOTIFY_PAINT | \ - TEXTSW_NOTIFY_REPAINT | \ - TEXTSW_NOTIFY_SCROLL | \ - TEXTSW_NOTIFY_SPLIT_VIEW | \ - TEXTSW_NOTIFY_STANDARD) - -#define TEXTSW_ATTR_RECT_PAIR ATTR_TYPE(ATTR_BASE_RECT_PTR, 2) -#define TEXTSW_ATTR_REPLACE_5 ATTR_TYPE(ATTR_BASE_INT, 5) - - /* - * Bit flags returned by textsw_process_event - */ -#define TEXTSW_PE_BUSY 0x1 -#define TEXTSW_PE_READ_ONLY 0x2 -#define TEXTSW_PE_USED 0x4 - - /* - * Reset actions for Load/Reset/Save/Store - */ -#define TEXTSW_LRSS_CURRENT 0 -#define TEXTSW_LRSS_ENTITY_START 1 -#define TEXTSW_LRSS_LINE_START 2 - - /* - * The magic number for smart filters - */ -#define TEXTSW_FILTER_MAGIC 0xFF012003 - - /* - * Flag values for textsw_add_glyph_on_line(). - */ -#define TEXTSW_GLYPH_DISPLAY 0x0000001 -#define TEXTSW_GLYPH_LINE_START 0x0000002 -#define TEXTSW_GLYPH_WORD_START 0x0000004 -#define TEXTSW_GLYPH_LINE_END 0x0000008 - - /* - * For SunView 1 compatibility - */ -#define TEXTSW_NO_CD TEXTSW_DISABLE_CD -#define TEXTSW_LEFT_MARGIN XV_LEFT_MARGIN -#define TEXTSW_RIGHT_MARGIN XV_RIGHT_MARGIN -#define TEXTSW_SCROLLBAR WIN_VERTICAL_SCROLLBAR -#define TEXTSW_MENU WIN_MENU -#define TEXTSW_TOOL WIN_FRAME -#define TEXTSW_PIXWIN WIN_PIXWIN -#define TEXTSW_TYPE ATTR_PKG_TEXTSW - - /* - *********************************************************************** - * Typedefs, enumerations, and structs - *********************************************************************** - */ - -#if lint - typedef void * Textsw_opaque; -#else - typedef char * Textsw_opaque; -#endif - -typedef Xv_opaque Textsw; -typedef Xv_opaque Textsw_view; -typedef long int Textsw_index; -typedef Textsw_opaque Textsw_mark; - -/* - * Enumerations - */ - -/* - * Attributes for textsw_build, textsw_init, textsw_set and textsw_get. - */ -typedef enum -{ - /* - * Public Attributes - */ - TEXTSW_ADJUST_IS_PENDING_DELETE = TEXTSW_ATTR(ATTR_BOOLEAN, 1), - TEXTSW_AGAIN_RECORDING = TEXTSW_ATTR(ATTR_BOOLEAN, 2), - TEXTSW_AUTO_INDENT = TEXTSW_ATTR(ATTR_BOOLEAN, 4), - TEXTSW_AUTO_SCROLL_BY = TEXTSW_ATTR(ATTR_INT, 6), - TEXTSW_BLINK_CARET = TEXTSW_ATTR(ATTR_BOOLEAN, 8), - TEXTSW_BROWSING = TEXTSW_ATTR(ATTR_BOOLEAN, 10), - TEXTSW_CHECKPOINT_FREQUENCY = TEXTSW_ATTR(ATTR_INT, 12), - TEXTSW_CLIENT_DATA = TEXTSW_ATTR(ATTR_OPAQUE, 14), - TEXTSW_CONFIRM_OVERWRITE = TEXTSW_ATTR(ATTR_BOOLEAN, 16), - TEXTSW_CONTENTS = TEXTSW_ATTR(ATTR_STRING, 18), -#ifdef OW_I18N - TEXTSW_CONTENTS_WCS = TEXTSW_ATTR(ATTR_WSTRING, 19), -#endif - TEXTSW_CONTROL_CHARS_USE_FONT = TEXTSW_ATTR(ATTR_BOOLEAN, 20), - TEXTSW_DISABLE_CD = TEXTSW_ATTR(ATTR_BOOLEAN, 22), - TEXTSW_DISABLE_LOAD = TEXTSW_ATTR(ATTR_BOOLEAN, 24), - TEXTSW_SUBMENU_EDIT = TEXTSW_ATTR(ATTR_NO_VALUE, 26), - TEXTSW_EDIT_COUNT = TEXTSW_ATTR(ATTR_INT, 28), - TEXTSW_EXTRAS_CMD_MENU = TEXTSW_ATTR(ATTR_INT, 30), - TEXTSW_FILE = TEXTSW_ATTR(ATTR_STRING, 32), -#ifdef OW_I18N - TEXTSW_FILE_WCS = TEXTSW_ATTR(ATTR_WSTRING, 33), -#endif - TEXTSW_SUBMENU_FILE = TEXTSW_ATTR(ATTR_NO_VALUE, 34), - TEXTSW_FILE_CONTENTS = TEXTSW_ATTR(ATTR_STRING, 36), -#ifdef OW_I18N - TEXTSW_FILE_CONTENTS_WCS = TEXTSW_ATTR(ATTR_WSTRING, 37), -#endif - TEXTSW_SUBMENU_FIND = TEXTSW_ATTR(ATTR_NO_VALUE, 38), - TEXTSW_FIRST = TEXTSW_ATTR(ATTR_INT, 40), - TEXTSW_FIRST_LINE = TEXTSW_ATTR(ATTR_INT, 42), - TEXTSW_HISTORY_LIMIT = TEXTSW_ATTR(ATTR_INT, 44), - TEXTSW_IGNORE_LIMIT = TEXTSW_ATTR(ATTR_INT, 46), - TEXTSW_INSERTION_POINT = TEXTSW_ATTR(ATTR_INT, 48), -#ifdef OW_I18N - TEXTSW_INSERTION_POINT_WC = TEXTSW_ATTR(ATTR_INT, 49), -#endif - TEXTSW_INSERT_FROM_FILE = TEXTSW_ATTR(ATTR_STRING, 50), -#ifdef OW_I18N - TEXTSW_INSERT_FROM_FILE_WCS = TEXTSW_ATTR(ATTR_WSTRING, 51), -#endif - TEXTSW_INSERT_MAKES_VISIBLE = TEXTSW_ATTR(ATTR_ENUM, 52), - TEXTSW_LENGTH = TEXTSW_ATTR(ATTR_INT, 54), -#ifdef OW_I18N - TEXTSW_LENGTH_WC = TEXTSW_ATTR(ATTR_INT, 55), -#endif - TEXTSW_LINE_BREAK_ACTION = TEXTSW_ATTR(ATTR_ENUM, 56), - TEXTSW_LOWER_CONTEXT = TEXTSW_ATTR(ATTR_INT, 58), - TEXTSW_MEMORY_MAXIMUM = TEXTSW_ATTR(ATTR_INT, 60), - TEXTSW_MODIFIED = TEXTSW_ATTR(ATTR_BOOLEAN, 62), - TEXTSW_MULTI_CLICK_SPACE = TEXTSW_ATTR(ATTR_INT, 64), - TEXTSW_MULTI_CLICK_TIMEOUT = TEXTSW_ATTR(ATTR_INT, 66), - TEXTSW_NOTIFY_PROC = TEXTSW_ATTR(ATTR_FUNCTION_PTR, 68), - TEXTSW_READ_ONLY = TEXTSW_ATTR(ATTR_BOOLEAN, 70), - TEXTSW_STATUS = TEXTSW_ATTR(ATTR_OPAQUE, 72), - TEXTSW_STORE_CHANGES_FILE = TEXTSW_ATTR(ATTR_BOOLEAN, 74), - TEXTSW_UPDATE_SCROLLBAR = TEXTSW_ATTR(ATTR_NO_VALUE, 78), - TEXTSW_UPPER_CONTEXT = TEXTSW_ATTR(ATTR_INT, 80), - TEXTSW_SUBMENU_VIEW = TEXTSW_ATTR(ATTR_NO_VALUE, 82), - /* - * Private Attributes - */ - TEXTSW_AGAIN_LIMIT = TEXTSW_ATTR(ATTR_INT, 84), - TEXTSW_COALESCE_WITH = TEXTSW_ATTR(ATTR_OPAQUE, 86), - TEXTSW_DESTROY_ALL_VIEWS = TEXTSW_ATTR(ATTR_BOOLEAN, 92), - TEXTSW_EDIT_BACK_CHAR = TEXTSW_ATTR(ATTR_CHAR, 98), - TEXTSW_EDIT_BACK_LINE = TEXTSW_ATTR(ATTR_CHAR, 100), - TEXTSW_EDIT_BACK_WORD = TEXTSW_ATTR(ATTR_CHAR, 102), - TEXTSW_ERROR_MSG = TEXTSW_ATTR(ATTR_STRING, 104), - TEXTSW_ES_CREATE_PROC = TEXTSW_ATTR(ATTR_FUNCTION_PTR,106), - TEXTSW_INSERT_ONLY = TEXTSW_ATTR(ATTR_BOOLEAN, 108), - TEXTSW_LOAD_DIR_IS_CD = TEXTSW_ATTR(ATTR_ENUM, 110), -#ifdef DEBUG - TEXTSW_MALLOC_DEBUG_LEVEL = TEXTSW_ATTR(ATTR_INT, 112), -#endif - TEXTSW_MUST_SHOW_CARET = TEXTSW_ATTR(ATTR_BOOLEAN, 114), - TEXTSW_NAME_TO_USE = TEXTSW_ATTR(ATTR_STRING, 116), - TEXTSW_NOTIFY_LEVEL = TEXTSW_ATTR(ATTR_INT, 118), - TEXTSW_NO_REPAINT_TIL_EVENT = TEXTSW_ATTR(ATTR_BOOLEAN, 120), - TEXTSW_NO_RESET_TO_SCRATCH = TEXTSW_ATTR(ATTR_BOOLEAN, 122), - TEXTSW_NO_SELECTION_SERVICE = TEXTSW_ATTR(ATTR_BOOLEAN, 124), - TEXTSW_RESET_MODE = TEXTSW_ATTR(ATTR_ENUM, 128), - TEXTSW_RESET_TO_CONTENTS = TEXTSW_ATTR(ATTR_NO_VALUE, 130), - TEXTSW_SPARE_1 = - TEXTSW_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_INT), - 132), - TEXTSW_SPARE_2 = - TEXTSW_ATTR(ATTR_LIST_INLINE(ATTR_NULL, ATTR_INT), - 134), - TEXTSW_TAB_WIDTH = TEXTSW_ATTR(ATTR_INT, 136), - TEXTSW_TAB_WIDTHS = TEXTSW_ATTR_LIST(ATTR_NULL, ATTR_INT, 138), -#ifdef OW_I18N - TEXTSW_TEMP_FILENAME = TEXTSW_ATTR(ATTR_WSTRING, 140), -#else - TEXTSW_TEMP_FILENAME = TEXTSW_ATTR(ATTR_STRING, 140), -#endif - TEXTSW_WRAPAROUND_SIZE = TEXTSW_ATTR(ATTR_INT, 142), - /* - * Make individual view changes affect all views - */ - TEXTSW_END_ALL_VIEWS = TEXTSW_ATTR(ATTR_NO_VALUE, 144), - TEXTSW_FOR_ALL_VIEWS = TEXTSW_ATTR(ATTR_NO_VALUE, 146) -} -Textsw_attribute; - -/* - * Following are actions defined for client provided notify_proc. - * Two standard notify procs are textsw_default_notify and textsw_nop_notify. - */ -typedef enum { - /* - * Public Attributes - */ - TEXTSW_ACTION_CAPS_LOCK = TEXTSW_ATTR(ATTR_BOOLEAN, 1), - TEXTSW_ACTION_CHANGED_DIRECTORY = TEXTSW_ATTR(ATTR_STRING, 5), - TEXTSW_ACTION_EDITED_FILE = TEXTSW_ATTR(ATTR_STRING, 10), - TEXTSW_ACTION_EDITED_MEMORY = TEXTSW_ATTR(ATTR_NO_VALUE, 15), - TEXTSW_ACTION_FILE_IS_READONLY = TEXTSW_ATTR(ATTR_STRING, 20), - TEXTSW_ACTION_LOADED_FILE = TEXTSW_ATTR(ATTR_STRING, 25), - TEXTSW_ACTION_TOOL_CLOSE = TEXTSW_ATTR(ATTR_NO_VALUE, 30), - TEXTSW_ACTION_TOOL_DESTROY = TEXTSW_ATTR(ATTR_OPAQUE, 35), - TEXTSW_ACTION_TOOL_MGR = TEXTSW_ATTR(ATTR_OPAQUE, 40), - TEXTSW_ACTION_TOOL_QUIT = TEXTSW_ATTR(ATTR_OPAQUE, 45), - TEXTSW_ACTION_USING_MEMORY = TEXTSW_ATTR(ATTR_NO_VALUE, 50), -#ifdef OW_I18N - TEXTSW_ACTION_CHANGED_DIRECTORY_WCS = TEXTSW_ATTR(ATTR_WSTRING, 51), - TEXTSW_ACTION_EDITED_FILE_WCS = TEXTSW_ATTR(ATTR_WSTRING, 52), - TEXTSW_ACTION_LOADED_FILE_WCS = TEXTSW_ATTR(ATTR_WSTRING, 53), -#endif - /* - * Private Attributes - */ - TEXTSW_ACTION_DESTROY_VIEW = TEXTSW_ATTR(ATTR_NO_VALUE, 55), - TEXTSW_ACTION_PAINTED = TEXTSW_ATTR(ATTR_RECT_PTR, 60), - TEXTSW_ACTION_REPLACED = - TEXTSW_ATTR(TEXTSW_ATTR_REPLACE_5, 65), - TEXTSW_ACTION_SAVING_FILE = TEXTSW_ATTR(ATTR_NO_VALUE, 70), - TEXTSW_ACTION_SCROLLED = - TEXTSW_ATTR(TEXTSW_ATTR_RECT_PAIR, 75), - TEXTSW_ACTION_SPLIT_VIEW = TEXTSW_ATTR(ATTR_OPAQUE, 80), - TEXTSW_ACTION_STORING_FILE = TEXTSW_ATTR(ATTR_STRING, 85), - TEXTSW_ACTION_WRITE_FAILED = TEXTSW_ATTR(ATTR_NO_VALUE, 90) -} Textsw_action; - -/* - * Attributes for smart filters - */ -typedef enum { - TEXTSW_FATTR_INPUT = TEXTSW_ATTR(ATTR_OPAQUE,1), - TEXTSW_FATTR_INPUT_EVENT = TEXTSW_ATTR(ATTR_OPAQUE,5), - TEXTSW_FATTR_INSERTION_POINTS = TEXTSW_ATTR(ATTR_OPAQUE,10), - TEXTSW_FATTR_INSERTION_LINE = TEXTSW_ATTR(ATTR_OPAQUE,15), - TEXTSW_FATTR_SELECTION_ENDPOINTS= TEXTSW_ATTR(ATTR_OPAQUE,20) -} Textsw_filter_attribute; - -/* - * Status values for textsw_build and textsw_init. - */ -typedef enum { - TEXTSW_STATUS_OKAY, - TEXTSW_STATUS_OTHER_ERROR, - TEXTSW_STATUS_CANNOT_ALLOCATE, - TEXTSW_STATUS_CANNOT_OPEN_INPUT, - TEXTSW_STATUS_BAD_ATTR, - TEXTSW_STATUS_BAD_ATTR_VALUE, - TEXTSW_STATUS_CANNOT_INSERT_FROM_FILE, - TEXTSW_STATUS_OUT_OF_MEMORY -} Textsw_status; - -/* - * Status values for textsw_expand. - */ -typedef enum { - TEXTSW_EXPAND_OK, - TEXTSW_EXPAND_FULL_BUF, - TEXTSW_EXPAND_OTHER_ERROR -} Textsw_expand_status; - -typedef enum { - TEXTSW_NEVER = 0, - /* - * Additional values for TEXTSW_LOAD_DIR_IS_CD - */ - TEXTSW_ALWAYS = 1, - TEXTSW_ONLY = 2, - /* - * Additional values for TEXTSW_INSERT_MAKES_VISIBLE - */ - TEXTSW_IF_AUTO_SCROLL, - /* - * Valid values for TEXTSW_LINE_BREAK_ACTION - */ - TEXTSW_CLIP, - TEXTSW_WRAP_AT_CHAR, - TEXTSW_WRAP_AT_WORD, - TEXTSW_WRAP_AT_LINE -} Textsw_enum; - -/* - * Menu command tokens - */ -typedef enum { - TEXTSW_MENU_NO_CMD, - /* - * File sub-menu - */ - TEXTSW_MENU_LOAD, - TEXTSW_MENU_SAVE, - TEXTSW_MENU_STORE, - TEXTSW_MENU_FILE_STUFF, - TEXTSW_MENU_RESET, - /* - * Edit sub-menu - */ - TEXTSW_MENU_AGAIN, - TEXTSW_MENU_UNDO, - TEXTSW_MENU_UNDO_ALL, - TEXTSW_MENU_COPY, - TEXTSW_MENU_PASTE, - TEXTSW_MENU_CUT, - /* - * View sub-menu - */ - TEXTSW_MENU_NORMALIZE_LINE, - TEXTSW_MENU_COUNT_TO_LINE, - TEXTSW_MENU_NORMALIZE_INSERTION, - /* - * Change line wrap sub-menu - */ - TEXTSW_MENU_WRAP_LINES_AT_CHAR, - TEXTSW_MENU_WRAP_LINES_AT_WORD, - TEXTSW_MENU_CLIP_LINES, - /* - * Find sub-menu - */ - TEXTSW_MENU_FIND_AND_REPLACE, - TEXTSW_MENU_FIND, - TEXTSW_MENU_FIND_BACKWARD, - /* - * Replace field sub-menu - */ - TEXTSW_MENU_SEL_MARK_TEXT, - TEXTSW_MENU_SEL_ENCLOSE_FIELD, /* Select |> field <| in pending and - * delete mode - */ - TEXTSW_MENU_SEL_NEXT_FIELD, - TEXTSW_MENU_SEL_PREV_FIELD, -#ifdef _TEXTSW_FIND_RE - TEXTSW_MENU_FIND_RE, - TEXTSW_MENU_FIND_RE_BACKWARD, - TEXTSW_MENU_FIND_TAG, - TEXTSW_MENU_FIND_TAG_BACKWARD, -#endif - TEXTSW_MENU_FILE_CMDS, - TEXTSW_MENU_EDIT_CMDS, - TEXTSW_MENU_VIEW_CMDS, - TEXTSW_MENU_FIND_CMDS, - TEXTSW_MENU_EXTRAS_CMDS, - TEXTSW_MENU_LAST_CMD -} Textsw_menu_cmd; - -/* - * Commands for smart filters - */ -typedef enum { - TEXTSW_FILTER_DELETE_RANGE = 0, - TEXTSW_FILTER_INSERT = 1, - TEXTSW_FILTER_SEND_RANGE = 2, - TEXTSW_FILTER_SET_INSERTION = 3, - TEXTSW_FILTER_SET_SELECTION = 4 -} Textsw_filter_command; - -/* - * Structs - */ -typedef struct -{ - Xv_openwin parent_data; - Xv_opaque private_data; -} -Xv_textsw; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_textsw_view; - -/* - *********************************************************************** - * Global Variables and Functions - *********************************************************************** - */ - -extern Xv_pkg xv_textsw_pkg; -extern Xv_pkg xv_textsw_view_pkg; -extern int TEXTSW_MENU_DATA_KEY; - - -/* - * Public functions - */ - -EXTERN_FUNCTION (Textsw_mark textsw_add_mark, (Textsw textsw, Textsw_index position, unsigned flags)); - -EXTERN_FUNCTION (Textsw_index textsw_find_mark, (Textsw textsw, Textsw_mark mark)); -EXTERN_FUNCTION (int textsw_append_file_name, (Textsw textsw, char *name)); - -EXTERN_FUNCTION (Textsw_index textsw_delete, (Textsw textsw, Textsw_index first, Textsw_index last_plus_one)); - -EXTERN_FUNCTION (Textsw_index textsw_edit, (Textsw textsw, unsigned int unit, unsigned int count, unsigned int direction)); - -EXTERN_FUNCTION (Textsw_index textsw_erase, (Textsw textsw, Textsw_index first, Textsw_index last_plus_one)); - -EXTERN_FUNCTION (int textsw_find_bytes, (Textsw textsw, Textsw_index *first, Textsw_index *last_plus_one, char *buf, unsigned int buf_len, unsigned int flags)); - -EXTERN_FUNCTION (void textsw_file_lines_visible, (Textsw textsw, int *top, int *bottom)); - -EXTERN_FUNCTION (Textsw textsw_first, (Textsw textsw)); -EXTERN_FUNCTION (Textsw_index textsw_index_for_file_line, (Textsw textsw, int line)); -EXTERN_FUNCTION (Textsw_index textsw_insert, (Textsw textsw, char *buf, int buf_len)); - -EXTERN_FUNCTION (int textsw_match_bytes, (Textsw textsw, Textsw_index *first, Textsw_index *last_plus_one, char * start_sym, int start_sym_len, char *end_sym, int end_sym_len, unsigned int field_flag)); - -EXTERN_FUNCTION (Textsw textsw_next, (Textsw previous)); -EXTERN_FUNCTION (void textsw_remove_mark, (Textsw textsw, Textsw_mark mark)); - -EXTERN_FUNCTION (Textsw_index textsw_replace_bytes, (Textsw textsw, Textsw_index first, Textsw_index last_plus_one, char *buf, long int buf_len)); - -EXTERN_FUNCTION (void textsw_reset, (Textsw textsw, int locx, int locy)); -EXTERN_FUNCTION (unsigned int textsw_save, (Textsw textsw, int locx, int locy)); -EXTERN_FUNCTION (int textsw_screen_line_count, (Textsw textsw)); -EXTERN_FUNCTION (void textsw_scroll_lines, (Textsw abstract, int count)); -EXTERN_FUNCTION (unsigned int textsw_store_file, (Textsw textsw, char *filename, int locx, int locy)); -/* - * Private functions - */ - -EXTERN_FUNCTION (Textsw_expand_status textsw_expand, (Textsw textsw, Textsw_index start, Textsw_index stop_plus_one, char *out_buf, int out_buf_len, int *total_chars)); - -EXTERN_FUNCTION (int textsw_default_notify, (Textsw textsw, Attr_avlist attrs)); - -EXTERN_FUNCTION (int textsw_nop_notify, (Textsw textsw, Attr_avlist attrs)); - -#ifdef _OTHER_TEXTSW_FUNCTIONS - -EXTERN_FUNCTION (void textsw_normalize_view, (Textsw textsw, Textsw_index pos)); -EXTERN_FUNCTION (void textsw_possibly_normalize, (Textsw textsw, Textsw_index pos)); -EXTERN_FUNCTION (void textsw_set_selection, (Textsw textsw, Textsw_index first, Textsw_index last_plus_one, unsigned int type)); - -#endif /* _OTHER_TEXTSW_FUNCTIONS */ - -#endif /* xview_textsw_DEFINED */ diff --git a/include/xview/tty.h b/include/xview/tty.h deleted file mode 100644 index 7b6fda05bbb..00000000000 --- a/include/xview/tty.h +++ /dev/null @@ -1,141 +0,0 @@ -/* - * @(#)tty.h 20.17 91/09/14 SMI - * - * (c) Copyright 1989 Sun Microsystems, Inc. Sun design patents - * pending in the U.S. and foreign countries. See LEGAL NOTICE - * file for terms of the license. - */ - -#ifndef xview_tty_DEFINED -#define xview_tty_DEFINED - -/* - *********************************************************************** - * Include Files - *********************************************************************** - */ - -#include -#include -#include -#include - -/* - *********************************************************************** - * Definitions and Macros - *********************************************************************** - */ - -/* - * PUBLIC #defines - */ - -#define TTY &xv_tty_pkg - -/* - * Data type declaration for ttysw view - */ -#define TTY_VIEW_TYPE ATTR_PKG_TTY_VIEW -#define TTY_VIEW &xv_tty_view_pkg - -/* - * PRIVATE #defines - */ - -#define TTY_ATTR(type, ordinal) ATTR(ATTR_PKG_TTY, type, ordinal) -#define ATTR_BUF_LEN_USED ATTR_TYPE(ATTR_BASE_OPAQUE, 3) -#define TTY_ARGV_DO_NOT_FORK -1 -#define TTY_INFINITY ((long)0x77777777) - -/* - * PUBLIC #defines - * For SunView 1 Compatibility Only - */ - -/* - * Data type declaration for ttysw folio - */ -#define TTY_TYPE ATTR_PKG_TTY - -/* - *********************************************************************** - * Typedefs, Enumerations, and Structures - *********************************************************************** - */ - -typedef Xv_opaque Tty; -typedef Xv_opaque Tty_view; - -typedef struct -{ - Xv_openwin parent_data; - Xv_opaque private_data; -} -Xv_tty; - -typedef struct -{ - Xv_window_struct parent_data; - Xv_opaque private_data; -} -Xv_tty_view; - -typedef enum { - /* - * Public attributes - */ - TTY_ARGV = TTY_ATTR(ATTR_OPAQUE, 1), - TTY_CONSOLE = TTY_ATTR(ATTR_BOOLEAN, 5), - TTY_INPUT = TTY_ATTR(ATTR_BUF_LEN_USED, 10), - TTY_OUTPUT = TTY_ATTR(ATTR_BUF_LEN_USED, 15), - TTY_PAGE_MODE = TTY_ATTR(ATTR_BOOLEAN, 20), - TTY_QUIT_ON_CHILD_DEATH - = TTY_ATTR(ATTR_BOOLEAN, 25), - /* - * Private attributes - */ - TTY_BOLDSTYLE = TTY_ATTR(ATTR_INT, 30), - TTY_BOLDSTYLE_NAME = TTY_ATTR(ATTR_STRING, 35), - TTY_INVERSE_MODE = TTY_ATTR(ATTR_INT, 40), - TTY_PID = TTY_ATTR(ATTR_INT, 45), - TTY_PTY_FD = TTY_ATTR(ATTR_INT, 50), /* --G */ - TTY_TTY_FD = TTY_ATTR(ATTR_INT, 60), /* --G */ - TTY_UNDERLINE_MODE = TTY_ATTR(ATTR_INT, 65) -} Tty_attribute; - -#undef ATTR_BUF_LEN_USED - -/* - *********************************************************************** - * Globals - *********************************************************************** - */ - -extern Xv_pkg xv_tty_pkg; -extern Xv_pkg xv_tty_view_pkg; - -/* - * Escape sequences recognized by TTY subwindows - * - * \E[1t - open - * \E[2t - close (become iconic) - * \E[3t - move, with interactive feedback - * \E[3;TOP;LEFTt - move, TOP LEFT in pixels - * \E[4t - stretch, with interactive feedback - * \E[4;ROWS;COLSt - stretch, ROWS COLS in pixels - * \E[5t - top (expose) - * \E[6t - bottom (hide) - * \E[7t - refresh - * \E[8;ROWS;COLSt - stretch, ROWS COLS in characters - * \E[11t - report open or iconic, sends \E[1t or \E[2t - * \E[13t - report position, sends \E[3;TOP;LEFTt - * \E[14t - report size in pixels, sends \E[8;ROWS;COLSt - * \E[18t - report size in chars, sends \E[4;ROWS;COLSt - * \E[20t - report icon label, sends \E]Llabel\E\ - * \E[21t - report tool label, sends \E]llabel\E\ - * \E]l\E\ - set tool label to - * \E]I\E\ - set icon file to - * \E]L

") -load_vals_from_sol(atof(argv[1]),atof(argv[2]), - atoi(argv[3])); -WEND - -int W_load_var_from_sol WBEGIN -ERR(2,"Wrong # args: load_var_from_sol ") -load_var_from_sol(atoi(argv[1])); -WEND - -int W_read_iop WBEGIN -ERR(3,"Wrong # args: read_iop ") -read_iop(argv[1],atoi(argv[2])); -WEND - -int W_read_rec WBEGIN -ERR(2,"Wrong # args: read_rec ") -read_rec(argv[1]); -WEND - -int W_read_ncov WBEGIN -ERR(2,"Wrong # args: read_ncov ") -read_ncov(argv[1]); -WEND - -int W_filter_recs WBEGIN -ERR(1,"Wrong # args: filter_recs") -filter_recs(); -WEND - -int W_normalize_time_courses WBEGIN -ERR(2,"Wrong # args: normalize_time_courses ") -normalize_time_courses(atoi(argv[1])); -WEND - -int W_compute_timecourses WBEGIN -ERR(1,"Wrong # args: compute_timecourses") -compute_timecourses(); -WEND - -int W_normalize_inverse WBEGIN -ERR(1,"Wrong # args: normalize_inverse") -normalize_inverse(); -WEND - -int W_compute_pval_fwd WBEGIN -ERR(2,"Wrong # args: compute_pval_fwd ") -compute_pval_fwd(atof(argv[1])); -WEND - -int W_compute_select_fwd WBEGIN -ERR(2,"Wrong # args: compute_select_fwd ") -compute_select_fwd(atof(argv[1])); -WEND - -int W_compute_pval_inv WBEGIN -ERR(1,"Wrong # args: compute_pval_inv") -compute_pval_inv(); -WEND - -int W_find_orig_vertex_coordinates WBEGIN -ERR(1,"Wrong # args: find_orig_vertex_coordinates") -find_orig_vertex_coordinates(selection); -WEND - -int W_select_orig_vertex_coordinates WBEGIN -ERR(1,"Wrong # args: select_orig_vertex_coordinates") -select_orig_vertex_coordinates(&selection); -WEND - -int W_select_talairach_point WBEGIN -ERR(4,"Wrong # args: select_talairach_point ") -select_talairach_point(&selection, - atof(argv[1]),atof(argv[2]),atof(argv[3])); -WEND - -int W_print_nearest_vertex_to_talairach_point WBEGIN -ERR(4,"Wrong # args: print_nearest_vertex_to_talairach_point ") -print_nearest_vertex_to_talairach_point( - atof(argv[1]),atof(argv[2]),atof(argv[3])); -WEND - -int W_read_orig_vertex_coordinates WBEGIN -ERR(1,"Wrong # args: read_orig_vertex_coordinates") -read_orig_vertex_coordinates(orfname); -WEND - -int W_read_white_vertex_coordinates WBEGIN -ERR(1,"Wrong # args: read_white_vertex_coordinates") -read_white_vertex_coordinates(); -WEND - -int W_read_pial_vertex_coordinates WBEGIN -ERR(1,"Wrong # args: read_pial_vertex_coordinates") -read_pial_vertex_coordinates(); -WEND - -int W_read_canon_vertex_coordinates WBEGIN -ERR(2,"Wrong # args: read_canon_vertex_coordinates") -read_canon_vertex_coordinates(argv[1]); -WEND - -int W_send_spherical_point WBEGIN -ERR(4,"Wrong # args: send_spherical_point ") -send_spherical_point(argv[1], argv[2], argv[3]); -WEND -int W_send_contralateral_point WBEGIN - -ERR(3,"Wrong # args: send_contralateral_point ") -send_contralateral_point(argv[1], argv[2]); -WEND - -int W_send_to_subject WBEGIN -ERR(2,"Wrong # args: send_to_subject ") -send_to_subject(argv[1]); -WEND - -int W_send_to_other_hemi WBEGIN -ERR(1,"Wrong # args: send_to_other_hemi") -send_to_other_hemi(); -WEND - -int W_resend_to_subject WBEGIN -ERR(1,"Wrong # args: resend_to_subject") -resend_to_subject(); -WEND - -int W_drawcb WBEGIN -ERR(1,"Wrong # args: drawcb") -drawcb(); -WEND - -int W_read_ellipsoid_vertex_coordinates WBEGIN -ERR(4,"Wrong # args: read_ellipsoid_vertex_coordinates ") -read_ellipsoid_vertex_coordinates(elfname, - atof(argv[1]), - atof(argv[2]), - atof(argv[3])); -WEND - -int W_invert_surface WBEGIN -ERR(1,"Wrong # args: invert_surface ") -invert_surface(); -WEND - -int W_fix_nonzero_vals WBEGIN -ERR(1,"Wrong # args: fix_nonzero_vals ") -fix_nonzero_vals(); -WEND - -int W_invert_vertex WBEGIN -ERR(2,"Wrong # args: invert_vertex ") -invert_vertex(atoi(argv[1])); -WEND - -int W_invert_face WBEGIN -ERR(2,"Wrong # args: invert_face ") -invert_face(atoi(argv[1])); -WEND - -int W_mark_annotation WBEGIN -ERR(1,"Wrong # args: mark_annotation ") -mark_annotation(selection); -WEND - -int W_mark_faces WBEGIN -ERR(2,"Wrong # args: mark_faces ") -mark_faces(atoi(argv[1])); -WEND - -int W_mark_face WBEGIN -ERR(2,"Wrong # args: mark_face ") -mark_face(atoi(argv[1])); -WEND - -int W_dump_vertex WBEGIN -ERR(2,"Wrong # args: dump_vertex ") -dump_vertex(atoi(argv[1])); -WEND - -int W_val_to_mark WBEGIN -ERR(1,"Wrong # args: val_to_mark ") -val_to_mark(); -WEND - -int W_set_area_thresh WBEGIN -ERR(2,"Wrong # args: set_area_thresh ") -set_area_thresh(atof(argv[1])); -WEND - - -int W_scale_brain WBEGIN -ERR(2,"Wrong # args: scale_brain ") -scale_brain(atof(argv[1])); -WEND - -int W_transform_brain WBEGIN -ERR(1,"Wrong # args: transform_brain ") -transform_brain(); -WEND - -int W_show_flat_regions WBEGIN -ERR(3,"Wrong # args: show_flat_regions ") -show_flat_regions(argv[1], atof(argv[2])); -WEND - -int W_val_to_curv WBEGIN -ERR(1,"Wrong # args: val_to_curv ") -val_to_curv(); -WEND - -int W_val_to_stat WBEGIN -ERR(1,"Wrong # args: val_to_stat ") -val_to_stat(); -WEND - -int W_set_vals WBEGIN -ERR(2,"Wrong # args: set_vals ") -MRISsetVals(mris,atof(argv[2])); -WEND - -int W_stat_to_val WBEGIN -ERR(1,"Wrong # args: stat_to_val ") -stat_to_val(); -WEND - - -int W_f_to_p WBEGIN -ERR(3,"Wrong # args: f_to_p(numer_dof, denom_dof) ") -f_to_p(atoi(argv[1]), atoi(argv[2])); -WEND - -int W_t_to_p WBEGIN -ERR(2,"Wrong # args: t_to_p(dof) ") -t_to_p(atoi(argv[1])); -WEND - -int W_f_to_t WBEGIN -ERR(1,"Wrong # args: f_to_t ") -f_to_t(); -WEND - -int W_label_to_stat WBEGIN -ERR(2,"Wrong # args: label_to_stat ") -label_to_stat(atoi(argv[1])); -WEND - -int W_taubin_smooth WBEGIN -ERR(4,"Wrong # args: taubin_smooth where mu < -lambda < 0 ") - taubin_smooth(mris, atoi(argv[1]), atof(argv[2]), atof(argv[3])); -WEND - -int W_label_from_stats WBEGIN -ERR(2,"Wrong # args: label_from_stats ") -label_from_stats(atoi(argv[1])); -WEND - -int W_label_set_stats WBEGIN -ERR(2,"Wrong # args: label_set_stats ") -label_set_stats(atof(argv[1])); -WEND - -int W_remove_triangle_links WBEGIN -ERR(1,"Wrong # args: remove_triangle_links ") -remove_triangle_links(); -WEND - -int W_read_soltimecourse WBEGIN -ERR(2,"Wrong # args: read_soltimecourse ") -read_soltimecourse(argv[1]); -WEND - -int W_read_imag_vals WBEGIN -ERR(2,"Wrong # args: read_imag_vals ") -read_imag_vals(argv[1]); -WEND - -int W_sol_plot WBEGIN -ERR(3,"Wrong # args: sol_plot ") -sol_plot(atoi(argv[1]), atoi(argv[2])); -WEND - -int W_read_curv_to_val WBEGIN -ERR(2,"Wrong # args: read_curv_to_val ") -read_curv_to_val(argv[1]); -WEND - -int W_read_and_smooth_parcellation WBEGIN -ERR(5,"Wrong # args: read_and_smooth_parcellation ") -read_and_smooth_parcellation(argv[1],argv[2], - atoi(argv[3]), - atoi(argv[4])); -WEND - -int W_read_parcellation WBEGIN -ERR(3,"Wrong # args: read_parcellation ") -read_parcellation(argv[1],argv[2]); -WEND - -int W_read_disc WBEGIN -ERR(2,"Wrong # args: read_disc ") -read_disc(argv[1]); -WEND - -int W_deconvolve_weights WBEGIN -ERR(3,"Wrong # args: deconvolve_weights(weight_fname, scale_fname) ") -deconvolve_weights(argv[1], argv[2]); -WEND - -int W_curv_to_val WBEGIN -ERR(1,"Wrong # args: curv_to_val ") -curv_to_val(); -WEND - -int W_scale_vals WBEGIN -ERR(2,"Wrong # args: scale_vals ") - scale_vals(atof(argv[1])); -WEND - -int W_mask_label WBEGIN -ERR(2,"Wrong # args: mask_label ") -mask_label(argv[1]); -WEND - -int W_dump_faces WBEGIN -ERR(2,"Wrong # args: dump_faces ") -dump_faces(atoi(argv[1])); -WEND - -int W_load_gcsa WBEGIN -ERR(2,"Wrong # args: load_gcsa ") -load_gcsa(argv[1]); -WEND - -int W_orient_sphere WBEGIN -ERR(1,"Wrong # args: orient_sphere ") -orient_sphere(); -WEND - -int W_draw_ellipsoid_latlong WBEGIN -ERR(4,"Wrong # args: draw_ellipsoid_latlong ") -draw_ellipsoid_latlong(atof(argv[1]),atof(argv[2]), - atof(argv[3])); -WEND -int W_left_click WBEGIN -ERR(3,"Wrong # args: left_click [relative to window 0,0]") -left_click( - (short)atoi(argv[1]),(short)atoi(argv[2])); - -WEND - -int W_plot_all_time_courses WBEGIN -ERR(1,"Wrong # args: plot_all_time_courses") -plot_all_time_courses(); -WEND - -int W_read_plot_list WBEGIN -ERR(2,"Wrong # args: read_plot_list ") -read_plot_list(argv[1]); -WEND - -int W_read_vertex_list WBEGIN -ERR(2,"Wrong # args: read_vertex_list ") -read_vertex_list(argv[1]); -WEND - -int W_draw_cursor WBEGIN -ERR(3,"Wrong # args: draw_cursor ") -draw_cursor(atoi(argv[1]),atoi(argv[2])); -WEND - -int W_draw_marked_vertices WBEGIN -ERR(1,"Wrong # args: draw_marked_vertices") -draw_marked_vertices(); -WEND - -int W_mark_vertex WBEGIN -ERR(3,"Wrong # args: mark_vertex ") -mark_vertex(atoi(argv[1]),atoi(argv[2])); -WEND - -int W_mark_translated_vertex WBEGIN -ERR(4,"Wrong # args: mark_translated_vertex ") -mark_translated_vertex(atoi(argv[1]),atoi(argv[2]), argv[3]); -WEND - -int W_draw_all_cursor WBEGIN -ERR(1,"Wrong # args: draw_all_cursor") -draw_all_cursor(); -WEND - -int W_draw_all_vertex_cursor WBEGIN -ERR(1,"Wrong # args: draw_all_vertex_cursor") -draw_all_vertex_cursor(); -WEND - -int W_clear_all_vertex_cursor WBEGIN -ERR(1,"Wrong # args: clear_all_vertex_cursor") -clear_all_vertex_cursor(); -WEND -/* begin rkt */ -int W_send_current_labels WBEGIN -ERR(1, "Wrong # args: send_current_labels") -send_current_labels (); -WEND - -int W_select_vertex_by_vno WBEGIN -ERR(2, "Wrong # args: select_vertex_by_vno vno") -select_vertex_by_vno (atoi(argv[1])); -WEND - -int W_swap_vertex_fields WBEGIN -ERR(3,"Wrong # args: swap_vertex_fields ") -swap_vertex_fields(atoi(argv[1]),atoi(argv[2])); -WEND -int W_clear_vertex_marks WBEGIN -ERR(1,"Wrong # args: clear_vertex_marks") -clear_vertex_marks(); -WEND -int W_clear_all_vertex_marks WBEGIN -ERR(1,"Wrong # args: clear_all_vertex_marks") -clear_all_vertex_marks(); -WEND - -int W_close_marked_vertices WBEGIN -ERR(1,"Wrong # args: close_marked_vertices") -close_marked_vertices(); -WEND - -int W_undo_last_action WBEGIN -ERR(1,"Wrong # args: undo_last_action") -undo_do_first_action(); -WEND - -int W_sclv_read_from_dotw WBEGIN -ERR(2,"Wrong # args: sclv_read_from_dotw field") -sclv_read_from_dotw(vfname,atoi(argv[1])); -WEND - -int W_sclv_read_from_dotw_frame WBEGIN -ERR(2,"Wrong # args: sclv_read_from_dotw_frame field") -sclv_read_from_dotw_frame(vfname,atoi(argv[1])); -WEND - -int W_sclv_write_dotw WBEGIN -ERR(2,"Wrong # args: sclv_write_dotw field") -sclv_write_dotw(vfname,atoi(argv[1])); -WEND - -int W_read_surface_vertex_set WBEGIN -ERR(3,"Wrong # args: read_surface_vertex_set field file") -vset_read_vertex_set(atoi(argv[1]), argv[2]); -WEND - -int W_set_current_vertex_set WBEGIN -ERR(2,"Wrong # args: set_current_vertex_set field") -vset_set_current_set(atoi(argv[1])); -WEND - -int W_sclv_load_label_value_file WBEGIN -ERR(3,"Wrong # args: sclv_load_label_value_file fname field") -sclv_load_label_value_file(argv[1],atoi(argv[2])); -WEND - - -int W_func_load_timecourse (ClientData clientData,Tcl_Interp *interp, - int argc,char *argv[]) -{ - FunD_tRegistrationType reg_type = FunD_tRegistration_None; - - if (argc!=3 && argc!=4) - { - Tcl_SetResult(interp,"Wrong # args: func_load_timecourse volumeFileName" - "registrationType [registrationFileName]",TCL_VOLATILE); - return TCL_ERROR; - } - - reg_type = (FunD_tRegistrationType) atoi (argv[2]); - - if (argc==3) - func_load_timecourse (argv[1], reg_type, NULL); - /* even if we have 3 args, tcl could have passed us a blank string - for the 4th. if it's blank, call the load function with a null - registration, otherwise it will think it's a valid file name. */ - if (argc==4) - { - if (strcmp(argv[3],"")==0) - func_load_timecourse (argv[1], reg_type, NULL); - else - func_load_timecourse (argv[1], reg_type, argv[2]); - } - return TCL_OK; -} - -int W_func_load_timecourse_offset (ClientData clientData,Tcl_Interp *interp, - int argc,char *argv[]) -{ - FunD_tRegistrationType reg_type = FunD_tRegistration_None; - - if (argc!=3 && argc!=4) - { - Tcl_SetResult(interp,"Wrong # args: func_load_timecourse_offset fname" - "registrationType [registration]",TCL_VOLATILE); - return TCL_ERROR; - } - - reg_type = (FunD_tRegistrationType) atoi (argv[2]); - - if (argc==3) - func_load_timecourse_offset (argv[1], reg_type, NULL); - /* even if we have 3 args, tcl could have passed us a blank string - for the 4th. if it's blank, call the load function with a null - registration, otherwise it will think it's a valid file name. */ - if (argc==4) - { - if (strcmp(argv[3],"")==0) - func_load_timecourse_offset (argv[1], reg_type, NULL); - else - func_load_timecourse_offset (argv[1], reg_type, argv[2]); - } - - return TCL_OK; -} - -int W_sclv_read_from_volume (ClientData clientData,Tcl_Interp *interp, - int argc,char *argv[]) -{ - FunD_tRegistrationType reg_type = FunD_tRegistration_None; - - if (argc!=4&&argc!=5) - { - Tcl_SetResult(interp,"Wrong # args: sclv_read_from_volume field fname " - "registrationType [registration]",TCL_VOLATILE); - return TCL_ERROR; - } - - reg_type = (FunD_tRegistrationType) atoi (argv[3]); - - if (argc==4) - sclv_read_from_volume (argv[2], reg_type, NULL, atoi(argv[1])); - /* even if we have 4 args, tcl could have passed us a blank string - for the 4th. if it's blank, call the read function with a null - registration, otherwise it will think it's a valid file name. */ - if (argc==5) - { - if (strcmp(argv[4],"")==0) - sclv_read_from_volume (argv[2], reg_type, NULL, atoi(argv[1])); - else - sclv_read_from_volume (argv[2], reg_type, argv[4], atoi(argv[1])); - } - return TCL_OK; -} -int W_sclv_smooth WBEGIN -ERR(3,"Wrong # args: sclv_smooth steps field") -sclv_smooth(atoi(argv[1]), atoi(argv[2])); -WEND -int W_sclv_set_overlay_alpha WBEGIN -ERR(2,"Wrong # args: sclv_set_overlay_alpha alpha") -sclv_set_overlay_alpha(atof(argv[1])); -WEND -int W_sclv_set_current_field WBEGIN -ERR(2,"Wrong # args: sclv_set_current_field field") -sclv_set_current_field(atoi(argv[1])); -WEND -int W_sclv_unload_field WBEGIN -ERR(2,"Wrong # args: sclv_unload_field field") -sclv_unload_field(atoi(argv[1])); -WEND -int W_sclv_set_current_timepoint WBEGIN -ERR(3,"Wrong # args: sclv_set_current_timepoint timepoint condition") -sclv_set_timepoint_of_field(sclv_current_field, - atoi(argv[1]),atoi(argv[2])); -WEND -int W_sclv_copy_view_settings_from_field WBEGIN -ERR(3,"Wrong # args: sclv_copy_view_settings_from_field field fromfield") -sclv_copy_view_settings_from_field(atoi(argv[1]),atoi(argv[2])); -WEND -int W_sclv_copy_view_settings_from_current_field WBEGIN -ERR(2,"Wrong # args: sclv_copy_view_settings_from_current_field field") -sclv_copy_view_settings_from_current_field(atoi(argv[1])); -WEND -int W_sclv_copy_all_view_settings_from_current_field WBEGIN -ERR(1,"Wrong # args: sclv_copy_all_view_settings_from_current_field") -sclv_copy_all_view_settings_from_current_field(); -WEND -int W_sclv_set_current_threshold_from_percentile WBEGIN -ERR(4,"Wrong # args: sclv_set_current_threshold_from_percentile " - "thresh mid slope") -sclv_set_current_threshold_from_percentile( - atof(argv[1]), - atof(argv[2]), - atof(argv[3])); -WEND -int W_sclv_set_current_threshold_using_fdr WBEGIN -ERR(3,"Wrong # args: sclv_set_current_threshold_using_fdr rate marked") -sclv_set_threshold_using_fdr(sclv_current_field,atof( - argv[1]), - atoi(argv[2])); -WEND -int W_sclv_send_histogram WBEGIN -ERR(2,"Wrong # args: sclv_send_histogram field") -sclv_send_histogram(atoi(argv[1])); -WEND -int W_sclv_send_current_field_info WBEGIN -ERR(1,"Wrong # args: sclv_send_current_field_info") -sclv_send_current_field_info(); -WEND - - -int W_sclv_get_normalized_color_for_value (ClientData clientData, - Tcl_Interp *interp, - int argc,char *argv[]) -{ - float r, g, b; - char stringResult[256]; - - if (argc!=2) - { - Tcl_SetResult(interp,"Wrong # args: sclv_get_normalized_color_for_value " - "value",TCL_VOLATILE); - return TCL_ERROR; - } - - /* get the rgb values here and print them to a string */ - sclv_get_normalized_color_for_value (sclv_current_field, - atof(argv[1]), &r, &g, &b); - sprintf (stringResult, "%f %f %f", r, g, b); - - /* set tcl result, volatile so tcl will make a copy of it. */ - Tcl_SetResult( interp, stringResult, TCL_VOLATILE ); - - return TCL_OK; -} - - -int W_func_select_marked_vertices WBEGIN -ERR(1,"Wrong # args: func_select_marked_vertices") -func_select_marked_vertices(); -WEND -int W_func_select_selected_vertex WBEGIN -ERR(1,"Wrong # args: func_select_selected_vertex") -func_select_selected_vertex(); -WEND -int W_func_select_label WBEGIN -ERR(1,"Wrong # args: func_select_label") -func_select_label(); -WEND -int W_func_clear_selection WBEGIN -ERR(1,"Wrong # args: func_clear_selection") -func_clear_selection(); -WEND -int W_func_graph_timecourse_selection WBEGIN -ERR(1,"Wrong # args: func_graph_timecourse_selection") -func_graph_timecourse_selection(); -WEND -int W_func_print_timecourse_selection WBEGIN -ERR(2,"Wrong # args: func_print_timecourse_selection filename") -func_print_timecourse_selection(argv[1]); -WEND - - -int W_labl_load_color_table WBEGIN -ERR(2,"Wrong # args: labl_load_color_table filename") -labl_load_color_table (argv[1]); -WEND -int W_labl_load WBEGIN -ERR(2,"Wrong # args: labl_load filename") -labl_load (argv[1]); -WEND -int W_labl_save WBEGIN -ERR(3,"Wrong # args: labl_save index filename") -labl_save (atoi(argv[1]), argv[2]); -WEND -int W_labl_save_all WBEGIN -ERR(1,"Wrong # args: labl_save_all prefix") -labl_save_all (argv[1]); -WEND -int W_labl_import_annotation WBEGIN -ERR(2,"Wrong # args: labl_import_annotation filename") -labl_import_annotation (argv[1]); -WEND -int W_labl_export_annotation WBEGIN -ERR(2,"Wrong # args: labl_export_annotation filename") -labl_export_annotation (argv[1]); -WEND -int W_labl_new_from_marked_vertices WBEGIN -ERR(1,"Wrong # args: labl_new_from_marked_vertices") -labl_new_from_marked_vertices (NULL); -WEND -int W_labl_mark_vertices WBEGIN -ERR(2,"Wrong # args: labl_mark_vertices index") -labl_mark_vertices (atoi(argv[1])); -WEND -int W_labl_select WBEGIN -ERR(2,"Wrong # args: labl_select index") -labl_select (atoi(argv[1])); -WEND -int W_labl_set_name_from_table WBEGIN -ERR(2,"Wrong # args: labl_set_name_from_table index") -labl_set_name_from_table (atoi(argv[1])); -WEND -int W_labl_set_info WBEGIN -ERR(8,"Wrong # args: labl_set_info index name structure visibility") -labl_set_info (atoi(argv[1]), - argv[2], atoi(argv[3]), - atoi(argv[4]), atoi(argv[5]), - atoi(argv[6]), atoi(argv[7]) ); -WEND -int W_labl_set_color WBEGIN -ERR(5,"Wrong # args: labl_set_color index r g b") -labl_set_color (atoi(argv[1]), atoi(argv[2]), - atoi(argv[3]), atoi(argv[4]) ); -WEND -int W_labl_remove WBEGIN -ERR(2,"Wrong # args: labl_remove index") -labl_remove (atoi(argv[1])); -WEND -int W_labl_threshold WBEGIN -ERR(3,"Wrong # args: labl_threshold index threshold") -labl_threshold (atoi(argv[1]), atof(argv[2])); -WEND -int W_labl_remove_all WBEGIN -ERR(1,"Wrong # args: labl_remove_all") -labl_remove_all (); -WEND -int W_labl_select_label_by_vno WBEGIN -ERR(2,"Wrong # args: labl_select_label_by_vno vno") -labl_select_label_by_vno (atoi(argv[1])); -WEND -int W_labl_erode WBEGIN -ERR(2,"Wrong # args: labl_erode index") -labl_erode (atoi(argv[1])); -WEND -int W_labl_dilate WBEGIN -ERR(2,"Wrong # args: labl_dilate index") -labl_dilate (atoi(argv[1])); -WEND -int W_labl_fill_holes WBEGIN -ERR(2,"Wrong # args: labl_fill_holes index") -labl_fill_holes (atoi(argv[1])); -WEND -int W_labl_print_list WBEGIN -ERR(1,"Wrong # args: labl_print_list") -labl_print_list(); -WEND -int W_labl_print_table WBEGIN -ERR(1,"Wrong # args: labl_print_table") -labl_print_table(); -WEND -int W_path_select WBEGIN -ERR(2,"Wrong # args: path_select") -path_select( atoi(argv[1])); -WEND -int W_path_new_path_from_marked_vertices WBEGIN -ERR(1,"Wrong # args: path_new_path_from_marked_vertices") -path_new_path_from_marked_vertices(); -WEND -int W_path_remove_selected_path WBEGIN -ERR(1,"Wrong # args: path_remove_selected_path") -path_remove_selected_path(); -WEND -int W_path_mark_selected_path WBEGIN -ERR(1,"Wrong # args: path_mark_selected_path") -path_mark_selected_path(); -WEND -int W_path_save WBEGIN -ERR(2,"Wrong # args: path_save fname") -path_save(argv[1]); -WEND -int W_path_load WBEGIN -ERR(2,"Wrong # args: path_load fname") -path_load(argv[1]); -WEND -int W_edit_vertex_at_cursor WBEGIN -ERR(3,"Wrong # args: edit_vertex_at_cursor action argument") -edit_vertex_at_cursor(atoi(argv[1]), atoi(argv[2])); -WEND - -int W_fill_flood_from_cursor (ClientData clientData,Tcl_Interp *interp, - int argc,char *argv[]) -{ - FILL_PARAMETERS params; - char first_fill; - int seed; - int seeds[mris->nvertices]; - int nseeds; - int n; - - if (argc != 9) - { - Tcl_SetResult(interp,"Wrong # args: fill_flood_from_cursor " - "dont_cross_path dont_cross_label dont_fill_unlabeled " - "dont_cross_cmid dont_cross_fthresh " - "use_multiple_seeds action argument", - TCL_VOLATILE); - return TCL_ERROR; - } - - params.dont_cross_path = atoi(argv[1]); - params.dont_cross_label = atoi(argv[2]); - params.dont_fill_unlabeled = atoi(argv[3]); - params.dont_cross_cmid = atoi(argv[4]); - params.dont_cross_fthresh = atoi(argv[5]); - params.use_multiple_seeds = atoi(argv[6]); - params.action = atoi(argv[7]); - params.argument = atoi(argv[8]); - - if (params.use_multiple_seeds) - { - /* Since making a label will mess with the marked array, we need to - copy the marked verts to use them as seeds. */ - for (n = 0; n < nmarked; n++) - seeds[n] = marked[n]; - nseeds = nmarked; - - /* Clear the marked verts so any extraneous ones don't end up in the - label. */ - clear_all_vertex_marks(); - - /* Fill for each seed point. */ - first_fill = TRUE; - for (n = 0; n < nseeds; n++) - { - fill_flood_from_seed (seeds[n], ¶ms); - - /* If this was the first fill and this was a NEW_LABEL - action, take the new label index that was pasesd back in - the params block and make it the new argument of a - ADD_LABEL action, so that the next label is added to the - one we just made. */ - if (first_fill && FILL_ACTION_NEW_LABEL == params.action ) - { - first_fill = FALSE; - params.action = FILL_ACTION_ADD_LABEL; - params.argument = params.new_label_index; - } - } - } - else - { - /* Use the selection as the seed. */ - seed = selection; - - /* Clear the marked verts so any extraneous ones don't end up in the - label. */ - clear_all_vertex_marks(); - - /* Fill using the first seed. */ - fill_flood_from_seed (seed, ¶ms); - } - - return TCL_OK; -} - -int W_get_marked_vnos ( ClientData clientData, Tcl_Interp *interp, - int argc, char *argv[] ) -{ - Tcl_Obj *list; - int vno; - VERTEX* v = NULL; - - if (argc != 1) - { - Tcl_SetResult(interp, "Wrong # args: get_marked_vnos", TCL_VOLATILE); - return TCL_ERROR; - } - - list = Tcl_NewListObj(0,NULL); - - for (vno = 0; vno < mris->nvertices; vno++) - { - v = &mris->vertices[vno]; - if (v->marked) - { - Tcl_ListObjAppendElement(interp,list,Tcl_NewIntObj(vno)); - } - } - - Tcl_SetObjResult(interp,list); - - return TCL_OK; -} - -int W_get_selected_path_vnos ( ClientData clientData, Tcl_Interp *interp, - int argc, char *argv[] ) -{ - Tcl_Obj *list; - int path_vno, vno; - - if (argc != 1) - { - Tcl_SetResult(interp, "Wrong # args: get_selected_path_vnos", - TCL_VOLATILE); - return TCL_ERROR; - } - - if (path_selected_path < 0 || path_selected_path >= path_num_paths) - { - Tcl_SetResult(interp, "No path selected.", TCL_VOLATILE); - return TCL_ERROR; - } - - list = Tcl_NewListObj(0,NULL); - - for (path_vno = 0; - path_vno < path_paths[path_selected_path].num_vertices; - path_vno++) - { - vno = path_paths[path_selected_path].vertices[path_vno]; - Tcl_ListObjAppendElement(interp,list,Tcl_NewIntObj(vno)); - } - - Tcl_SetObjResult(interp,list); - - return TCL_OK; -} - -int W_save_tiff WBEGIN -ERR(2,"Wrong # args: save_tiff filename") -save_tiff(argv[1]); -WEND - -int W_flip_normals WBEGIN -ERR(2,"Wrong # args: flip_normals axes") -flip_normals(argv[1]); -WEND - -int W_mark_contiguous_vertices_over_thresh WBEGIN -ERR(1,"Wrong # args: mark_contiguous_vertices_over_thresh") -mark_contiguous_vertices_over_thresh(); -WEND - -int W_mark_contiguous_vertices_with_similar_curvature WBEGIN -ERR(1,"Wrong # args: mark_contiguous_vertices_with_similar_curvature") -mark_contiguous_vertices_with_similar_curvature(); -WEND - -int W_rip_all_vertices_except_contiguous_upripped WBEGIN -ERR(1,"Wrong # args: rip_all_vertices_except_contiguous_upripped") -rip_all_vertices_except_contiguous_upripped (); -WEND - -int W_func_calc_correlation_and_write_to_overlay WBEGIN -ERR(2,"Wrong # args: func_calc_correlation_and_write_to_overlay field") -func_calc_correlation_and_write_to_overlay(selection,atoi(argv[1])); -WEND - -int W_func_normalize WBEGIN -ERR(1,"Wrong # args: func_normalize") -func_normalize(); -WEND - -int W_cptn_set_format_string WBEGIN -ERR(2,"Wrong # args: cptn_set_format_string string") -cptn_set_format_string(argv[1]); -WEND - - - -/* end rkt */ -/*===================================================================*/ - -/* licensing */ - -#ifdef USE_LICENSE -#ifndef IRIX -extern char *crypt(char *, char *) ; -#endif -void checkLicense(char* dirname) -{ - FILE* lfile; - char* email; - char* magic; - char* key; - char* gkey; - char* lfilename; - - lfilename = (char*)malloc(512); - email = (char*)malloc(512); - magic = (char*)malloc(512); - key = (char*)malloc(512); - gkey = (char*)malloc(1024); - - sprintf(lfilename,"%s/.license",dirname); - - lfile = fopen(lfilename,"r"); - if (lfile) - { - fscanf(lfile,"%s\n",email); - fscanf(lfile,"%s\n",magic); - fscanf(lfile,"%s\n",key); - - sprintf(gkey,"%s.%s",email,magic); - if (strcmp(key,crypt(gkey,"*C*O*R*T*E*C*H*S*0*1*2*3*"))!=0) - { - printf("No valid license key !\n"); - exit(-1); - } - } - else - { - printf("License file not found !\n"); - exit(-1); - } - free(email); - free(magic); - free(key); - free(gkey); - free(lfilename); - return; -} - -#endif - -/* for tcl/tk */ -#ifndef Windows_NT -static void StdinProc _ANSI_ARGS_((ClientData clientData, int mask)); -#endif -static void Prompt _ANSI_ARGS_((Tcl_Interp *interp, int partial)); -#ifndef TCL8 -static Tk_Window mainWindow; -#endif -static Tcl_Interp *interp; -static Tcl_DString command; -static int tty; - -int main(int argc, char *argv[]) /* new main */ -{ - int code; - int aliasflag=FALSE; -#ifndef TCL8 - static char *display = NULL; -#endif - char tksurfer_tcl[NAME_LENGTH]; - char str[NAME_LENGTH]; - char alias_tcl[NAME_LENGTH]; - char *envptr; - FILE *fp; -#ifndef USE_XGLUT_WINDOW - struct timeval tv; -#endif /* USE_XGLUT_WINDOW */ - /* begin rkt */ - int found_script = FALSE; - char* tksurfer_scripts_dir = NULL; - int nargs; - char tcl_cmd[STRLEN] = ""; - /* end rkt */ - - /* rkt: check for and handle version tag */ - nargs = - handle_version_option - (argc, argv, - "$Id: tksurfer.c,v 1.364 2016/12/11 14:33:47 fischl Exp $", "$Name: $"); - if (nargs && argc - nargs == 1) - exit (0); - argc -= nargs; - - Progname = argv[0] ; - ErrorInit(NULL, NULL, NULL) ; - DiagInit(NULL, NULL, NULL) ; - - //#ifdef USE_XGLUT_WINDOW - //NJS note: glut needs to initialized, even if USE_XGLUT_WINDOW is not - //defined, because if freeglut is used, then glutinit needs be to called - //in order for certain tksurfer functions to work, like the 'Show Color - //Scale Bar' button. - /* init glut */ - DebugNote( ("Initializing glut") ); - glutInit( &argc, argv ); - glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE ); - //#endif - - /* begin rkt */ - undo_initialize(); - vset_initialize(); - func_initialize(); - sclv_initialize(); - conv_initialize(); - labl_initialize(); - cncl_initialize(); - path_initialize(); - cptn_initialize(); - /* end rkt */ - - /* get tksurfer tcl startup script location from environment */ - envptr = getenv("FREESURFER_HOME"); - if (envptr==NULL) - { - printf("tksurfer: env var FREESURFER_HOME undefined (use setenv)\n"); - printf(" [dir containing mri distribution]\n"); - exit(0); - } - -#ifdef USE_LICENSE - checkLicense(envptr); -#endif - - /* begin rkt */ - - /* here is the priority of the tksurfer.tcl files: - 1) tksurfer.new.tcl in TKSURFER_SCRIPTS_DIR - 2) tksurfer.tcl in TKSURFER_SCRIPTS_DIR - 3) tksurfer.new.tcl in local dir - 4) tksurfer.tcl in local dir - 5) tksurfer.new.tcl in FREESURFER_HOME/tktools - 6) tksurfer.tcl in FREESURFER_HOME/tktools - */ - - found_script = FALSE; - tksurfer_scripts_dir = getenv ("TKSURFER_SCRIPTS_DIR"); - - if (!found_script && tksurfer_scripts_dir) - { - sprintf (tksurfer_tcl, "%s/tksurfer.new.tcl", tksurfer_scripts_dir); - if ((fp=fopen(tksurfer_tcl,"r"))!=NULL) - { - fclose(fp); - found_script = TRUE; - } - } - if (!found_script && tksurfer_scripts_dir) - { - sprintf (tksurfer_tcl, "%s/tksurfer.tcl", tksurfer_scripts_dir); - if ((fp=fopen(tksurfer_tcl,"r"))!=NULL) - { - fclose(fp); - found_script = TRUE; - } - } - if (!found_script) - { - strcpy (tksurfer_tcl, "tksurfer.new.tcl"); - if ((fp=fopen(tksurfer_tcl,"r"))!=NULL) - { - fclose(fp); - found_script = TRUE; - } - } - if (!found_script) - { - strcpy (tksurfer_tcl, "tksurfer.tcl"); - if ((fp=fopen(tksurfer_tcl,"r"))!=NULL) - { - fclose(fp); - found_script = TRUE; - } - } - if (!found_script && envptr) - { - sprintf (tksurfer_tcl, "%s/tktools/tksurfer.new.tcl", envptr); - if ((fp=fopen(tksurfer_tcl,"r"))!=NULL) - { - fclose(fp); - found_script = TRUE; - } - } - if (!found_script && envptr) - { - sprintf (tksurfer_tcl, "%s/tktools/tksurfer.tcl", envptr); - if ((fp=fopen(tksurfer_tcl,"r"))!=NULL) - { - fclose(fp); - found_script = TRUE; - } - } - if (!found_script) - { - printf ("surfer: cannot find tksurfer.tcl script\n"); - exit (1); - } - - /* end rkt */ - - /* look for script: (1) cwd, - (2) FREESURFER_HOME/lib/tcl, (3) [same]/alias.tcl */ - sprintf(script_tcl,"%s/lib/tcl/twocond-views.tcl",envptr); /* default */ - if (argc==6) - { - strcpy(str,argv[4]); - if (MATCH_STR("-tcl")) /* if command line script, run as batch job */ - { - char *cp ; - - if (argc!=6) - { - printf("Usage: tksurfer [-]name hemi surf [-tcl script]\n"); - exit(0); - } - - strcpy(script_tcl,argv[5]); - fp = fopen(script_tcl,"r"); /* first, look in cwd */ - if (fp==NULL) /* then FREESURFER_HOME/lib/tcl dir */ - { - sprintf(script_tcl,"%s/lib/tcl/%s",envptr,argv[5]); - fp = fopen(script_tcl,"r"); - if (fp == NULL) /* then FREESURFER_HOME/tktools dir */ - { - sprintf(script_tcl,"%s/tktools/%s",envptr,argv[5]); - fp = fopen(script_tcl,"r"); - if (fp == NULL) /* then TKSURFER_TCL_SCRIPTS dir */ - { - cp = getenv("TKSURFER_TCL_SCRIPTS") ; - if (cp) - /* see if script is in users has own scripts directory */ - { - sprintf(script_tcl,"%s/%s",cp,argv[5]); - fp = fopen(script_tcl,"r"); - } else - fp = NULL ; - if (fp==NULL) /* then aliases */ - { - aliasflag = TRUE; - sprintf(script_tcl,"%s/lib/tcl/alias.tcl",envptr); - fp = fopen(script_tcl,"r"); - if (fp==NULL) /* couldn't find it anywhere */ - { - printf("tksurfer: (1) File ./%s not found\n", - argv[5]); - printf(" (2) File %s/lib/tcl/%s " - "not found\n", - envptr,argv[5]); - printf(" (3) File %s/lib/tcl/alias.tcl " - "not found\n", - envptr); - exit(0); - } - } - } - } - } - scriptok = TRUE; - } else - { - ; /* ignore 6 arg command lines without -tcl option */ - } - } - - /* start surfer, now as function; gl window not opened yet */ - /* printf("tksurfer: starting surfer\n");*/ - Surfer((ClientData) NULL, interp, argc, argv); /* event loop commented out */ - - /* start tcl/tk; first make interpreter */ - interp = Tcl_CreateInterp(); - /* begin rkt */ - g_interp = interp; - - /* end rkt */ - - /* make main window (not displayed until event loop starts) */ - /*mainWindow = TkCreateMainWindow(interp, display, argv[0], "Tk"); - if (mainWindow == NULL) { - fprintf(stderr, "%s\n", interp->result); - exit(1); } - */ - /* set the "tcl_interactive" variable */ - tty = isatty(0); - Tcl_SetVar(interp, "tcl_interactive", (tty) ? "1" : "0", TCL_GLOBAL_ONLY); - if (tty) promptflag = TRUE; /* no-CR blocks pipe log read */ - - /* read tcl/tk internal startup scripts */ - if (Tcl_Init(interp) == TCL_ERROR) - { - fprintf(stderr, "Tcl_Init failed: %s\n", interp->result); - } - if (Tk_Init(interp) == TCL_ERROR) - { - fprintf(stderr, "Tk_Init failed: %s\n", interp->result); - } - - // later version of Tix needs these. - // Unfortunately Tix does not define Major and Minor - // to distinguish what it is (stupidity). I had to use gnu ;-(.... - // Do the following only for RedHat Enterprise Linux only - -#if NEEDS_ITCL_ITK - if (Itcl_Init(interp) == TCL_ERROR) - { - fprintf(stderr, "Itcl_Init failed: %s\n", interp->result); - } - if (Itk_Init(interp) == TCL_ERROR) - { - fprintf(stderr, "Itk_Init failed: %s\n", interp->result); - } -#endif - - /* begin rkt */ - if (Tix_Init(interp) == TCL_ERROR) - { - fprintf(stderr, "Tix_Init failed: %s\n", interp->result); - } - if (Blt_Init(interp) == TCL_ERROR) - { - fprintf(stderr, "Blt_Init failed: %s\n", interp->result); - } - - /* Initialize our Fsgdf functions. This is in fsgdf_wrap.c */ - if (Fsgdf_Init(interp) == TCL_ERROR) - { - fprintf(stderr, "Fsgdf_Init failed: %s\n", interp->result); - } - - Tcl_StaticPackage( interp, "BLT", Blt_Init, Blt_SafeInit ); -#ifdef Windows_NT -#define Tix_SafeInit NULL -#endif - Tcl_StaticPackage( interp, "Tix", Tix_Init, Tix_SafeInit ); - /* end rkt */ - - /*=======================================================================*/ - /* register wrapped surfer functions with interpreter */ - Tcl_CreateCommand(interp, "swap_buffers", - (Tcl_CmdProc*) W_swap_buffers, REND); - Tcl_CreateCommand(interp, "to_single_buffer", - (Tcl_CmdProc*) W_to_single_buffer, REND); - Tcl_CreateCommand(interp, "to_double_buffer", - (Tcl_CmdProc*) W_to_double_buffer, REND); - Tcl_CreateCommand(interp, "open_window", - (Tcl_CmdProc*) W_open_window, REND); - Tcl_CreateCommand(interp, "help", - (Tcl_CmdProc*) W_help, REND); - Tcl_CreateCommand(interp, "redraw", - (Tcl_CmdProc*) W_redraw, REND); - Tcl_CreateCommand(interp, "redraw_second", - (Tcl_CmdProc*) W_redraw_second, REND); - Tcl_CreateCommand(interp, "shrink", - (Tcl_CmdProc*) W_shrink, REND); - Tcl_CreateCommand(interp, "area_shrink", - (Tcl_CmdProc*) W_area_shrink, REND); - Tcl_CreateCommand(interp, "sphere_shrink", - (Tcl_CmdProc*) W_sphere_shrink, REND); - Tcl_CreateCommand(interp, "ellipsoid_project", - (Tcl_CmdProc*) W_ellipsoid_project, REND); - Tcl_CreateCommand(interp, "ellipsoid_morph", - (Tcl_CmdProc*) W_ellipsoid_morph, REND); - Tcl_CreateCommand(interp, "ellipsoid_shrink", - (Tcl_CmdProc*) W_ellipsoid_shrink, REND); - Tcl_CreateCommand(interp, "ellipsoid_shrink_bug", - (Tcl_CmdProc*) W_ellipsoid_shrink_bug,REND); - Tcl_CreateCommand(interp, "curv_shrink_to_fill", - (Tcl_CmdProc*) W_curv_shrink_to_fill,REND); - Tcl_CreateCommand(interp, "smooth_curvim", - (Tcl_CmdProc*) W_smooth_curvim, REND); - Tcl_CreateCommand(interp, "smooth_curv", - (Tcl_CmdProc*) W_smooth_curv, REND); - Tcl_CreateCommand(interp, "smooth_val", - (Tcl_CmdProc*) W_smooth_val, REND); - Tcl_CreateCommand(interp, "smooth_val_sparse", - (Tcl_CmdProc*) W_smooth_val_sparse, REND); - Tcl_CreateCommand(interp, "smooth_curvim_sparse", - (Tcl_CmdProc*) W_smooth_curvim_sparse, REND); - Tcl_CreateCommand(interp, "smooth_fs", - (Tcl_CmdProc*) W_smooth_fs, REND); - Tcl_CreateCommand(interp, "add_subject_to_average_curvim", - (Tcl_CmdProc*) W_add_subject_to_average_curvim,REND); - Tcl_CreateCommand(interp, "read_curv_images", - (Tcl_CmdProc*) W_read_curv_images, REND); - Tcl_CreateCommand(interp, "read_stds", - (Tcl_CmdProc*) W_read_stds, REND); - Tcl_CreateCommand(interp, "read_second_binary_surf", - (Tcl_CmdProc*) W_read_second_binary_surf, REND); - Tcl_CreateCommand(interp, "read_second_binary_curv", - (Tcl_CmdProc*) W_read_second_binary_curv, REND); - Tcl_CreateCommand(interp, "normalize_second_binary_curv", - (Tcl_CmdProc*) W_normalize_second_binary_curv, REND); - Tcl_CreateCommand(interp, "curv_to_curvim", - (Tcl_CmdProc*) W_curv_to_curvim, REND); - Tcl_CreateCommand(interp, "second_surface_curv_to_curvim", - (Tcl_CmdProc*) W_second_surface_curv_to_curvim, REND); - Tcl_CreateCommand(interp, "curvim_to_second_surface", - (Tcl_CmdProc*) W_curvim_to_second_surface, REND); - Tcl_CreateCommand(interp, "swap_curv", - (Tcl_CmdProc*) W_swap_curv, REND); - Tcl_CreateCommand(interp, "curvim_to_surface", - (Tcl_CmdProc*) W_curvim_to_surface, REND); - Tcl_CreateCommand(interp, "read_binary_surf", - (Tcl_CmdProc*) W_read_binary_surf, REND); - Tcl_CreateCommand(interp, "read_surf", - (Tcl_CmdProc*) W_read_surf, REND); - Tcl_CreateCommand(interp, "save_surf", - (Tcl_CmdProc*) W_save_surf, REND); - Tcl_CreateCommand(interp, "store_surf", - (Tcl_CmdProc*) W_save_surf, REND); - Tcl_CreateCommand(interp, "restore_surf", - (Tcl_CmdProc*) W_restore_surf, REND); - Tcl_CreateCommand(interp, "surf", - (Tcl_CmdProc*) W_show_surf, REND); - Tcl_CreateCommand(interp, "read_binary_curv", - (Tcl_CmdProc*) W_read_binary_curv, REND); - Tcl_CreateCommand(interp, "read_binary_sulc", - (Tcl_CmdProc*) W_read_binary_sulc, REND); - Tcl_CreateCommand(interp, "read_binary_values", - (Tcl_CmdProc*) W_read_binary_values, REND); - Tcl_CreateCommand(interp, "read_binary_values_frame", - (Tcl_CmdProc*) W_read_binary_values_frame, REND); - Tcl_CreateCommand(interp, "read_annotated_image", - (Tcl_CmdProc*) W_read_annotated_image,REND); - Tcl_CreateCommand(interp, "read_annotations", - (Tcl_CmdProc*) W_read_annotations,REND); - Tcl_CreateCommand(interp, "read_binary_patch", - (Tcl_CmdProc*) W_read_binary_patch, REND); - Tcl_CreateCommand(interp, "read_fieldsign", - (Tcl_CmdProc*) W_read_fieldsign, REND); - Tcl_CreateCommand(interp, "read_fsmask", - (Tcl_CmdProc*) W_read_fsmask, REND); - Tcl_CreateCommand(interp, "write_binary_areas", - (Tcl_CmdProc*) W_write_binary_areas, REND); - Tcl_CreateCommand(interp, "write_binary_surface", - (Tcl_CmdProc*) W_write_binary_surface,REND); - Tcl_CreateCommand(interp, "write_binary_curv", - (Tcl_CmdProc*) W_write_binary_curv,REND); - Tcl_CreateCommand(interp, "write_binary_sulc", - (Tcl_CmdProc*) W_write_binary_sulc,REND); - Tcl_CreateCommand(interp, "write_binary_values", - (Tcl_CmdProc*) W_write_binary_values,REND); - Tcl_CreateCommand(interp, "write_binary_patch", - (Tcl_CmdProc*) W_write_binary_patch, REND); - Tcl_CreateCommand(interp, "write_labeled_vertices", - (Tcl_CmdProc*) W_write_labeled_vertices, REND); - Tcl_CreateCommand(interp, "read_labeled_vertices", - (Tcl_CmdProc*) W_read_labeled_vertices, REND); - Tcl_CreateCommand(interp, "read_and_color_labeled_vertices", - (Tcl_CmdProc*) W_read_and_color_labeled_vertices, REND); - Tcl_CreateCommand(interp, "write_fieldsign", - (Tcl_CmdProc*) W_write_fieldsign, REND); - Tcl_CreateCommand(interp, "write_fsmask", - (Tcl_CmdProc*) W_write_fsmask, REND); - Tcl_CreateCommand(interp, "write_vrml", - (Tcl_CmdProc*) W_write_vrml, REND); - Tcl_CreateCommand(interp, "write_binary_dipoles", - (Tcl_CmdProc*) W_write_binary_dipoles,REND); - Tcl_CreateCommand(interp, "write_binary_decimation", - (Tcl_CmdProc*) W_write_binary_decimation, REND); - Tcl_CreateCommand(interp, "write_dipoles", - (Tcl_CmdProc*) W_write_dipoles, REND); - Tcl_CreateCommand(interp, "write_decimation", - (Tcl_CmdProc*) W_write_decimation, REND); - Tcl_CreateCommand(interp, "write_curv_images", - (Tcl_CmdProc*) W_write_curv_images, REND); - Tcl_CreateCommand(interp, "write_fill_images", - (Tcl_CmdProc*) W_write_fill_images, REND); - Tcl_CreateCommand(interp, "fill_second_surface", - (Tcl_CmdProc*) W_fill_second_surface,REND); - Tcl_CreateCommand(interp, "subsample_dist", - (Tcl_CmdProc*) W_subsample_dist, REND); - Tcl_CreateCommand(interp, "subsample_orient", - (Tcl_CmdProc*) W_subsample_orient, REND); - Tcl_CreateCommand(interp, "write_subsample", - (Tcl_CmdProc*) W_write_subsample, REND); - Tcl_CreateCommand(interp, "compute_curvature", - (Tcl_CmdProc*) W_compute_curvature, REND); - Tcl_CreateCommand(interp, "compute_CMF", - (Tcl_CmdProc*) W_compute_CMF, REND); - Tcl_CreateCommand(interp, "compute_cortical_thickness", - (Tcl_CmdProc*) W_compute_cortical_thickness, REND); - Tcl_CreateCommand(interp, "clear_curvature", - (Tcl_CmdProc*) W_clear_curvature, REND); - Tcl_CreateCommand(interp, "clear_vals", - (Tcl_CmdProc*) W_clear_vals, REND); - Tcl_CreateCommand(interp, "clear_ripflags", - (Tcl_CmdProc*) W_clear_ripflags, REND); - Tcl_CreateCommand(interp, "restore_ripflags", - (Tcl_CmdProc*) W_restore_ripflags, REND); - Tcl_CreateCommand(interp, "floodfill_marked_patch", - (Tcl_CmdProc*) W_floodfill_marked_patch, REND); - Tcl_CreateCommand(interp, "rip_unmarked_vertices", - (Tcl_CmdProc*) W_rip_unmarked_vertices, REND); - Tcl_CreateCommand(interp, "dilate_ripped", - (Tcl_CmdProc*) W_dilate_ripped, REND); - Tcl_CreateCommand(interp, "twocond", - (Tcl_CmdProc*) W_twocond, REND); - Tcl_CreateCommand(interp, "cut_line", - (Tcl_CmdProc*) W_cut_line, REND); - Tcl_CreateCommand(interp, "plot_curv", - (Tcl_CmdProc*) W_plot_curv, REND); - Tcl_CreateCommand(interp, "draw_fundus", - (Tcl_CmdProc*) W_draw_fundus, REND); - Tcl_CreateCommand(interp, "plot_marked", - (Tcl_CmdProc*) W_plot_marked, REND); - Tcl_CreateCommand(interp, "put_retinotopy_stats_in_vals", - (Tcl_CmdProc*) W_put_retinotopy_stats_in_vals, REND); - Tcl_CreateCommand(interp, "draw_vector", - (Tcl_CmdProc*) W_draw_vector, REND); - Tcl_CreateCommand(interp, "cut_plane", - (Tcl_CmdProc*) W_cut_plane, REND); - Tcl_CreateCommand(interp, "flatten", - (Tcl_CmdProc*) W_flatten, REND); - Tcl_CreateCommand(interp, "normalize_binary_curv", - (Tcl_CmdProc*) W_normalize_binary_curv, REND); - Tcl_CreateCommand(interp, "normalize_area", - (Tcl_CmdProc*) W_normalize_area, REND); - Tcl_CreateCommand(interp, "normalize_curvature", - (Tcl_CmdProc*) W_normalize_curvature,REND); - Tcl_CreateCommand(interp, "shift_values", - (Tcl_CmdProc*) W_shift_values, REND); - Tcl_CreateCommand(interp, "swap_values", - (Tcl_CmdProc*) W_swap_values, REND); - Tcl_CreateCommand(interp, "swap_stat_val", - (Tcl_CmdProc*) W_swap_stat_val, REND); - Tcl_CreateCommand(interp, "swap_val_val2", - (Tcl_CmdProc*) W_swap_val_val2, REND); - Tcl_CreateCommand(interp, "compute_angles", - (Tcl_CmdProc*) W_compute_angles, REND); - Tcl_CreateCommand(interp, "compute_fieldsign", - (Tcl_CmdProc*) W_compute_fieldsign, REND); - Tcl_CreateCommand(interp, "draw_radius", - (Tcl_CmdProc*) W_draw_radius, REND); - Tcl_CreateCommand(interp, "draw_theta", - (Tcl_CmdProc*) W_draw_theta, REND); - Tcl_CreateCommand(interp, "save_rgb", - (Tcl_CmdProc*) W_save_rgb, REND); - Tcl_CreateCommand(interp, "save_rgb_named_orig", - (Tcl_CmdProc*) W_save_rgb_named_orig,REND); - Tcl_CreateCommand(interp, "save_rgb_cmp_frame", - (Tcl_CmdProc*) W_save_rgb_cmp_frame, REND); - Tcl_CreateCommand(interp, "open_rgb_cmp_named", - (Tcl_CmdProc*) W_open_rgb_cmp_named, REND); - Tcl_CreateCommand(interp, "save_rgb_cmp_frame_named", - (Tcl_CmdProc*) W_save_rgb_cmp_frame_named, REND); - Tcl_CreateCommand(interp, "close_rgb_cmp_named", - (Tcl_CmdProc*) W_close_rgb_cmp_named,REND); - Tcl_CreateCommand(interp, "rotate_brain_x", - (Tcl_CmdProc*) W_rotate_brain_x, REND); - Tcl_CreateCommand(interp, "rotate_brain_y", - (Tcl_CmdProc*) W_rotate_brain_y, REND); - Tcl_CreateCommand(interp, "rotate_brain_z", - (Tcl_CmdProc*) W_rotate_brain_z, REND); - Tcl_CreateCommand(interp, "translate_brain_x", - (Tcl_CmdProc*) W_translate_brain_x, REND); - Tcl_CreateCommand(interp, "translate_brain_y", - (Tcl_CmdProc*) W_translate_brain_y, REND); - Tcl_CreateCommand(interp, "translate_brain_z", - (Tcl_CmdProc*) W_translate_brain_z, REND); - Tcl_CreateCommand(interp, "scale_brain", - (Tcl_CmdProc*) W_scale_brain, REND); - Tcl_CreateCommand(interp, "resize_window", - (Tcl_CmdProc*) W_resize_window, REND); - Tcl_CreateCommand(interp, "setsize_window", - (Tcl_CmdProc*) W_setsize_window, REND); - Tcl_CreateCommand(interp, "move_window", - (Tcl_CmdProc*) W_move_window, REND); - Tcl_CreateCommand(interp, "do_lighting_model", - (Tcl_CmdProc*) W_do_lighting_model, REND); - Tcl_CreateCommand(interp, "restore_zero_position", - (Tcl_CmdProc*) W_restore_zero_position, REND); - Tcl_CreateCommand(interp, "restore_initial_position", - (Tcl_CmdProc*) W_restore_initial_position, REND); - Tcl_CreateCommand(interp, "make_lateral_view", - (Tcl_CmdProc*) W_make_lateral_view, REND); - Tcl_CreateCommand(interp, "make_lateral_view_second", - (Tcl_CmdProc*) W_make_lateral_view_second, REND); - Tcl_CreateCommand(interp, "read_view_matrix", - (Tcl_CmdProc*) W_read_view_matrix, REND); - Tcl_CreateCommand(interp, "write_view_matrix", - (Tcl_CmdProc*) W_write_view_matrix, REND); - Tcl_CreateCommand(interp, "read_really_matrix", - (Tcl_CmdProc*) W_read_really_matrix, REND); - Tcl_CreateCommand(interp, "write_really_matrix", - (Tcl_CmdProc*) W_write_really_matrix,REND); - Tcl_CreateCommand(interp, "really_translate_brain", - (Tcl_CmdProc*) W_really_translate_brain, REND); - Tcl_CreateCommand(interp, "really_scale_brain", - (Tcl_CmdProc*) W_really_scale_brain, REND); - Tcl_CreateCommand(interp, "align_sphere", - (Tcl_CmdProc*) W_align_sphere, REND); - Tcl_CreateCommand(interp, "really_rotate_brain_x", - (Tcl_CmdProc*) W_really_rotate_brain_x, REND); - Tcl_CreateCommand(interp, "really_rotate_brain_y", - (Tcl_CmdProc*) W_really_rotate_brain_y, REND); - Tcl_CreateCommand(interp, "really_rotate_brain_z", - (Tcl_CmdProc*) W_really_rotate_brain_z, REND); - Tcl_CreateCommand(interp, "really_center_brain", - (Tcl_CmdProc*) W_really_center_brain, REND); - Tcl_CreateCommand(interp, "really_center_second_brain", - (Tcl_CmdProc*) W_really_center_second_brain, REND); - Tcl_CreateCommand(interp, "really_align_brain", - (Tcl_CmdProc*) W_really_align_brain, REND); - Tcl_CreateCommand(interp, "read_binary_decimation", - (Tcl_CmdProc*) W_read_binary_decimation, REND); - Tcl_CreateCommand(interp, "read_binary_dipoles", - (Tcl_CmdProc*) W_read_binary_dipoles, REND); - Tcl_CreateCommand(interp, "load_vals_from_sol", - (Tcl_CmdProc*) W_load_vals_from_sol, REND); - Tcl_CreateCommand(interp, "load_var_from_sol", - (Tcl_CmdProc*) W_load_var_from_sol, REND); - Tcl_CreateCommand(interp, "compute_timecourses", - (Tcl_CmdProc*) W_compute_timecourses, REND); - Tcl_CreateCommand(interp, "filter_recs", - (Tcl_CmdProc*) W_filter_recs, REND); - Tcl_CreateCommand(interp, "read_rec", - (Tcl_CmdProc*) W_read_rec, REND); - Tcl_CreateCommand(interp, "read_iop", - (Tcl_CmdProc*) W_read_iop, REND); - Tcl_CreateCommand(interp, "read_ncov", - (Tcl_CmdProc*) W_read_ncov, REND); - Tcl_CreateCommand(interp, "normalize_time_courses", - (Tcl_CmdProc*) W_normalize_time_courses, REND); - Tcl_CreateCommand(interp, "compute_timecourses", - (Tcl_CmdProc*) W_compute_timecourses, REND); - Tcl_CreateCommand(interp, "compute_pval_fwd", - (Tcl_CmdProc*) W_compute_pval_fwd, REND); - Tcl_CreateCommand(interp, "compute_select_fwd", - (Tcl_CmdProc*) W_compute_select_fwd, REND); - Tcl_CreateCommand(interp, "compute_pval_inv", - (Tcl_CmdProc*) W_compute_pval_inv, REND); - Tcl_CreateCommand(interp, "normalize_inverse", - (Tcl_CmdProc*) W_normalize_inverse, REND); - Tcl_CreateCommand(interp, "find_orig_vertex_coordinates", - (Tcl_CmdProc*) W_find_orig_vertex_coordinates, REND); - Tcl_CreateCommand(interp, "select_orig_vertex_coordinates", - (Tcl_CmdProc*) W_select_orig_vertex_coordinates, REND); - Tcl_CreateCommand(interp, "select_talairach_point", - (Tcl_CmdProc*) W_select_talairach_point, REND); - Tcl_CreateCommand(interp, "print_nearest_vertex_to_talairach_point", - (Tcl_CmdProc*) W_print_nearest_vertex_to_talairach_point, REND); - Tcl_CreateCommand(interp, "read_white_vertex_coordinates", - (Tcl_CmdProc*) W_read_white_vertex_coordinates, REND); - Tcl_CreateCommand(interp, "read_pial_vertex_coordinates", - (Tcl_CmdProc*) W_read_pial_vertex_coordinates, REND); - Tcl_CreateCommand(interp, "read_orig_vertex_coordinates", - (Tcl_CmdProc*) W_read_orig_vertex_coordinates, REND); - Tcl_CreateCommand(interp, "read_canon_vertex_coordinates", - (Tcl_CmdProc*) W_read_canon_vertex_coordinates, REND); - Tcl_CreateCommand(interp, "send_spherical_point", - (Tcl_CmdProc*) W_send_spherical_point, REND); - Tcl_CreateCommand(interp, "send_contralateral_point", - (Tcl_CmdProc*) W_send_contralateral_point, REND); - Tcl_CreateCommand(interp, "send_to_subject", - (Tcl_CmdProc*) W_send_to_subject, REND); - Tcl_CreateCommand(interp, "send_to_other_hemi", - (Tcl_CmdProc*) W_send_to_other_hemi, REND); - Tcl_CreateCommand(interp, "resend_to_subject", - (Tcl_CmdProc*) W_resend_to_subject, REND); - Tcl_CreateCommand(interp, "drawcb", - (Tcl_CmdProc*) W_drawcb, REND); - Tcl_CreateCommand(interp, "read_ellipsoid_vertex_coordinates", - (Tcl_CmdProc*) W_read_ellipsoid_vertex_coordinates, REND); - Tcl_CreateCommand(interp, "invert_surface", - (Tcl_CmdProc*) W_invert_surface, REND); - Tcl_CreateCommand(interp, "fix_nonzero_vals", - (Tcl_CmdProc*) W_fix_nonzero_vals, REND); - Tcl_CreateCommand(interp, "invert_vertex", - (Tcl_CmdProc*) W_invert_vertex, REND); - Tcl_CreateCommand(interp, "invert_face", - (Tcl_CmdProc*) W_invert_face, REND); - Tcl_CreateCommand(interp, "mark_annotation", - (Tcl_CmdProc*) W_mark_annotation, REND); - Tcl_CreateCommand(interp, "mark_faces", - (Tcl_CmdProc*) W_mark_faces, REND); - Tcl_CreateCommand(interp, "mark_face", - (Tcl_CmdProc*) W_mark_face, REND); - Tcl_CreateCommand(interp, "dump_vertex", - (Tcl_CmdProc*) W_dump_vertex, REND); - Tcl_CreateCommand(interp, "val_to_mark", - (Tcl_CmdProc*) W_val_to_mark, REND); - Tcl_CreateCommand(interp, "set_area_thresh", - (Tcl_CmdProc*) W_set_area_thresh, REND); - Tcl_CreateCommand(interp, "resize_brain", - (Tcl_CmdProc*) W_resize_brain, REND); - Tcl_CreateCommand(interp, "transform_brain", - (Tcl_CmdProc*) W_transform_brain, REND); - Tcl_CreateCommand(interp, "show_flat_regions", - (Tcl_CmdProc*) W_show_flat_regions, REND); - Tcl_CreateCommand(interp, "val_to_stat", - (Tcl_CmdProc*) W_val_to_stat, REND); - Tcl_CreateCommand(interp, "set_vals", - (Tcl_CmdProc*) W_set_vals, REND); - Tcl_CreateCommand(interp, "stat_to_val", - (Tcl_CmdProc*) W_stat_to_val, REND); - Tcl_CreateCommand(interp, "scale_vals", - (Tcl_CmdProc*) W_scale_vals, REND); - Tcl_CreateCommand(interp, "read_soltimecourse", - (Tcl_CmdProc*) W_read_soltimecourse, REND); - Tcl_CreateCommand(interp, "read_imag_vals", - (Tcl_CmdProc*) W_read_imag_vals, REND); - Tcl_CreateCommand(interp, "sol_plot", - (Tcl_CmdProc*) W_sol_plot, REND); - Tcl_CreateCommand(interp, "remove_triangle_links", - (Tcl_CmdProc*) W_remove_triangle_links, REND); - Tcl_CreateCommand(interp, "f_to_t", - (Tcl_CmdProc*) W_f_to_t, REND); - Tcl_CreateCommand(interp, "label_to_stat", - (Tcl_CmdProc*) W_label_to_stat, REND); - Tcl_CreateCommand(interp, "taubin_smooth", - (Tcl_CmdProc*) W_taubin_smooth, REND); - - Tcl_CreateCommand(interp, "label_from_stats", - (Tcl_CmdProc*) W_label_from_stats, REND); - Tcl_CreateCommand(interp, "label_set_stats", - (Tcl_CmdProc*) W_label_set_stats, REND); - - Tcl_CreateCommand(interp, "t_to_p", - (Tcl_CmdProc*) W_t_to_p, REND); - Tcl_CreateCommand(interp, "f_to_p", - (Tcl_CmdProc*) W_f_to_p, REND); - Tcl_CreateCommand(interp, "val_to_curv", - (Tcl_CmdProc*) W_val_to_curv, REND); - Tcl_CreateCommand(interp, "curv_to_val", - (Tcl_CmdProc*) W_curv_to_val, REND); - Tcl_CreateCommand(interp, "read_curv_to_val", - (Tcl_CmdProc*) W_read_curv_to_val, REND); - Tcl_CreateCommand(interp, "read_and_smooth_parcellation", - (Tcl_CmdProc*) W_read_and_smooth_parcellation, REND); - Tcl_CreateCommand(interp, "read_parcellation", - (Tcl_CmdProc*) W_read_parcellation, REND); - Tcl_CreateCommand(interp, "deconvolve_weights", - (Tcl_CmdProc*) W_deconvolve_weights, REND); - Tcl_CreateCommand(interp, "read_disc", - (Tcl_CmdProc*) W_read_disc, REND); - Tcl_CreateCommand(interp, "mask_label", - (Tcl_CmdProc*) W_mask_label, REND); - Tcl_CreateCommand(interp, "orient_sphere", - (Tcl_CmdProc*) W_orient_sphere, REND); - Tcl_CreateCommand(interp, "dump_faces", - (Tcl_CmdProc*) W_dump_faces, REND); - Tcl_CreateCommand(interp, "load_gcsa", - (Tcl_CmdProc*) W_load_gcsa, REND); - Tcl_CreateCommand(interp, "draw_ellipsoid_latlong", - (Tcl_CmdProc*) W_draw_ellipsoid_latlong, REND); - Tcl_CreateCommand(interp, "left_click", - (Tcl_CmdProc*) W_left_click, REND); - Tcl_CreateCommand(interp, "plot_all_time_courses", - (Tcl_CmdProc*) W_plot_all_time_courses, REND); - Tcl_CreateCommand(interp, "read_plot_list", - (Tcl_CmdProc*) W_read_plot_list, REND); - Tcl_CreateCommand(interp, "read_vertex_list", - (Tcl_CmdProc*) W_read_vertex_list, REND); - Tcl_CreateCommand(interp, "draw_cursor", - (Tcl_CmdProc*) W_draw_cursor, REND); - Tcl_CreateCommand(interp, "draw_marked_vertices", - (Tcl_CmdProc*) W_draw_marked_vertices, REND); - Tcl_CreateCommand(interp, "mark_vertex", - (Tcl_CmdProc*) W_mark_vertex, REND); - Tcl_CreateCommand(interp, "mark_translated_vertex", - (Tcl_CmdProc*) W_mark_translated_vertex, REND); - Tcl_CreateCommand(interp, "draw_all_cursor", - (Tcl_CmdProc*) W_draw_all_cursor, REND); - Tcl_CreateCommand(interp, "draw_all_vertex_cursor", - (Tcl_CmdProc*) W_draw_all_vertex_cursor, REND); - Tcl_CreateCommand(interp, "clear_all_vertex_cursor", - (Tcl_CmdProc*) W_clear_all_vertex_cursor, REND); - /* begin rkt */ - Tcl_CreateCommand(interp, "send_current_labels", - (Tcl_CmdProc*) W_send_current_labels, REND); - - Tcl_CreateCommand(interp, "select_vertex_by_vno", - (Tcl_CmdProc*) W_select_vertex_by_vno, REND); - - Tcl_CreateCommand(interp, "swap_vertex_fields", - (Tcl_CmdProc*) W_swap_vertex_fields, REND); - - Tcl_CreateCommand(interp, "clear_vertex_marks", - (Tcl_CmdProc*) W_clear_vertex_marks, REND); - Tcl_CreateCommand(interp, "clear_all_vertex_marks", - (Tcl_CmdProc*) W_clear_all_vertex_marks, REND); - - Tcl_CreateCommand(interp, "close_marked_vertices", - (Tcl_CmdProc*) W_close_marked_vertices, REND); - - Tcl_CreateCommand(interp, "undo_last_action", - (Tcl_CmdProc*) W_undo_last_action, REND); - - Tcl_CreateCommand(interp, "sclv_read_from_dotw", - (Tcl_CmdProc*) W_sclv_read_from_dotw, REND); - Tcl_CreateCommand(interp, "sclv_read_binary_values", - (Tcl_CmdProc*) W_sclv_read_from_dotw, REND); - Tcl_CreateCommand(interp, "sclv_read_from_dotw_frame", - (Tcl_CmdProc*) W_sclv_read_from_dotw_frame, REND); - Tcl_CreateCommand(interp, "sclv_read_binary_values_frame", - (Tcl_CmdProc*) W_sclv_read_from_dotw_frame, REND); - Tcl_CreateCommand(interp, "sclv_read_from_volume", - (Tcl_CmdProc*) W_sclv_read_from_volume, REND); - Tcl_CreateCommand(interp, "sclv_read_bfile_values", - (Tcl_CmdProc*) W_sclv_read_from_volume, REND); - Tcl_CreateCommand(interp, "sclv_write_dotw", - (Tcl_CmdProc*) W_sclv_write_dotw, REND); - Tcl_CreateCommand(interp, "sclv_load_label_value_file", - (Tcl_CmdProc*) W_sclv_load_label_value_file, REND); - Tcl_CreateCommand(interp, "sclv_smooth", - (Tcl_CmdProc*) W_sclv_smooth, REND); - Tcl_CreateCommand(interp, "sclv_set_overlay_alpha", - (Tcl_CmdProc*) W_sclv_set_overlay_alpha, REND); - Tcl_CreateCommand(interp, "sclv_set_current_field", - (Tcl_CmdProc*) W_sclv_set_current_field, REND); - Tcl_CreateCommand(interp, "sclv_unload_field", - (Tcl_CmdProc*) W_sclv_unload_field, REND); - Tcl_CreateCommand(interp, "sclv_set_current_timepoint", - (Tcl_CmdProc*) W_sclv_set_current_timepoint, REND); - Tcl_CreateCommand(interp, "sclv_copy_view_settings_from_current_field", - (Tcl_CmdProc*) W_sclv_copy_view_settings_from_current_field, REND); - Tcl_CreateCommand(interp, "sclv_copy_all_view_settings_from_current_field", - (Tcl_CmdProc*) W_sclv_copy_all_view_settings_from_current_field, REND); - Tcl_CreateCommand(interp, "sclv_copy_view_settings_from_field", - (Tcl_CmdProc*) W_sclv_copy_view_settings_from_field, REND); - Tcl_CreateCommand(interp, "sclv_set_current_threshold_from_percentile", - (Tcl_CmdProc*) W_sclv_set_current_threshold_from_percentile, REND); - Tcl_CreateCommand(interp, "sclv_set_current_threshold_using_fdr", - (Tcl_CmdProc*) W_sclv_set_current_threshold_using_fdr, REND); - Tcl_CreateCommand(interp, "sclv_send_histogram", - (Tcl_CmdProc*) W_sclv_send_histogram, REND); - Tcl_CreateCommand(interp, "sclv_send_current_field_info", - (Tcl_CmdProc*) W_sclv_send_current_field_info, REND); - Tcl_CreateCommand(interp, "sclv_get_normalized_color_for_value", - (Tcl_CmdProc*) W_sclv_get_normalized_color_for_value, REND); - - Tcl_CreateCommand(interp, "read_surface_vertex_set", - (Tcl_CmdProc*) W_read_surface_vertex_set, REND); - Tcl_CreateCommand(interp, "set_current_vertex_set", - (Tcl_CmdProc*) W_set_current_vertex_set, REND); - - Tcl_CreateCommand(interp, "func_load_timecourse", - (Tcl_CmdProc*) W_func_load_timecourse, REND); - Tcl_CreateCommand(interp, "func_load_timecourse_offset", - (Tcl_CmdProc*) W_func_load_timecourse_offset, REND); - Tcl_CreateCommand(interp, "func_select_selected_vertex", - (Tcl_CmdProc*) W_func_select_selected_vertex, REND); - Tcl_CreateCommand(interp, "func_select_marked_vertices", - (Tcl_CmdProc*) W_func_select_marked_vertices, REND); - Tcl_CreateCommand(interp, "func_select_label", - (Tcl_CmdProc*) W_func_select_label, REND); - Tcl_CreateCommand(interp, "func_clear_selection", - (Tcl_CmdProc*) W_func_clear_selection, REND); - Tcl_CreateCommand(interp, "func_graph_timecourse_selection", - (Tcl_CmdProc*) W_func_graph_timecourse_selection, REND); - Tcl_CreateCommand(interp, "func_print_timecourse_selection", - (Tcl_CmdProc*) W_func_print_timecourse_selection, REND); - Tcl_CreateCommand(interp, "func_calc_correlation_and_write_to_overlay", - (Tcl_CmdProc*) W_func_calc_correlation_and_write_to_overlay, REND); - Tcl_CreateCommand(interp, "func_normalize", - (Tcl_CmdProc*) W_func_normalize, REND); - - Tcl_CreateCommand(interp, "labl_load_color_table", - (Tcl_CmdProc*) W_labl_load_color_table, REND); - Tcl_CreateCommand(interp, "labl_load", - (Tcl_CmdProc*) W_labl_load, REND); - Tcl_CreateCommand(interp, "labl_save", - (Tcl_CmdProc*) W_labl_save, REND); - Tcl_CreateCommand(interp, "labl_save_all", - (Tcl_CmdProc*) W_labl_save_all, REND); - Tcl_CreateCommand(interp, "labl_import_annotation", - (Tcl_CmdProc*) W_labl_import_annotation, REND); - Tcl_CreateCommand(interp, "labl_export_annotation", - (Tcl_CmdProc*) W_labl_export_annotation, REND); - Tcl_CreateCommand(interp, "labl_new_from_marked_vertices", - (Tcl_CmdProc*) W_labl_new_from_marked_vertices, REND); - Tcl_CreateCommand(interp, "labl_mark_vertices", - (Tcl_CmdProc*) W_labl_mark_vertices, REND); - Tcl_CreateCommand(interp, "labl_select", - (Tcl_CmdProc*) W_labl_select, REND); - Tcl_CreateCommand(interp, "labl_set_name_from_table", - (Tcl_CmdProc*) W_labl_set_name_from_table, REND); - Tcl_CreateCommand(interp, "labl_set_info", - (Tcl_CmdProc*) W_labl_set_info, REND); - Tcl_CreateCommand(interp, "labl_set_color", - (Tcl_CmdProc*) W_labl_set_color, REND); - Tcl_CreateCommand(interp, "labl_remove", - (Tcl_CmdProc*) W_labl_remove, REND); - Tcl_CreateCommand(interp, "labl_threshold", - (Tcl_CmdProc*) W_labl_threshold, REND); - Tcl_CreateCommand(interp, "labl_remove_all", - (Tcl_CmdProc*) W_labl_remove_all, REND); - Tcl_CreateCommand(interp, "labl_erode", - (Tcl_CmdProc*) W_labl_erode, REND); - Tcl_CreateCommand(interp, "labl_dilate", - (Tcl_CmdProc*) W_labl_dilate, REND); - Tcl_CreateCommand(interp, "labl_fill_holes", - (Tcl_CmdProc*) W_labl_fill_holes, REND); - Tcl_CreateCommand(interp, "labl_select_label_by_vno", - (Tcl_CmdProc*) W_labl_select_label_by_vno, REND); - Tcl_CreateCommand(interp, "labl_print_list", - (Tcl_CmdProc*) W_labl_print_list, REND); - Tcl_CreateCommand(interp, "labl_print_table", - (Tcl_CmdProc*) W_labl_print_table, REND); - - Tcl_CreateCommand(interp, "path_select", - (Tcl_CmdProc*) W_path_select, REND); - Tcl_CreateCommand(interp, "path_new_path_from_marked_vertices", - (Tcl_CmdProc*) W_path_new_path_from_marked_vertices, REND); - Tcl_CreateCommand(interp, "path_remove_selected_path", - (Tcl_CmdProc*) W_path_remove_selected_path, REND); - Tcl_CreateCommand(interp, "path_mark_selected_path", - (Tcl_CmdProc*) W_path_mark_selected_path, REND); - Tcl_CreateCommand(interp, "path_save", - (Tcl_CmdProc*) W_path_save, REND); - Tcl_CreateCommand(interp, "path_load", - (Tcl_CmdProc*) W_path_load, REND); - - Tcl_CreateCommand(interp, "fill_flood_from_cursor", - (Tcl_CmdProc*) W_fill_flood_from_cursor, REND); - - Tcl_CreateCommand(interp, "edit_vertex_at_cursor", - (Tcl_CmdProc*) W_edit_vertex_at_cursor, REND); - - Tcl_CreateCommand(interp, "draw_curvature_line", - (Tcl_CmdProc*) W_draw_curvature_line, REND); - - Tcl_CreateCommand(interp, "get_marked_vnos", - (Tcl_CmdProc*) W_get_marked_vnos, REND); - - Tcl_CreateCommand(interp, "get_selected_path_vnos", - (Tcl_CmdProc*) W_get_selected_path_vnos, REND); - - Tcl_CreateCommand(interp, "save_tiff", - (Tcl_CmdProc*) W_save_tiff, REND); - - Tcl_CreateCommand(interp, "flip_normals", - (Tcl_CmdProc*) W_flip_normals, REND); - - Tcl_CreateCommand(interp, "mark_contiguous_vertices_over_thresh", - (Tcl_CmdProc*) W_mark_contiguous_vertices_over_thresh, REND); - - Tcl_CreateCommand(interp, "mark_contiguous_vertices_with_similar_curvature", - (Tcl_CmdProc*) W_mark_contiguous_vertices_with_similar_curvature, REND); - - Tcl_CreateCommand(interp, "rip_all_vertices_except_contiguous_upripped", - (Tcl_CmdProc*) W_rip_all_vertices_except_contiguous_upripped, REND); - - Tcl_CreateCommand(interp, "cptn_set_format_string", - (Tcl_CmdProc*) W_cptn_set_format_string, REND); - - /* end rkt */ - /*=======================================================================*/ - /***** link global surfer BOOLEAN variables to tcl equivalents */ - Tcl_LinkVar(interp,"use_vertex_arrays", - (char *)&use_vertex_arrays, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"use_display_lists", - (char *)&use_display_lists, TCL_LINK_BOOLEAN); - - Tcl_LinkVar(interp,"dlat",(char *)&dlat, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"momentumflag",(char *)&momentumflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"expandflag",(char *)&expandflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"MRIflag",(char *)&MRIflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"sulcflag",(char *)&sulcflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"avgflag",(char *)&avgflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"areaflag",(char *)&areaflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"complexvalflag", - (char *)&complexvalflag,TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"statflag",(char *)&statflag,TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"overlayflag",(char *)&overlayflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"ncthreshflag",(char *)&ncthreshflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"verticesflag",(char *)&verticesflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"shearvecflag",(char *)&shearvecflag,TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"normvecflag",(char *)&normvecflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"movevecflag",(char *)&movevecflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"autoscaleflag",(char *)&autoscaleflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"revfsflag",(char *)&revfsflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"revphaseflag",(char *)&revphaseflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"invphaseflag",(char *)&invphaseflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"rectphaseflag",(char *)&rectphaseflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"truncphaseflag", - (char *)&truncphaseflag,TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"fieldsignflag",(char *)&fieldsignflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"flag2d",(char *)&flag2d, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"scalebarflag",(char *)&scalebarflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"colscalebarflag",(char *)&colscalebarflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"colscalebartextflag",(char *)&colscalebartextflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"colscalebartickflag",(char *)&colscalebartickflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"colscalebaruselabelsflag",(char *)&colscalebaruselabelsflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"colscalebarvertflag",(char *)&colscalebarvertflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"pointsflag",(char *)&pointsflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"surfaceflag",(char *)&surfaceflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"phasecontourflag",(char *)&phasecontourflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"curvimflag",(char *)&curvimflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"doublebufferflag",(char *)&doublebufferflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"surface_compiled",(char *)&surface_compiled, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"openglwindowflag",(char *)&openglwindowflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"blinkflag",(char *)&blinkflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"renderoffscreen",(char *)&renderoffscreen, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"transform_loaded",(char *)&transform_loaded, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"blackcursorflag",(char *)&blackcursorflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"bigcursorflag",(char *)&bigcursorflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"vrml2flag",(char *)&vrml2flag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"showorigcoordsflag",(char *)&showorigcoordsflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"phasecontourmodflag",(char *)&phasecontourmodflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"promptflag",(char *)&promptflag,TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"followglwinflag",(char *)&followglwinflag, - TCL_LINK_BOOLEAN); - /* begin rkt */ - Tcl_LinkVar(interp,"curvflag",(char *)&curvflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"mouseoverflag",(char *)&mouseoverflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"simpledrawmodeflag", - (char *)&simpledrawmodeflag, TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"redrawlockflag",(char *)&redrawlockflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"selectlabelflag",(char *)&labl_select_flag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"drawlabelflag",(char *)&labl_draw_flag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"forcegraycurvatureflag",(char *)&forcegraycurvatureflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"drawcursorflag",(char *)&drawcursorflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"ignorezeroesinhistogramflag", - (char *)&ignorezeroesinhistogramflag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"fopaqueflag",(char *)&sclv_opaque, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"labels_before_overlay_flag", - (char *)&labels_before_overlay_flag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"cptn_draw_flag",(char *)&cptn_draw_flag, - TCL_LINK_BOOLEAN); - Tcl_LinkVar(interp,"long_config_overlay",(char *)&long_config_overlay, - TCL_LINK_BOOLEAN); - /* end rkt */ - /*=======================================================================*/ - /***** link global surfer INT variables to tcl equivalents */ - Tcl_LinkVar(interp,"nperdip",(char *)&sol_nperdip, TCL_LINK_INT); - Tcl_LinkVar(interp,"numvertices",(char *)&numvertices, TCL_LINK_INT); - Tcl_LinkVar(interp,"scrsaveflag",(char *)&scrsaveflag, TCL_LINK_INT); - Tcl_LinkVar(interp,"surfcolor",(char *)&surfcolor, TCL_LINK_INT); - Tcl_LinkVar(interp,"mingm",(char *)&mingm, TCL_LINK_INT); - Tcl_LinkVar(interp,"colscale",(char *)&colscale, TCL_LINK_INT); - Tcl_LinkVar(interp,"ilat",(char *)&ilat, TCL_LINK_INT); - Tcl_LinkVar(interp,"mesh_linewidth",(char *)&mesh_linewidth, TCL_LINK_INT); - Tcl_LinkVar(interp,"meshr",(char *)&meshr, TCL_LINK_INT); - Tcl_LinkVar(interp,"meshg",(char *)&meshg, TCL_LINK_INT); - Tcl_LinkVar(interp,"meshb",(char *)&meshb, TCL_LINK_INT); - Tcl_LinkVar(interp,"scalebar_bright",(char *)&scalebar_bright, TCL_LINK_INT); - Tcl_LinkVar(interp,"project",(char *)&project, TCL_LINK_INT); - Tcl_LinkVar(interp,"sol_plot_type",(char *)&sol_plot_type, TCL_LINK_INT); - Tcl_LinkVar(interp,"phasecontour_bright",(char *)&phasecontour_bright, - TCL_LINK_INT); - Tcl_LinkVar(interp,"blinkdelay",(char *)&blinkdelay, TCL_LINK_INT); - Tcl_LinkVar(interp,"blinktime",(char *)&blinktime, TCL_LINK_INT); - Tcl_LinkVar(interp,"select",(char *)&selection, TCL_LINK_INT); - Tcl_LinkVar(interp,"linkvertexmode",(char *)&linkvertexmode, - TCL_LINK_INT); - - /* begin rkt */ - Tcl_LinkVar(interp,"vertexset",(char *)&vset_current_set, TCL_LINK_INT); - Tcl_LinkVar(interp,"numprestimpoints", - (char *)&func_num_prestim_points, TCL_LINK_INT); - Tcl_LinkVar(interp,"currentvaluefield",(char *)&sclv_current_field, - TCL_LINK_INT); - Tcl_LinkVar(interp,"ftimepoint",(char *)&sclv_cur_timepoint, TCL_LINK_INT); - Tcl_LinkVar(interp,"fcondition",(char *)&sclv_cur_condition, TCL_LINK_INT); - Tcl_LinkVar(interp,"fnumtimepoints", - (char *)&sclv_num_timepoints, TCL_LINK_INT); - Tcl_LinkVar(interp,"fnumconditions", - (char *)&sclv_num_conditions, TCL_LINK_INT); - Tcl_LinkVar(interp,"labelstyle",(char *)&labl_draw_style, TCL_LINK_INT); - Tcl_LinkVar(interp,"labeloutlinered", - (char *)&labl_outline_color[0], TCL_LINK_INT); - Tcl_LinkVar(interp,"labeloutlinegreen", - (char *)&labl_outline_color[1], TCL_LINK_INT); - Tcl_LinkVar(interp,"labeloutlineblue", - (char *)&labl_outline_color[2], TCL_LINK_INT); - Tcl_LinkVar(interp,"func_graph_avg_mode",(char *)&func_graph_avg_mode, - TCL_LINK_INT); - Tcl_LinkVar(interp,"colscalebar_font_size",(char *)&colscalebar_font_size, - TCL_LINK_INT); - /* end rkt */ - /*=======================================================================*/ - /***** link global surfer DOUBLE variables to tcl equivalents (were float) */ - Tcl_LinkVar(interp,"decay",(char *)&decay, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fthreshmax",(char *)&fthreshmax, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fthresh",(char *)&fthresh, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fslope",(char *)&fslope, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fcurv",(char *)&fcurv, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"foffset",(char *)&foffset, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fmid",(char *)&fmid, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"cslope",(char *)&cslope, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"cmid",(char *)&cmid, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"cmax",(char *)&cmax, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"cmin",(char *)&cmin, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"mslope",(char *)&mslope, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"mmid",(char *)&mmid, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"whitemid",(char *)&whitemid, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"graymid",(char *)&graymid, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"mstrength",(char *)&mstrength, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"stressthresh",(char *)&stressthresh, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"icstrength",(char *)&icstrength, TCL_LINK_DOUBLE); - /*Tcl_LinkVar(interp,"dipscale",(char *)&dipscale, TCL_LINK_DOUBLE);*/ - Tcl_LinkVar(interp,"angle_cycles",(char *)&angle_cycles, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"angle_offset",(char *)&angle_offset, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"wt",(char *)&wt, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"wa",(char *)&wa, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"ws",(char *)&ws, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"wn",(char *)&wn, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"wc",(char *)&wc, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"wsh",(char *)&wsh, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"wbn",(char *)&wbn, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"update",(char *)&update, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"decay",(char *)&decay, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"cthk",(char *)&cthk, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"light0",(char *)&light0_br, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"light1",(char *)&light1_br, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"light2",(char *)&light2_br, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"light3",(char *)&light3_br, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"offset",(char *)&offset, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"blufact",(char *)&blufact, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"cvfact",(char *)&cvfact, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fadef",(char *)&fadef, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"ncthresh",(char *)&ncthresh, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"dipavg",(char *)&dipavg, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"scalebar_xpos",(char *)&scalebar_xpos, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"scalebar_ypos",(char *)&scalebar_ypos, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"colscalebar_height",(char *)&colscalebar_height, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"colscalebar_width",(char *)&colscalebar_width, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"colscalebar_xpos",(char *)&colscalebar_xpos, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"colscalebar_ypos",(char *)&colscalebar_ypos, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_lat0",(char *)&sol_lat0,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_lat1",(char *)&sol_lat1,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_pthresh",(char *)&sol_pthresh,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_pslope",(char *)&sol_pslope,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_maxrat",(char *)&sol_maxrat,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_baseline_period",(char *)&sol_baseline_period, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_baseline_end",(char *)&sol_baseline_end, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_loflim",(char *)&sol_loflim,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_hiflim",(char *)&sol_hiflim,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"sol_snr_rms",(char *)&sol_snr_rms,TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"phasecontour_min",(char *)&phasecontour_min, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"phasecontour_max",(char *)&phasecontour_max, - TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"dip_spacing",(char *)&dip_spacing,TCL_LINK_DOUBLE); - - /* begin rkt */ - Tcl_LinkVar(interp,"timeresolution", - (char *)&func_time_resolution, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"falpha",(char *)&sclv_overlay_alpha, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fmin",(char *)&sclv_value_min, TCL_LINK_DOUBLE); - Tcl_LinkVar(interp,"fmax",(char *)&sclv_value_max, TCL_LINK_DOUBLE); - /* end rkt */ - - /*=======================================================================*/ - /***** link global malloc'ed STRING vars */ - Tcl_LinkVar(interp,"spherereg_contra", (char *)&sphere_reg_contra,TCL_LINK_STRING); - Tcl_LinkVar(interp,"spherereg", (char *)&sphere_reg,TCL_LINK_STRING); - Tcl_LinkVar(interp,"home", (char *)&subjectsdir,TCL_LINK_STRING); - Tcl_LinkVar(interp,"subject", (char *)&pname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"hemi", (char *)&stem,TCL_LINK_STRING); - Tcl_LinkVar(interp,"ext", (char *)&ext,TCL_LINK_STRING); - Tcl_LinkVar(interp,"curv", (char *)&cfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"sulc", (char *)&kfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"patch", (char *)&pfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"label", (char *)&lfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"fs", (char *)&fsfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"fm", (char *)&fmfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"dip", (char *)&dfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"dec", (char *)&sfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"num_rgbdir", (char *)&gfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"named_rgbdir",(char *)&sgfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"rgb", (char *)&agfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"insurf", (char *)&ifname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"outsurf", (char *)&ofname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"targsurf", (char *)&if2name,TCL_LINK_STRING); - Tcl_LinkVar(interp,"targcurv", (char *)&cf2name,TCL_LINK_STRING); - Tcl_LinkVar(interp,"targcurvim", (char *)&cif2name,TCL_LINK_STRING); - Tcl_LinkVar(interp,"val", (char *)&vfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"annot", (char *)&nfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"area", (char *)&afname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"session", (char *)&srname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"script", (char *)&rfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"origcoords", (char *)&orfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"paintcoords", (char *)&paint_fname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"ellcoords", (char *)&elfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"vrmlsurf", (char *)&vrfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"subjtmpdir", (char *)&tfname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"transform", (char *)&xffname,TCL_LINK_STRING); - Tcl_LinkVar(interp,"colscalebar_label1",(char *)&colscalebar_label[0], - TCL_LINK_STRING); - Tcl_LinkVar(interp,"colscalebar_label2",(char *)&colscalebar_label[1], - TCL_LINK_STRING); - Tcl_LinkVar(interp,"colscalebar_label3",(char *)&colscalebar_label[2], - TCL_LINK_STRING); - Tcl_LinkVar(interp,"colscalebar_label4",(char *)&colscalebar_label[3], - TCL_LINK_STRING); - - /* begin rkt */ - Tcl_LinkVar(interp,"colortablename", - (char *)&labl_color_table_name,TCL_LINK_STRING); - Tcl_LinkVar(interp,"captionformat", - (char *)&cptn_format_string,TCL_LINK_STRING); - /* end rkt */ - - /*=======================================================================*/ - - strcpy(rfname,script_tcl); /* save in global (malloc'ed in Surfer) */ - if (aliasflag) - { - sprintf(alias_tcl,"%s/lib/tcl/%s",envptr,argv[5]); - Tcl_SetVar(interp,"aliasedscript",alias_tcl,0); - } - - /* run tcl/tk startup script to set vars, make interface; no display yet */ - printf("surfer: using interface %s\n",tksurfer_tcl); - code = Tcl_EvalFile(g_interp, tksurfer_tcl); - if (code != TCL_OK) - printf("Error sourcing %s:\n\t%s\n", tksurfer_tcl, - Tcl_GetStringResult(interp)); - - /* begin rkt */ - - /* disable certain menu sets */ - enable_menu_set (MENUSET_VSET_INFLATED_LOADED, 0); - enable_menu_set (MENUSET_VSET_PIAL_LOADED, 0); - if (NULL == func_timecourse) - enable_menu_set (MENUSET_TIMECOURSE_LOADED, 0); - if (!overlayflag) - enable_menu_set (MENUSET_OVERLAY_LOADED, 0); - enable_menu_set (MENUSET_CURVATURE_LOADED, 0); - enable_menu_set (MENUSET_LABEL_LOADED, 0); - enable_menu_set (MENUSET_FIELDSIGN_LOADED, 0); - enable_menu_set (MENUSET_FIELDMASK_LOADED, 0); - - /* Now that we've sourced the interface file, send our cached - commands. */ - send_cached_tcl_commands (); - - /* Try to read the white coords. These are used to load labels. */ - read_white_vertex_coordinates(); - - /* end rkt */ - - /* Update all the linked var sets with our values here in case they - are different from the defaults set in tksurfer.tcl */ - sprintf (tcl_cmd, "UpdateLinkedVarGroup all"); - send_tcl_command (tcl_cmd); - - /* if command line script exists, now run as batch job (possibly exiting) */ - if (scriptok) - { /* script may or may not open gl window */ - printf("tksurfer: run tcl script: %s\n",script_tcl); - code = Tcl_EvalFile (g_interp, script_tcl); - if (code != TCL_OK) printf("%s",Tcl_GetStringResult(interp)); - } - else - { - ; /* surfer has already opened gl window if no script */ - } - - /* always start up command line shell too (if script doesn't exit) */ -#ifndef Windows_NT - Tk_CreateFileHandler(0, TK_READABLE, StdinProc, (ClientData) 0); -#endif - if (tty) Prompt(interp, 0); - fflush(stdout); - Tcl_DStringInit(&command); - Tcl_ResetResult(interp); - - /*Tk_MainLoop();*/ /* standard */ - - if (statflag) /* uggh rkt and brf */ - { - char cmd[STRLEN] ; - - statflag = 0 ; /* I'm really, really sorry */ - sclv_set_current_field(SCLV_VALSTAT) ; - sprintf (cmd, "ShowValueLabel %d 1", SCLV_VALSTAT); - send_tcl_command (cmd); - sprintf (cmd, "UpdateLinkedVarGroup view"); - send_tcl_command (cmd); - } - -#ifdef USE_XGLUT_WINDOW - glutMainLoop(); /* never returns */ -#else /* USE_XGLUT_WINDOW */ - /* dual event loop (interface window made now) */ - while (tk_NumMainWindows > 0) - { - while (Tk_DoOneEvent(TK_ALL_EVENTS|TK_DONT_WAIT)) - { - /* do all the tk events; non-blocking */ - } - do_one_gl_event(interp); - -#ifndef sgi - tv.tv_sec = 0; - tv.tv_usec = 10000; - select(0, NULL, NULL, NULL, &tv); -#else - sginap((long)1); /* block for 10 msec */ -#endif - } -#endif /* USE_XGLUT_WINDOW */ - - send_tcl_command("exit"); - exit(0); - return(0) ; /* for ansi */ -} - -#ifndef Windows_NT -/*=== from TkMain.c ===================================================*/ -static void StdinProc(clientData, mask) -ClientData clientData; -int mask; -{ -#define BUFFER_SIZE 4000 - char input[BUFFER_SIZE+1]; - static int gotPartial = 0; - char *cmd; - int code, count; - - count = read(fileno(stdin), input, BUFFER_SIZE); - if (count <= 0) - { - if (!gotPartial) - { - if (tty) - { - send_tcl_command("exit"); - exit(1); - } - else - { - Tk_DeleteFileHandler(0); - } - return; - } - else count = 0; - } - cmd = Tcl_DStringAppend(&command, input, count); - if (count != 0) - { - if ((input[count-1] != '\n') && (input[count-1] != ';')) - { - gotPartial = 1; - goto prompt; - } - if (!Tcl_CommandComplete(cmd)) - { - gotPartial = 1; - goto prompt; - } - } - gotPartial = 0; - Tk_CreateFileHandler(0, 0, StdinProc, (ClientData) 0); - code = Tcl_RecordAndEval (interp, cmd, TCL_EVAL_GLOBAL); - Tk_CreateFileHandler (0, TK_READABLE, StdinProc, (ClientData) 0); - Tcl_DStringFree(&command); - if (*interp->result != 0) - if ((code != TCL_OK) || (tty)) - puts(interp->result); -prompt: - if (tty) Prompt(interp, gotPartial); - Tcl_ResetResult(interp); -} -#endif // Windows_NT - -/*=== from TkMain.c ===================================================*/ -static void Prompt(interp, partial) -Tcl_Interp *interp; -int partial; -{ - char *promptCmd; - int code; - - promptCmd = - (char*)Tcl_GetVar(interp, - partial ? (char*)"tcl_prompt2" : (char*)"tcl_prompt1", - TCL_GLOBAL_ONLY); - if (promptCmd == NULL) - { -defaultPrompt: - if (!partial) - fputs("% ", stdout); - } - else - { - code = Tcl_Eval (g_interp, promptCmd); - if (code != TCL_OK) - { - Tcl_AddErrorInfo(interp, - "\n (script that generates prompt)"); - fprintf(stderr, "%s\n", Tcl_GetStringResult(interp)); - goto defaultPrompt; - } - } - fflush(stdout); -} - -static void -grabPixels(unsigned int width, unsigned int height, unsigned short *red, - unsigned short *green, unsigned short *blue) -{ - GLint swapbytes, lsbfirst, rowlength ; - GLint skiprows, skippixels, alignment ; - - glGetIntegerv(GL_UNPACK_SWAP_BYTES, &swapbytes) ; - glGetIntegerv(GL_UNPACK_LSB_FIRST, &lsbfirst) ; - glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rowlength) ; - glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skiprows) ; - glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skippixels) ; - glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment) ; - - glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE) ; - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) ; - glPixelStorei(GL_UNPACK_SKIP_ROWS, 0) ; - glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0) ; - glPixelStorei(GL_UNPACK_ALIGNMENT, 1) ; - - glReadPixels(0, 0, width, height,GL_RED,GL_UNSIGNED_SHORT, (GLvoid *)red); - glReadPixels(0, 0,width,height,GL_GREEN,GL_UNSIGNED_SHORT,(GLvoid *)green); - glReadPixels(0, 0, width, height,GL_BLUE,GL_UNSIGNED_SHORT,(GLvoid *)blue); - - glPixelStorei(GL_UNPACK_SWAP_BYTES, swapbytes) ; - glPixelStorei(GL_UNPACK_LSB_FIRST, lsbfirst) ; - glPixelStorei(GL_UNPACK_ROW_LENGTH, rowlength) ; - glPixelStorei(GL_UNPACK_SKIP_ROWS, skiprows) ; - glPixelStorei(GL_UNPACK_SKIP_PIXELS, skippixels) ; - glPixelStorei(GL_UNPACK_ALIGNMENT, alignment) ; -} -static void -save_rgbfile(char *fname, int width, int height, unsigned short *red, - unsigned short *green, unsigned short *blue) -{ - RGB_IMAGE *image ; - int y ; - unsigned short *r, *g, *b ; - -#ifdef IRIX - image = iopen(fname,"w",RLE(1), 3, width, height, 3); -#else - image = iopen(fname,"w",UNCOMPRESSED(1), 3, width, height, 3); -#endif - if (!image) - return ; - for (y = 0 ; y < height; y++) - { - r = red + y * width ; - g = green + y * width ; - b = blue + y * width ; - - /* fill rbuf, gbuf, and bbuf with pixel values */ - putrow(image, r, y, 0); /* red row */ - putrow(image, g, y, 1); /* green row */ - putrow(image, b, y, 2); /* blue row */ - } - iclose(image); -} - -void -fix_nonzero_vals(void) -{ - int vno ; - VERTEX *v ; - - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - if (!FZERO(v->val)) - v->fixedval = TRUE ; - else - v->fixedval = FALSE ; - } -} - -void -curv_to_val(void) -{ - int vno ; - VERTEX *v ; - char label[1024]; - double min, max; - - /* Initialize our field. */ - strncpy (label, "From curv", sizeof(label)); - sclv_new_empty (SCLV_VAL, label); - - /* Copy the data in. */ - min = 1000000000; - max = -min; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - sclv_set_value (v, SCLV_VAL, v->curv); - - /* Update the min and max. */ - if (v->curv < min) - min = v->curv; - if (v->curv > max) - max = v->curv; - } - - /* Set the min and max. */ - sclv_field_info[SCLV_VAL].min_value = min; - sclv_field_info[SCLV_VAL].max_value = max; - - /* Calc the frquencies */ - sclv_calc_frequencies (SCLV_VAL); - - /* Request a redraw. Turn on the overlay flag and select this value - set. */ - vertex_array_dirty = 1 ; - overlayflag = TRUE; - sclv_set_current_field (SCLV_VAL); -} -void -scale_vals(float scale) -{ - int vno ; - VERTEX *v ; - float min, max ; - - min = 1e10 ; max = -min ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - sclv_get_value (v, SCLV_VAL, &(v->val)); - v->val *= scale ; - sclv_set_value (v, SCLV_VAL, v->val); - - /* Update the min and max. */ - if (v->val < min) - min = v->val; - if (v->val > max) - max = v->val; - } - - /* Set the min and max. */ - sclv_field_info[SCLV_VAL].min_value = min; - sclv_field_info[SCLV_VAL].max_value = max; - - /* Calc the frquencies */ - sclv_calc_frequencies (SCLV_VAL); - - /* Request a redraw. Turn on the overlay flag and select this value - set. */ - vertex_array_dirty = 1 ; - overlayflag = TRUE; - sclv_set_current_field (SCLV_VAL); -} -int -read_parcellation(char *parc_name, char *lut_name) -{ - return(read_and_smooth_parcellation(parc_name, lut_name, 25, 25)) ; -} -int -read_and_smooth_parcellation(char *parc_name, char *lut_name, - int siter, int miter) -{ - char *cp, fname[STRLEN], path[STRLEN], name[STRLEN] ; - MRI *mri ; - int vno, index, rd, gn, bl, xv, yv, zv ; - FILE *fp ; - char r[256], g[256], b[256], line[STRLEN] ; - VERTEX *v ; - double x, y, z ; - - MRISclearMarks(mris) ; - cp = strchr(parc_name, '/') ; - if (!cp) /* no path - use same one as mris was read from */ - { - FileNamePath(mris->fname, path) ; - sprintf(fname, "%s/../mri/%s", path, parc_name) ; - } else - strcpy(fname, parc_name) ; /* path specified explcitly */ - fprintf(stderr, "reading parcellation from %s...\n", fname) ; - mri = MRIread(fname) ; - if (!mri) - { - fprintf(stderr, "### could not read parcellation file %s\n", fname) ; - return(Gerror) ; - } - - cp = strchr(lut_name, '/') ; - if (!cp) /* no path - use same one as mris was read from */ - { - FileNamePath(mris->fname, path) ; - sprintf(fname, "%s/../label/%s", path, lut_name) ; - } else - strcpy(fname, lut_name) ; /* path specified explcitly */ - - fprintf(stderr, "reading color lut from %s...\n", fname) ; - fp = fopen(fname, "r") ; - if (!fp) - { - fprintf(stderr, "### could not read parcellation lut from %s\n", fname) ; - return(Gerror) ; - } - - - while ((cp = fgetl(line, 199, fp)) != NULL) - { - sscanf(cp, "%d %s %d %d %d %*s\n", &index, name, &rd, &gn, &bl) ; - r[index] = (char)rd ; - g[index] = (char)gn ; - b[index] = (char)bl ; - parc_names[index] = (char *)calloc(strlen(name)+1, sizeof(char)) ; - strcpy(parc_names[index], name) ; - parc_red[index] = (char)rd ; - parc_green[index] = (char)gn ; - parc_blue[index] = (char)bl ; - parc_flag = 1 ; - } - fclose(fp) ; - - MRISsaveVertexPositions(mris, TMP_VERTICES) ; - read_orig_vertex_coordinates("pial") ; - MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ; - fprintf(stderr, "painting parcellation onto surface...\n") ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - MRISvertexToVoxel(mris,v, mri, &x, &y, &z) ; - xv = nint(x) ; - yv = nint(y) ; - zv = nint(z) ; - xv = MAX(0,xv) ; - yv = MAX(0,yv) ; - zv = MAX(0,zv) ; - xv = MIN(mri->width-1, xv) ; - yv = MIN(mri->height-1, yv) ; - zv = MIN(mri->depth-1, zv) ; - index = MRIvox(mri, xv, yv, zv) ; - if (index < 1) - continue ; - v->marked = 1 ; - v->val = (float)index ; - rd = r[index] ; - gn = g[index] ; - bl = b[index] ; - v->annotation = rd + (gn << 8) + (bl << 16) ; - } - - MRISsoapBubbleVals(mris, siter) ; - fprintf(stderr, "applying mode filter...\n") ; - MRISmodeFilterVals(mris, miter) ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - index = nint(v->val) ; - rd = r[index] ; - gn = g[index] ; - bl = b[index] ; - v->annotation = rd + (gn << 8) + (bl << 16) ; - } - MRISrestoreVertexPositions(mris, TMP_VERTICES) ; - - PR ; - annotationloaded = TRUE ; - MRIfree(&mri) ; - MRISclearMarks(mris) ; - return(NO_ERROR) ; -} -int -read_curv_to_val(char *fname) -{ - int vno ; - VERTEX *v ; - - enable_menu_set (MENUSET_OVERLAY_LOADED, 1); - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - v->tx = v->curv ; - } - surface_compiled = 0 ; - if (MRISreadCurvatureFile(mris, fname) != NO_ERROR) - return(Gerror) ; - - printf("surfer: values read: min=%f max=%f\n", - mris->min_curv,mris->max_curv); - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - v->val = v->curv ; - v->curv = v->tx ; - } - return(NO_ERROR) ; -} - -void -val_to_curv(void) -{ - int vno ; - VERTEX *v ; - - enable_menu_set (MENUSET_OVERLAY_LOADED, 1); - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - v->curv = v->val ; - } -} - -void -val_to_stat(void) -{ - int vno ; - VERTEX *v ; - - enable_menu_set (MENUSET_OVERLAY_LOADED, 1); - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - v->stat = v->val ; - } -} - -void -stat_to_val(void) -{ - int vno ; - VERTEX *v ; - - enable_menu_set (MENUSET_OVERLAY_LOADED, 1); - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - v->val = v->stat ; - } -} - -void -show_flat_regions(char *surf_name, double thresh) -{ - int vno, nfound = 0 ; - VERTEX *v ; - float mx ; - - MRISsaveVertexPositions(mris, TMP_VERTICES) ; - if (MRISreadVertexPositions(mris, surf_name) != NO_ERROR) - { - ErrorPrintf(ERROR_NOFILE, - "show_flat_regions(%s): could not read surface", - surf_name) ; - return ; - } - - MRIScomputeMetricProperties(mris) ; /* compute normals */ - - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - mx = MAX(MAX(fabs(v->nx), fabs(v->ny)), fabs(v->nz)) ; - if (mx > thresh) - { - nfound++ ; - v->val = mx ; - } - else - v->val = 0 ; - } - MRISrestoreVertexPositions(mris, TMP_VERTICES) ; - MRIScomputeMetricProperties(mris) ; - printf("%d vertices marked...\n", nfound) ; - enable_menu_set (MENUSET_OVERLAY_LOADED, 1); -} - -static void -resize_brain(float surface_area) -{ - float scale ; - - MRIScomputeMetricProperties(mris) ; - scale = sqrt(surface_area / mris->total_area) ; - MRISscaleBrain(mris, mris, scale) ; - MRIScomputeMetricProperties(mris) ; - vset_save_surface_vertices(VSET_MAIN) ; - vset_set_current_set(vset_current_set) ; - redraw() ; -} - -void -val_to_mark(void) -{ - int vno ; - VERTEX *v ; - static int mark = 2 ; - - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - if (fabs(v->val) > fthresh && v->marked < 2) - v->marked = mark ; - } - mark++ ; -} - -void -twocond(int c0, int c1) -{ - char fname[STRLEN], val_name[STRLEN], *cp ; - int dof ; - FILE *fp ; - - cond0 = c0 ; - cond1 = c1 ; - - /* put the averages in val and val2, and the variances in valbak, val2bak */ - twocond_flag = 1 ; - sprintf(fname, "%s/sigavg%d-%s.w", val_dir, c1, stem) ; - fprintf(stderr, "reading cond %d means from %s\n", c1, fname) ; - surface_compiled = 0 ; - MRISreadValues(mris, fname) ; - MRIScopyValToVal2(mris) ; - - sprintf(fname, "%s/sigavg%d.dof", val_dir, c1) ; - fp = fopen(fname, "r") ; - if (!fp) - { - printf("### surfer: could not open dof file %s\n", fname) ; - return ; - } - fscanf(fp, "%d", &dof) ; - fclose(fp) ; - sprintf(fname, "%s/sigvar%d-%s.w", val_dir, c1, stem) ; - fprintf(stderr, "reading cond %d variances from %s and scaling by %d\n", - c1, fname, dof) ; - MRISreadValues(mris, fname) ; - /* turn squared standard errors into variances */ - MRISmulVal(mris, (float)dof) ; - MRISsqrtVal(mris) ; - MRIScopyValToVal2Bak(mris) ; - - sprintf(fname, "%s/sigavg%d.dof", val_dir, c0) ; - fp = fopen(fname, "r") ; - if (!fp) - { - printf("### surfer: could not open dof file %s\n", fname) ; - return ; - } - fscanf(fp, "%d", &dof) ; - fclose(fp) ; - sprintf(fname, "%s/sigvar%d-%s.w", val_dir, c0, stem) ; - fprintf(stderr, "reading cond %d variances from %s and scaling by %d\n", - c0, fname,dof) ; - MRISreadValues(mris, fname) ; - /* turn squared standard errors into variances */ - MRISmulVal(mris, (float)dof) ; - MRISsqrtVal(mris) ; - MRIScopyValToValBak(mris) ; - - sprintf(fname, "%s/sigavg%d-%s.w", val_dir, c0, stem) ; - fprintf(stderr, "reading condition %d means from %s\n", - c0, fname) ; - MRISreadValues(mris, fname) ; - sprintf(val_name, "GROUP%d", c0) ; - cp = getenv(val_name) ; - if (cp) - sprintf(val_name, "%s mean", cp) ; - else - sprintf(val_name, "group %d mean", c0) ; - set_value_label_name(val_name, SCLV_VAL) ; - if (cp) - sprintf(val_name, "%s std", cp) ; - else - sprintf(val_name, "group %d std", c0) ; - set_value_label_name(val_name, SCLV_VALBAK) ; - sprintf(val_name, "GROUP%d", c1) ; - cp = getenv(val_name) ; - if (cp) - sprintf(val_name, "%s mean", cp) ; - else - sprintf(val_name, "group %d mean", c1) ; - set_value_label_name(val_name, SCLV_VAL2) ; - if (cp) - sprintf(val_name, "%s std", cp) ; - else - sprintf(val_name, "group %d std", c1) ; - set_value_label_name(val_name, SCLV_VAL2BAK) ; -} - -int -mask_label(char *label_name) -{ - LABEL *area ; - int vno ; - VERTEX *v ; - - surface_compiled = 0 ; - MRISclearMarks(mris) ; - area = LabelRead(pname, label_name) ; - if (!area) - { - fprintf(stderr, "unable to read label file %s\n", label_name) ; - return(NO_ERROR) ; - } - - LabelMarkSurface(area, mris) ; /* mark all points in label */ - - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->marked || v->ripflag) - continue ; - v->stat = v->val = v->imag_val = v->val2 = v->valbak = v->val2bak = 0.0 ; - } - LabelFree(&area) ; - MRISclearMarks(mris) ; - redraw() ; - return(NO_ERROR) ; -} - -#include "mrishash.h" -static void -deconvolve_weights(char *weight_fname, char *scale_fname) -{ - MHT *mht ; - MHBT *bucket ; - MHB *bin ; - int vno, n, i ; - VERTEX *v, *vn ; - double angle, circumference, norm, sigma_sq, wt, mean, var, mn, mx, - sphere_area ; - float radius, dist, sigma, x0, y0, z0, dscale, dx, dy, dz ; - VECTOR *v1, *v2 ; - - - surface_compiled = 0 ; - if (is_val_file(weight_fname)) - { - if (MRISreadValues(mris,weight_fname) != NO_ERROR) - return ; - } - else if (read_curv_to_val(weight_fname) != NO_ERROR) - return ; - - fprintf(stderr, "loading spherical coordinate system...\n") ; - if (read_canon_vertex_coordinates("sphere") != NO_ERROR) - return ; - - MRISsaveVertexPositions(mris, TMP_VERTICES) ; - MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ; - radius = MRISaverageRadius(mris) ; - sphere_area = M_PI * radius * radius * 4.0 ; - dscale = sqrt(mris->total_area / sphere_area) ; - circumference = M_PI * 2.0 * radius ; - v1 = VectorAlloc(3, MATRIX_REAL) ; - v2 = VectorAlloc(3, MATRIX_REAL) ; - MRISrestoreVertexPositions(mris, TMP_VERTICES) ; - fprintf(stderr, "average radius = %2.1f\n", radius) ; - - MRIScopyValToVal2(mris) ; /* put weights in val2 field */ - if (MRISreadValues(mris, scale_fname) != NO_ERROR) - { - fprintf(stderr, - "### surfer: could not open scale file %s\n",scale_fname); - PR ; - return ; - } - MRIScopyValToVal2Bak(mris) ; /* put spatial scale in val2bak field */ - -#define MAX_DIST (1.0*sqrt(500)) - - fprintf(stderr, "building spatial LUT...\n") ; - mht = MHTcreateVertexTable_Resolution(mris, CANONICAL_VERTICES, MAX_DIST) ; - - fprintf(stderr, "deconvolving weights...\n") ; - MRISsetVals(mris, 0.0) ; /* clear all values */ - - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - v->tdx = 0 ; /* used for normalization below */ - } - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - if (!(vno % (mris->nvertices/50))) - fprintf(stderr, ".") ; - v = &mris->vertices[vno] ; - if (vno == Gdiag_no) - DiagBreak() ; - if (v->ripflag || (fabs(v->val2) < fthresh)) - continue ; - - x0 = v->cx ; - y0 = v->cy ; - z0 = v->cz ; - sigma = sqrt(v->val2bak) ; - if (FZERO(sigma)) - norm = 1.0 ; - else - norm = 1.0 / (sigma * sqrt(2.0*M_PI)) ; - sigma_sq = sigma*sigma ; - MRISclearMarks(mris) ; - - VECTOR_LOAD(v1, x0, y0, z0) ; /* radius vector */ - - for (dx = -MAX_DIST ; dx <= MAX_DIST ; dx += MAX_DIST) - for (dy = -MAX_DIST ; dy <= MAX_DIST ; dy += MAX_DIST) - for (dz = -MAX_DIST ; dz <= MAX_DIST ; dz += MAX_DIST) - { - x0 = v->cx + dx ; - y0 = v->cy + dy ; - z0 = v->cz + dz ; - - bucket = MHTacqBucket(mht, x0, y0, z0) ; - if (!bucket) - continue ; - for (bin = bucket->bins, i = 0 ; i < bucket->nused ; i++, bin++) - { - n = bin->fno ; - vn = &mris->vertices[n] ; - if (vn->marked) - continue ; - if (n == Gdiag_no) - DiagBreak() ; - vn->marked = 1 ; /* only process it once */ - VECTOR_LOAD(v2, vn->cx, vn->cy, vn->cz) ; - /* radius vector */ - angle = fabs(Vector3Angle(v1, v2)) ; - dist = dscale * circumference * angle / (2.0 * M_PI) ; - if (dist > 3*sigma) - continue ; - if (n == Gdiag_no) - DiagBreak() ; - if (FZERO(sigma_sq)) /* make it a unit delta function */ - { - if (FZERO(dist)) - wt = norm ; - else - wt = 0.0 ; - } else - wt = norm*exp(-0.5 * dist*dist / sigma_sq) ; -#if 0 - if (wt < fthresh/10) - continue ; -#endif - if (n == Gdiag_no) - DiagBreak() ; - vn->val += v->val2*wt ; - vn->tdx += wt ; /* for normalization later */ - if (!finite(vn->val)) - DiagBreak() ; - } - MHTrelBucket(&bucket); - } - } - fprintf(stderr, "\n") ; - - mean = var = mn = mx = 0.0f ; - for (i = vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (vno == Gdiag_no) - DiagBreak() ; - if (!FZERO(v->tdx)) - { - i++ ; - v->val /= v->tdx ; - v->tdx = 0 ; - if (v->val < mn) - mn = v->val ; - if (v->val > mx) - mx = v->val ; - mean += v->val ; - var += v->val * v->val ; - } - } - - if (i) - { - mean /= (double)i ; - var = var / i - mean*mean ; - fprintf(stderr, "%d non-zero vals, [%2.2f --> %2.2f], %2.2f += %2.2f\n", - i, mn, mx, mean, sqrt(var)) ; - } - overlayflag = TRUE ; - colscale = HEAT_SCALE ; - val_to_stat() ; - complexvalflag = FALSE ; - - MRISclearMarks(mris) ; - VectorFree(&v1) ; - VectorFree(&v2) ; - MHTfree(&mht) ; - redraw() ; -} - -static void -read_disc(char *subject_name) -{ - char fname[300] ; - int vno ; - VERTEX *v ; - double proj ; - - surface_compiled = 0 ; - sprintf(fname, "./%s.offset_%s", stem, subject_name) ; - if (read_curv_to_val(fname) != NO_ERROR) - { - fprintf(stderr, "### surfer: could not open %s\n", fname) ; - return ; - } - shift_values() ; - sprintf(fname, "./%s.mdiff", stem) ; - if (read_curv_to_val(fname) != NO_ERROR) - { - fprintf(stderr, "### surfer: could not open %s\n", fname) ; - return ; - } - - swap_values() ; /* mdiff ->valbak, offset ->val2bak */ - - sprintf(fname, "control_thickness/%s.thickness_%s", stem, subject_name) ; - if (read_curv_to_val(fname) != NO_ERROR) - { - fprintf(stderr, "### surfer: could not open %s\n", fname) ; - return ; - } - shift_values() ; /* thickness -> val2 */ - sprintf(fname, "./%s.disc_%s", stem, subject_name) ; /* disc -> val */ - if (read_curv_to_val(fname) != NO_ERROR) - { - fprintf(stderr, "### surfer: could not open %s\n", fname) ; - return ; - } - - MRIScopyValuesToImagValues(mris) ; /* disc -> imag_val */ - - /* - valbak - difference between means - val2bak - offset (mean of two groups) - val2 - thickness of individual - imag_val - discriminant weight for subject - val - projection of mean difference onto discriminant - */ - - disc_flag = 1 ; - mask_label("lh-cortex") ; - for (proj = 0.0, vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - v->val = (v->val2 - v->val2bak) * v->imag_val ; - proj += (double)v->val ; - } - printf("projection onto discriminant: %2.3f\n", proj) ; - PR -} - -/* begin rkt */ - -static void -print_vertex_data(int vno, FILE *fp, float dmin) -{ - VERTEX *v ; - int i, j, imnr ; - - v = &mris->vertices[vno] ; - if(twocond_flag){ - if (!FZERO(v->imag_val)) - fprintf(fp, "cond %d: %2.3f +- %2.3f, cond %d: %2.3f +- %2.3f, " - "scale=%2.0f\n", - cond0, v->val, v->valbak, cond1, v->val2, v->val2bak, - v->imag_val); - else - fprintf(fp, "cond %d: %2.3f +- %2.3f, cond %d: %2.3f +- %2.3f\n", - cond0, v->val, v->valbak, cond1, v->val2, v->val2bak); - PR; - } - else if (disc_flag){ - fprintf(fp, "v %d:\n\tdisc:\t\t%2.3f\n\tmdiff:" - "\t\t%2.3f\n\tthickness:\t%2.3f\n\toffset:\t\t%2.3f\n" - "\tdiff:\t\t%2.3f\n\tproj:\t\t%2.3f\n", - vno, v->imag_val, v->valbak, v->val2, v->val2bak, - v->val2-v->val2bak, v->val); - PR; - } - else - { - fprintf(fp, "-----------------------------------\n"); - fprintf(fp, "selected vertex %d out of %d\n",vno,mris->nvertices); - fprintf(fp, "current %6.2f %6.2f %6.2f\n",v->x,v->y,v->z); - fprintf(fp, "orig %6.2f %6.2f %6.2f\n",v->origx,v->origy,v->origz); - fprintf(fp, "pial %6.2f %6.2f %6.2f\n",v->pialx,v->pialy,v->pialz); - fprintf(fp, "white %6.2f %6.2f %6.2f\n",v->whitex,v->whitey,v->whitez); - fprintf(fp, "inflated %6.2f %6.2f %6.2f\n",v->infx,v->infy,v->infz); - fprintf(fp, "flat %6.2f %6.2f %6.2f\n",v->fx,v->fy,v->fz); - fprintf(fp, "normals %6.2f %6.2f %6.2f\n",v->nx,v->ny,v->nz); - fprintf(fp, "nneighbors %d\n",v->vtotal); - fprintf(fp, "ripflag %d\n",v->ripflag); - fprintf(fp, "surfer: dmin=%3.4f, vno=%d, x=%3.4f, y=%3.4f, z=%3.4f\n", - dmin,vno,v->x, v->y, v->z); - fprintf(fp, "surfer: curv=%f, fs=%f\n",v->curv,v->fieldsign); - fprintf(fp, "surfer: val=%f, val2=%f\n",v->val,v->val2); - fprintf(fp, "surfer: amp=%f, angle=%f deg (%f)\n",hypot(v->val,v->val2), - (float)(atan2(v->val2,v->val)*180/M_PI), - (float)(atan2(v->val2,v->val)/(2*M_PI))); - } - if (annotationloaded) - { - int r, g, b ; - r = v->annotation & 0x00ff ; - g = (v->annotation >> 8) & 0x00ff ; - b = (v->annotation >> 16) & 0x00ff ; - fprintf(fp, "annot = %d (%d, %d, %d)\n", v->annotation, r, g, b) ; - } - if (MRIflag && MRIloaded) - { - imnr = (int)((v->y-yy0)/st+0.5); - i = (int)((zz1-v->z)/ps+0.5); - j = (int)((xx1-v->x)/ps+0.5); - fprintf(fp, "surfer: mrival=%d imnr=%d, i=%d, j=%d\n", - im[imnr][i][j],imnr,i,j); - PR; - } - if (parc_flag && v->val > 0 && parc_names[(int)nint(v->val)]) - fprintf(stderr, "parcellation name: %s\n", parc_names[(int)nint(v->val)]) ; - if (Ggcsa != NULL) - { - VERTEX *v_classifier, *v_prior ; - int vno_classifier, vno_prior ; - GCSA_NODE *gcsan ; - CP_NODE *cpn ; - float x, y, z ; - - v = &mris->vertices[vno] ; - x = v->x ; - y = v->y ; - z = v->z ; - v->x = v->cx ; - v->y = v->cy ; - v->z = v->cz ; - v_prior = GCSAsourceToPriorVertex(Ggcsa, v) ; - v_classifier = GCSAsourceToClassifierVertex(Ggcsa, v_prior) ; - vno_classifier = v_classifier - Ggcsa->mris_classifiers->vertices ; - vno_prior = v_prior - Ggcsa->mris_priors->vertices ; - gcsan = &Ggcsa->gc_nodes[vno_classifier] ; - cpn = &Ggcsa->cp_nodes[vno_prior] ; - dump_gcsan(gcsan, cpn, stdout, 0) ; - v->x = x ; - v->y = y ; - v->z = z ; - } -} - -static void -send_current_labels() -{ - /* We've cached the current vnos of the cursor and mouseover, so - just send those. */ - update_labels (LABELSET_MOUSEOVER, mouseover_vno, 0); - update_labels (LABELSET_CURSOR, selection, 0); -} - -static void -update_labels(int label_set, int vno, float dmin) -{ - int err; - char command[NAME_LENGTH]; - VERTEX *v; - int i, j, imnr; - int r, g, b; - float x_mni, y_mni, z_mni; - float x_tal, y_tal, z_tal; - char fname[NAME_LENGTH]; - float x, y, z, sx, sy, sz, rr, dd, phi, theta; - int field; - int label_index_array[LABL_MAX_LABELS]; - int num_labels_found; - float value=0; - - /* make sure we an interpreter to send commands to */ - if (g_interp==NULL) - return; - - /* Make sure we have a valid vno. */ - if ( vno < 0 || vno >= mris->nvertices ) - return; - - /* If this is our cursor label set, we'll be updating captions - too. */ - if (0 == label_set) - cptn_clear_value_string(); - - /* get the vertex */ - v = &mris->vertices[vno]; - - /* send each label value. If this is the cursor label set, update - the caption, too. */ - sprintf(command, "UpdateLabel %d %d %d", label_set, LABEL_VERTEXINDEX, vno); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_VERTEXINDEX, "%d", vno); - - sprintf(command, "UpdateLabel %d %d %f", label_set, LABEL_DISTANCE, dmin); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_DISTANCE, "%f", dmin); - - sprintf(command,"UpdateLabel %d %d \"(%.2f %.2f %.2f)\"", - label_set, LABEL_COORDS_RAS, v->origx, v->origy, v->origz); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_COORDS_RAS, "(%.2f, %.2f, %.2f)", - v->origx, v->origy, v->origz); - - if (MRIflag && MRIloaded) - { - imnr = (int)((v->y-yy0)/st+0.5); - i = (int)((zz1-v->z)/ps+0.5); - j = (int)((xx1-v->x)/ps+0.5); - sprintf(command, "UpdateLabel %d %d \"(%d %d %d)\"", - label_set, LABEL_COORDS_INDEX, imnr, i, j); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_COORDS_INDEX, "(%d, %d, %d)", - imnr, i, j); - - sprintf(command, "UpdateLabel %d %d %d", - label_set, LABEL_MRIVALUE, im[imnr][i][j]); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_MRIVALUE, "%d", im[imnr][i][j]); - } - /* if we have a tal transform, compute the tal. */ - if (transform_loaded) - { - conv_ras_to_tal( v->origx, v->origy, v->origz, &x_tal, &y_tal, &z_tal ); - sprintf(command, "UpdateLabel %d %d \"(%.2f %.2f %.2f)\"", - label_set, LABEL_COORDS_TAL, x_tal, y_tal, z_tal ); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_COORDS_TAL, "(%.2f, %.2f, %.2f)", - x_tal, y_tal, z_tal); - - conv_ras_to_mnital( v->origx, v->origy, v->origz, - &x_mni, &y_mni, &z_mni ); - sprintf(command, "UpdateLabel %d %d \"(%.2f %.2f %.2f)\"", - label_set, LABEL_COORDS_MNITAL, x_mni, y_mni, z_mni ); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_COORDS_MNITAL, "(%.2f, %.2f, %.2f)", - x_mni, y_mni, z_mni); - } - - sprintf(command, "UpdateLabel %d %d \"(%.2f %.2f %.2f)\"", - label_set, LABEL_COORDS_NORMAL, v->nx, v->ny, v->nz); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_COORDS_NORMAL, "(%.2f, %.2f, %.2f)", - v->nx, v->ny, v->nz); - - /* if a canon surface isn't loaded, make a name and see if it exists. */ - if (canonsurfloaded == FALSE && canonsurffailed == FALSE) - { - sprintf(fname, "%s.%s", fpref, sphere_reg_suffix) ; - if (FileExists(fname)) - { - printf("surfer: reading canonical coordinates from\n"); - printf("surfer: %s\n",fname); - } - else - { - /* set our don't load flag here so we don't - try and load it every time */ - dontloadspherereg = TRUE; - } - } - if (canonsurffailed) - dontloadspherereg = TRUE; - - /* if the canon surface is loaded _or_ if the filename made above exists - and we can read in the vertex coords and our don't load flag isn't - on... */ - if (canonsurfloaded == TRUE || - (dontloadspherereg == FALSE && - FileExists(fname) && - read_canon_vertex_coordinates(fname) == NO_ERROR) ) - { - x = mris->vertices[vno].cx ; - y = mris->vertices[vno].cy ; - z = mris->vertices[vno].cz ; - sx = x*e0[0] + y*e0[1] + z*e0[2] ; - sy = x*e1[0] + y*e1[1] + z*e1[2] ; - sz = x*e2[0] + y*e2[1] + z*e2[2] ; - x = sx ; - y = sy ; - z = sz ; - - rr = sqrt(x*x + y*y + z*z) ; - dd = rr*rr-z*z ; - if (dd < 0.0) - dd = 0.0 ; - - phi = atan2(sqrt(dd), z) ; - theta = atan2(y/rr, x/rr) ; - - sprintf(command, "UpdateLabel %d %d \"(%.2f %.2f %.2f)\"", - label_set, LABEL_COORDS_SPHERE_XYZ, sx, sy, sz ); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_COORDS_SPHERE_XYZ, "(%.2f, %.2f, %.2f)", - sx, sy, sz); - - sprintf(command, "UpdateLabel %d %d \"(%2.1f %2.1f)\"", - label_set, LABEL_COORDS_SPHERE_RT, - DEGREES(phi), DEGREES(theta) ); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_COORDS_SPHERE_RT, "(%2.1f, %2.1f)", - DEGREES(phi), DEGREES(theta)); - } - - sprintf(command, "UpdateLabel %d %d %f", - label_set, LABEL_CURVATURE, v->curv); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_CURVATURE, "%f", v->curv); - - sprintf(command, "UpdateLabel %d %d %f", - label_set, LABEL_FIELDSIGN, v->fieldsign); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_FIELDSIGN, "%f", v->fieldsign); - - /* overlay labels. draw the current one in stars. */ - for (field = 0; field < NUM_SCALAR_VALUES; field++ ) - { - sclv_get_value(v,field,&value); - if (field == sclv_current_field) - { - sprintf(command, "UpdateLabel %d %d \"** %f **\"", label_set, - LABEL_VAL + field, value); - } - else - { - sprintf(command, "UpdateLabel %d %d %f", label_set, - LABEL_VAL + field, value); - } - send_tcl_command(command); - - if (LABELSET_CURSOR == label_set) - { - /* Build the string for the code here be affixing the field - number + 1 to the prefix, e.g. field 0 -> !o1 */ - sprintf (command, "%s%d", CPTN_CODE_FIELD_PREFIX, field+1); - cptn_sprintf_for_code (command, "%f", value); - } - } - - sprintf(command, "UpdateLabel %d %d %f", label_set, LABEL_AMPLITUDE, - hypot(v->val,v->val2)); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_AMPLITUDE, "%f", hypot(v->val,v->val2)); - - sprintf(command, "UpdateLabel %d %d %f", label_set, LABEL_ANGLE, - (float)(atan2(v->val2,v->val)*180.0/M_PI)); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_ANGLE, "%f", - (float)(atan2(v->val2,v->val)*180.0/M_PI)); - - sprintf(command, "UpdateLabel %d %d %f", label_set, LABEL_DEGREE, - (float)(atan2(v->val2,v->val)/(2*M_PI))); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_DEGREE, "%f", - (float)(atan2(v->val2,v->val)/(2*M_PI))); - - /* send label update. */ - err = labl_find_label_by_vno( vno, 0, label_index_array, - 2, &num_labels_found ); - if (err == ERROR_NONE && num_labels_found > 0) - { - if (num_labels_found > 1) - { - sprintf(command, "UpdateLabel %d %d \"%s, %d others\"", - label_set, LABEL_LABEL, - labl_labels[label_index_array[0]].name, - num_labels_found-1); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_LABEL, "%s, %d others", - labl_labels[label_index_array[0]].name, - num_labels_found-1 ); - - } - else - { - sprintf(command, "UpdateLabel %d %d \"%s\"", label_set, LABEL_LABEL, - labl_labels[label_index_array[0]].name ); - cptn_sprintf_for_code (CPTN_CODE_LABEL, "%s", - labl_labels[label_index_array[0]].name); - } - send_tcl_command(command); - } - else - { - sprintf(command, "UpdateLabel %d %d \"None.\"", label_set, LABEL_LABEL ); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_LABEL, "None"); - - } - - // if (annotationloaded) - // { - r = v->annotation & 0x00ff ; - g = (v->annotation >> 8) & 0x00ff ; - b = (v->annotation >> 16) & 0x00ff ; - sprintf(command, "UpdateLabel %d %d \"%d (%d %d %d)\"", - label_set, LABEL_ANNOTATION, v->annotation, r, g, b); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_ANNOTATION, "%d (%d, %d, %d)", - v->annotation, r, g, b); - // } - - if (parc_flag && v->val > 0 && parc_names[(int)nint(v->val)]) - { - sprintf(command, "UpdateLabel %d %d \"%s\"", - label_set, LABEL_PARCELLATION_NAME, - parc_names[(int)nint(v->val)]); - send_tcl_command(command); - if (LABELSET_CURSOR == label_set) - cptn_sprintf_for_code (CPTN_CODE_PARCELLATION_NAME, "%s", - parc_names[(int)nint(v->val)] ); - } - - /* Although we don't update the time point and condition in the - label section, we kind of need to update the caption with their - values here, so do that. */ - if ( sclv_current_field != -1 ) - { - cptn_sprintf_for_code (CPTN_CODE_TIME_POINT, "%d", - sclv_field_info[sclv_current_field].cur_timepoint ); - - cptn_sprintf_for_code (CPTN_CODE_CONDITION, "%d", - sclv_field_info[sclv_current_field].cur_condition ); - } -} - -/* ------------------------------------------------------------- the window */ - -#ifdef USE_XGLUT_WINDOW - -void wndw_create (int x, int y, int width, int height) -{ - xGWin_New (&gWindow, width, height, "tksurfer"); - xGWin_SetEventHandlerFunc (gWindow, wndw_handle_event, gWindow); - xGWin_ActivateIdleEvents (gWindow); - xGWin_ActivatePassiveMotionEvents (gWindow); - - openglwindowflag = 1; -} - -void wndw_set_title (char* title) -{ - xGWin_SetWindowTitle (gWindow, title); -} - -void wndw_handle_event (void* data, xGWin_tEventRef event) -{ - char command[STRLEN]; - int screen_x; - int screen_y; - int origin_x; - int origin_y; - int size_x; - int size_y; - float translate_x; - float translate_y; - float md; - int mvno; - int vno; - struct timeval tv; - - switch (event->mType) - { - case xGWin_tEventType_KeyDown: - switch (event->mKey) - { - case 'r': - if (event->mbAltKey && g_interp) - { - send_tcl_command("UpdateAndRedraw"); - } - break; - case 'q': - if (event->mbCtrlKey) - { - exit (0); - } - break; - case xGWin_tKey_UpArrow: - if (event->mbAltKey && g_interp) - { - send_tcl_command("set gNextTransform(rotate,x) " - "[expr $gNextTransform(rotate,x)+18.0]"); - send_tcl_command (command); - } - break; - case xGWin_tKey_DownArrow: - if (event->mbAltKey && g_interp) - { - send_tcl_command("set gNextTransform(rotate,x) " - "[expr $gNextTransform(rotate,x)-18.0]"); - send_tcl_command (command); - } - break; - case xGWin_tKey_RightArrow: - if (event->mbAltKey && g_interp) - { - send_tcl_command("set gNextTransform(rotate,y) " - "[expr $gNextTransform(rotate,y)-18.0]"); - send_tcl_command (command); - } - break; - case xGWin_tKey_LeftArrow: - if (event->mbAltKey && g_interp) - { - send_tcl_command("set gNextTransform(rotate,y) " - "[expr $gNextTransform(rotate,y)+18.0]"); - send_tcl_command (command); - } - break; - case xGWin_tKey_Home: - sprintf (command,"MoveToolWindow %d %d", - glutGet (GLUT_WINDOW_X), - glutGet (GLUT_WINDOW_Y) + w.h + MOTIF_YFUDGE); - send_tcl_command (command); - break; - } - break; /* case xGWin_tEventType_KeyDown */ - - case xGWin_tEventType_MouseDown: - screen_x = event->mWhere.mnX + w.x; - screen_y = 1024 - w.y - event->mWhere.mnY ; - if (1 == event->mButton) - { - /* Scale around click */ - if (event->mbCtrlKey) - { - origin_x = w.x; - origin_y = 1024 - w.y - w.h; - - size_x = w.w; - size_y = w.h; - - translate_x = sf * - (screen_x - origin_x - size_x / 2.0 ) * - 2.0 * fov / size_x; - translate_y = sf * - (screen_y - origin_y - size_y / 2.0 ) * - 2.0 * fov / size_y; - - translate_brain (-translate_x, -translate_y, 0); - scale_brain (SCALE_UP_MOUSE); - redraw(); - } - /* curvim */ - else if (event->mbShiftKey) - { - select_vertex (screen_x, screen_y); - read_curvim_at_vertex (selection); - draw_cursor (selection, TRUE); - } - else - { - /* If something is already selected, hilite it (because - it's marked now) and deselect it. */ - if (selection>=0) - { - draw_vertex_hilite (selection); - draw_cursor (selection, FALSE); - } - - /* Select the vertex at this point. If we got one, mark - it and draw the cursor. */ - select_vertex (screen_x, screen_y); - if (selection >= 0) - { - mark_vertex (selection, TRUE); - draw_cursor (selection, TRUE); - } - - /* Draw all the marked verts. */ - draw_marked_vertices (); - - if (showorigcoordsflag) - find_orig_vertex_coordinates(selection); - } - } /* if button 1 */ - - /* Button 2, just select and mark this vertex. */ - else if (2 == event->mButton) - { - find_closest_marked_vertex ((int)sx, (int)sy, NULL, &vno); - if (vno>=0) - { - fprintf (stderr, "Unmarking %d\n", vno); - mark_vertex (vno, FALSE); - draw_cursor (vno, FALSE); - } - } - - /* Button 3, if ctrl, zoom out, else clear all the selections. */ - else if (3 == event->mButton) - { - if (event->mbCtrlKey) - { - origin_x = w.x; - origin_y = 1024 - w.y - w.h; - - size_x = w.w; - size_y = w.h; - - translate_x = sf * - (screen_x - origin_x - size_x / 2.0 ) * 2.0 * fov / size_x; - translate_y = sf * - (screen_y - origin_y - size_y / 2.0 ) * 2.0 * fov / size_y; - - translate_brain (-translate_x, -translate_y, 0); - scale_brain (1.0/SCALE_UP_MOUSE); - redraw(); - } - else - { - clear_all_vertex_marks(); - labl_select(-1); - redraw(); - } - } - break; - - case xGWin_tEventType_MouseUp: - break; - - case xGWin_tEventType_MouseMoved: - screen_x = event->mWhere.mnX + w.x; - screen_y = 1024 - w.y - event->mWhere.mnY ; - find_vertex_at_screen_point (screen_x, screen_y, &mvno, &md); - if (mvno >= 0) - { - mouseover_vno = vno; - update_labels (LABELSET_MOUSEOVER, mouseover_vno, md); - } - break; - - case xGWin_tEventType_Resize: - /* Get the new dimensions. */ - w.x = glutGet( GLUT_WINDOW_X ); - w.y = glutGet( GLUT_WINDOW_Y ); - w.w = event->mWhere.mnX; - w.h = event->mWhere.mnY; - curwindowleft = w.x; - curwindowbottom = w.y + w.h; - - /* Resize the opengl port. */ - glutReshapeWindow (w.w, w.h); - - /* Do some other legacy stuff. */ - resize_window (0); - - /* Move the tool window under us. */ - sprintf (command,"MoveToolWindow %d %d", w.x, w.y + w.h + MOTIF_YFUDGE); - send_tcl_command (command); - - break; - - case xGWin_tEventType_Draw: - if (redrawlockflag) - redraw(); - break; - - case xGWin_tEventType_Idle: - /* Call the Tk event handling function. */ - while (Tk_DoOneEvent (TK_ALL_EVENTS | TK_DONT_WAIT)) - {} - -#ifndef sgi - tv.tv_sec = 0; - tv.tv_usec = 10000; - select(0, NULL, NULL, NULL, &tv); -#else - sginap((long)1); /* block for 10 msec */ -#endif - - break; - - default: - break; - - } -} - -#endif /* USE_XGLUT_WINDOW */ - -/* -------------------------------------------------- ctrl-c cancel support */ - -void cncl_initialize () -{ - /* init the flags and register our handler. */ - cncl_listening = 0; - cncl_canceled = 0; - signal (SIGINT, cncl_handle_sigint); -} - -void cncl_start_listening () -{ - /* set our listening flag. */ - cncl_listening = 1; -} - -void cncl_stop_listening () -{ - /* stop listening and reset the canceled flag. */ - cncl_listening = 0; - cncl_canceled = 0; -} - -int cncl_user_canceled () -{ - /* just return the canceled flag. */ - return (cncl_canceled); -} - -void cncl_handle_sigint (int signal) -{ - - /* if we're listening, set the flag, if not, exit normally. */ - if (cncl_listening) - { - cncl_canceled = 1; - } - else - { - printf ("Killed\n"); - fflush ( stdout ); - exit (1); - } -} - -/* ------------------------------------------------------------------------ */ - -/* ------------------------------------------------------- menu set support */ - -int -enable_menu_set (int set, int enable) -{ - char tcl_cmd[1024]; - - strncpy (tcl_cmd, "tkm_SetEnableGroupStatus", sizeof(tcl_cmd)); - switch (set) - { - case MENUSET_VSET_INFLATED_LOADED: - strcat (tcl_cmd, " mg_InflatedVSetLoaded"); - break; - case MENUSET_VSET_WHITE_LOADED: - strcat (tcl_cmd, " mg_WhiteVSetLoaded"); - break; - case MENUSET_VSET_PIAL_LOADED: - strcat (tcl_cmd, " mg_PialVSetLoaded"); - break; - case MENUSET_VSET_ORIGINAL_LOADED: - strcat (tcl_cmd, " mg_OriginalVSetLoaded"); - break; - case MENUSET_TIMECOURSE_LOADED: - strcat (tcl_cmd, " mg_TimeCourseLoaded"); - break; - case MENUSET_OVERLAY_LOADED: - strcat (tcl_cmd, " mg_OverlayLoaded"); - break; - case MENUSET_CURVATURE_LOADED: - strcat (tcl_cmd, " mg_CurvatureLoaded"); - break; - case MENUSET_LABEL_LOADED: - strcat (tcl_cmd, " mg_LabelLoaded"); - break; - case MENUSET_FIELDSIGN_LOADED: - strcat (tcl_cmd, " mg_FieldSignLoaded"); - break; - case MENUSET_FIELDMASK_LOADED: - strcat (tcl_cmd, " mg_FieldMaskLoaded"); - break; - default: - ErrorReturn(ERROR_BADPARM,(ERROR_BADPARM, - "enable_menu_set: bad set %d\n",set)); - } - char enable_cmd[100]; - sprintf (enable_cmd, " %d", enable); - strcat (tcl_cmd, enable_cmd); - send_tcl_command(tcl_cmd); - - return(ERROR_NONE); -} - -/* ------------------------------------------------------------------------ */ - -/* -------------------------------------------- multiple vertex set support */ - -int -vset_initialize() -{ - int i; - /* set them all to null */ - for (i=0; i NUM_VERTEX_SETS) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "vset_load_surface_vertices: invalid set %d\n",set)); - - /* allocate storage if not done so already */ - if (vset_vertex_list[set]==NULL) - { - vset_vertex_list[set]=(VSET_VERTEX*) - calloc(mris->nvertices,sizeof(VSET_VERTEX)); - if (vset_vertex_list[set]==NULL) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "vset_save_surface_vertices: allocation of " - "vset_vertex_list[%d] failed (size=%d)\n", - set,mris->nvertices)); - } - - /* save all vertex values into storage */ - nvertices=mris->nvertices; - for (vno=0;vnovertices[vno]; - vset_vertex_list[set][vno].x = v->x; - vset_vertex_list[set][vno].y = v->y; - vset_vertex_list[set][vno].z = v->z; - } - - return(NO_ERROR); -} - -int -vset_load_surface_vertices(int set) -{ - - int vno,nvertices; - VERTEX* v; - - if (set < 0 || set > NUM_VERTEX_SETS) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "vset_load_surface_vertices: invalid set %d\n",set)); - - /* if not allocated, no verts stored there */ - if (vset_vertex_list[set]==NULL) - { - printf("surfer: vertex set not loaded.\n"); - return(NO_ERROR); - } - - /* load all vertex values from storage */ - nvertices=mris->nvertices; - for (vno=0;vnonvertices;vno++) - { - v = &mris->vertices[vno]; - v->x = vset_vertex_list[set][vno].x; - v->y = vset_vertex_list[set][vno].y; - v->z = vset_vertex_list[set][vno].z; - } - - return(NO_ERROR); -} - -int vset_set_current_set(int set) -{ - int err; - - if (set < 0 || set > NUM_VERTEX_SETS) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "vset_set_current_set: invalid set %d\n",set)); - - if (NULL == vset_vertex_list[set]) - { - switch (set) - { - case VSET_PIAL: - err = vset_read_vertex_set(set, "pial"); - if (err) ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "vset_set_current_set: set %d not loaded\n",set)); - break; - case VSET_ORIGINAL: - err = vset_read_vertex_set(set, "orig"); - if (err) ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "vset_set_current_set: set %d not loaded\n",set)); - break; - case VSET_WHITE: - err = vset_read_vertex_set(set, "white"); - if (err) ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "vset_set_current_set: set %d not loaded\n",set)); - break; - case VSET_INFLATED: - err = vset_read_vertex_set(set, "inflated"); - if (err) ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "vset_set_current_set: set %d not loaded\n",set)); - break; - } - } - - /* Make sure this set is loaded unless it's the main set which is - always loaded.. */ - if (NULL == vset_vertex_list[set] && VSET_MAIN != set) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "vset_set_current_set: set %d not loaded\n",set)); - - /* save the main set if we haven't done so yet */ - if (vset_current_set==VSET_MAIN && vset_vertex_list[VSET_MAIN]==NULL) - vset_save_surface_vertices(VSET_MAIN); - - /* load in over the main set */ - vset_load_surface_vertices(set); - - /* save the new vertex set. recompute the normals and mark our - vertex array dirty so it will rebuild on next redraw. */ - vset_current_set = set; - vertex_array_dirty = 1; - compute_normals(); - - /* Find the path bounding boxes again. */ - path_update_bounding_boxes(); - - /* Find the label bounding boxes again. */ - labl_all_changed(); - - return(NO_ERROR); -} - -/* ------------------------------------------------------------------------ */ - -/* -------------------------------------------------- coordinate conversion */ - -int conv_initialize() -{ - char fname[STRLEN] = ""; - char surf_path[STRLEN] = ""; - FILE* fTest; - - - /* allocate our conversion matrices. */ - if (NULL != conv_mnital_to_tal_m_ltz) - MatrixFree (&conv_mnital_to_tal_m_ltz); - - conv_mnital_to_tal_m_ltz = MatrixIdentity (4, NULL); - stuff_four_by_four (conv_mnital_to_tal_m_ltz, - 0.99, 0, 0, 0, - 0.00, 0.9688, 0.042, 0, - 0.00, -0.0485, 0.839, 0, - 0.00, 0, 0, 1); - - if (NULL != conv_mnital_to_tal_m_gtz) - MatrixFree (&conv_mnital_to_tal_m_gtz); - - conv_mnital_to_tal_m_gtz = MatrixIdentity (4, NULL); - stuff_four_by_four (conv_mnital_to_tal_m_gtz, - 0.99, 0, 0, 0, - 0.00, 0.9688, 0.046, 0, - 0.00, -0.0485, 0.9189, 0, - 0.00, 0, 0, 1); - - /* calc the inverses. */ - conv_tal_to_mnital_m_ltz = MatrixInverse (conv_mnital_to_tal_m_ltz, NULL ); - conv_tal_to_mnital_m_gtz = MatrixInverse (conv_mnital_to_tal_m_gtz, NULL ); - - /* allocate our temporary matrices. */ - if (NULL != conv_tmp1_m) - MatrixFree (&conv_tmp1_m); - conv_tmp1_m = MatrixAlloc (4, 1, MATRIX_REAL); - - if (NULL != conv_tmp2_m) - MatrixFree (&conv_tmp2_m); - conv_tmp2_m = MatrixAlloc (4, 1, MATRIX_REAL); - - - /* We need to read in the COR- header from the orig volume, if - available, and get the extract_i_to_r transform. */ - if ( NULL != mris ) - { - FileNamePath (mris->fname, surf_path); - sprintf (fname, "%s/../mri/orig/COR-.info", surf_path); - - fTest = fopen (fname, "r" ); - if (NULL != fTest) - { - fclose (fTest ); - orig_mri_header = MRIreadHeader (fname, MRI_VOLUME_TYPE_UNKNOWN); - } - if ( NULL == orig_mri_header ) - { - sprintf (fname, "%s/../mri/orig.mgh", surf_path); - fTest = fopen (fname, "r" ); - if (NULL != fTest) - { - fclose (fTest ); - orig_mri_header = MRIreadHeader (fname, MRI_VOLUME_TYPE_UNKNOWN); - } - if ( NULL == orig_mri_header ) - { - sprintf (fname, "%s/../mri/orig.mgz", surf_path); - fTest = fopen (fname, "r" ); - if (NULL != fTest) - { - fclose (fTest ); - orig_mri_header = MRIreadHeader (fname, MRI_VOLUME_TYPE_UNKNOWN); - } - if ( NULL == orig_mri_header ) - { - printf ("WARNING: Could not load orig volume.\n" - " Talairach coords will be incorrect.\n" ); - } - } - } - - if (NULL != orig_mri_header) - { - surfaceRAStoRAS = surfaceRASFromRAS_( orig_mri_header ); - } - } - - return(NO_ERROR); -} - - -int conv_ras_to_mnital(float srasx, float srasy, float srasz, - float* mnix, float* mniy, float* mniz) -{ - double rasx, rasy, rasz; - - /* If we have the original MRI volume and this surface doesn't have - the useRealRAS flag, use it to go from surface RAS coords to - normal RAS coords. Otherwise just use the surface RAS coords. */ - if (NULL != orig_mri_header && !mris->useRealRAS) - { - MRIsurfaceRASToRAS (orig_mri_header, srasx, srasy, srasz, - &rasx, &rasy, &rasz); - } - else - { - rasx = srasx; - rasy = srasy; - rasz = srasz; - } - - /* Run the talairach transformation. */ - if (transform_loaded && - NULL != lta && - lta->type == LINEAR_RAS_TO_RAS) - { - LTAworldToWorldEx (lta, rasx, rasy, rasz, mnix, mniy, mniz); - } - - return(NO_ERROR); -} - -int conv_ras_to_tal(float srasx, float srasy, float srasz, - float* talx, float* taly, float* talz) -{ - float mnix, mniy, mniz; - - conv_ras_to_mnital (srasx, srasy, srasz, &mnix, &mniy, &mniz); - - *MATRIX_RELT(conv_tmp1_m,1,1) = mnix; - *MATRIX_RELT(conv_tmp1_m,2,1) = mniy; - *MATRIX_RELT(conv_tmp1_m,3,1) = mniz; - *MATRIX_RELT(conv_tmp1_m,4,1) = 1.0; - - if (mniz > 0) - { - MatrixMultiply (conv_mnital_to_tal_m_gtz, conv_tmp1_m, conv_tmp2_m); - } - else - { - MatrixMultiply (conv_mnital_to_tal_m_ltz, conv_tmp1_m, conv_tmp2_m); - } - - *talx = *MATRIX_RELT(conv_tmp2_m,1,1); - *taly = *MATRIX_RELT(conv_tmp2_m,2,1); - *talz = *MATRIX_RELT(conv_tmp2_m,3,1); - - return(NO_ERROR); -} - -int conv_mnital_to_ras(float mnix, float mniy, float mniz, - float* osrasx, float* osrasy, float* osrasz) -{ - - float rasx, rasy, rasz; - double srasx, srasy, srasz; - - /* Run the talairach transformation. */ - if (transform_loaded && - NULL != lta && - lta->type == LINEAR_RAS_TO_RAS) - { - LTAinverseWorldToWorldEx (lta, mnix, mniy, mniz, &rasx, &rasy, &rasz); - } - - if (NULL != orig_mri_header && !mris->useRealRAS) - { - MRIRASToSurfaceRAS (orig_mri_header, rasx, rasy, rasz, - &srasx, &srasy, &srasz); - } - else - { - srasx = rasx; - srasy = rasy; - srasz = rasz; - } - - *osrasx = (float) srasx; - *osrasy = (float) srasy; - *osrasz = (float) srasz; - - return(NO_ERROR); -} - -int conv_tal_to_ras(float talx, float taly, float talz, - float* srasx, float* srasy, float* srasz) -{ - - float mnix, mniy, mniz; - - - *MATRIX_RELT(conv_tmp1_m,1,1) = talx; - *MATRIX_RELT(conv_tmp1_m,2,1) = taly; - *MATRIX_RELT(conv_tmp1_m,3,1) = talz; - *MATRIX_RELT(conv_tmp1_m,4,1) = 1.0; - - if (talz > 0) - { - MatrixMultiply (conv_tal_to_mnital_m_gtz, conv_tmp1_m, conv_tmp2_m); - } - else - { - MatrixMultiply (conv_tal_to_mnital_m_ltz, conv_tmp1_m, conv_tmp2_m); - } - - mnix = *MATRIX_RELT(conv_tmp2_m,1,1); - mniy = *MATRIX_RELT(conv_tmp2_m,2,1); - mniz = *MATRIX_RELT(conv_tmp2_m,3,1); - - conv_mnital_to_ras (mnix, mniy, mniz, srasx, srasy, srasz); - - return(NO_ERROR); -} - -/* ------------------------------------------------------------------------ */ - -/* ----------------------------------------------------------- undo support */ - -int undo_initialize() -{ - int undo_index; - for (undo_index = UNDO_LIST_POS_FIRST; - undo_index <= UNDO_LIST_POS_LAST; - undo_index++ ) - undo_list[undo_index] = NULL; - - undo_send_first_action_name(); - - return(NO_ERROR); -} - -int undo_get_action_node_size(int action_type) -{ - int size=-1; - - /* return the size of the specific action node impelementation, or - -1 as an error condition. */ - switch (action_type) - { - case UNDO_CUT: - size = sizeof(UNDO_CUT_NODE); - break; - default: - size = -1; - break; - } - - return(size); -} - -char* undo_get_action_string(int action_type) -{ - char* string=NULL; - - /* if the action type is in bounds, return a string from the - undo_action_strings array, else return a null string. */ - if (action_type >= UNDO_INVALID && action_type < NUM_UNDO_ACTIONS) - string=undo_action_strings[action_type]; - else - string=NULL; - - return(string); -} - -int undo_begin_action(int action_type) -{ - UNDO_ACTION* action = NULL; - xGArr_tErr array_error = xGArr_tErr_NoErr; - int action_size = 0; - int undo_index = 0; - - if (undo_list_state!=UNDO_LIST_STATE_CLOSED) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "undo_begin_action: undo list state is not closed\n")); - - if (action_type<=UNDO_NONE || action_type>=NUM_UNDO_ACTIONS) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "undo_begin_action: invalid action type\n")); - - /* create a new undo action */ - action = (UNDO_ACTION*)malloc(sizeof(UNDO_ACTION)); - if (action==NULL) - ErrorReturn(ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, - "undo_begin_action: malloc UNDO_ACTION failed\n")); - action->undo_type = action_type; - - /* get the action node size and allocate the node list */ - action_size = undo_get_action_node_size(action_type); - if (action_size<=0) - ErrorReturn(ERROR_UNDO_ACTION, - (ERROR_UNDO_ACTION, - "undo_begin_action: action_size was <= 0\n")); - array_error = xGArr_New (&(action->node_list), action_size, 64); - if (array_error!=xGArr_tErr_NoErr) - ErrorReturn(ERROR_ARRAY, - (ERROR_ARRAY, - "undo_begin_action: xGArr_New failed\n")); - - /* if there was a list in the last slot, delete it */ - if (undo_list[UNDO_LIST_POS_LAST]!=NULL) - { - array_error = xGArr_Delete (&(undo_list[UNDO_LIST_POS_LAST]->node_list)); - if (array_error!=xGArr_tErr_NoErr) - ErrorPrintf(0,"undo_begin_action: xGArr_Delete failed\n"); - free (undo_list[UNDO_LIST_POS_LAST]); - } - - /* move the undo lists down */ - for (undo_index=UNDO_LIST_POS_LAST; - undo_index>UNDO_LIST_POS_FIRST; - undo_index--) - { - undo_list[undo_index] = undo_list[undo_index-1]; - } - - /* save the new action in the list */ - undo_list[UNDO_LIST_POS_FIRST] = action; - - /* set our state */ - undo_list_state = UNDO_LIST_STATE_OPEN; - - return(NO_ERROR); -} - -int undo_finish_action() -{ - /* set our state */ - undo_list_state = UNDO_LIST_STATE_CLOSED; - - undo_send_first_action_name (); - - return(NO_ERROR); -} - -int undo_send_first_action_name() -{ - char* string = NULL; - char command[1024] = ""; - - /* get the undo action string and send it to the interface */ - if (undo_list[UNDO_LIST_POS_FIRST]!=NULL) - { - string = undo_get_action_string - (undo_list[UNDO_LIST_POS_FIRST]->undo_type); - } - else - { - string = undo_get_action_string (UNDO_NONE); - } - - if (string==NULL) - ErrorReturn(ERROR_UNDO_ACTION, - (ERROR_UNDO_ACTION, - "undo_send_first_action_name: " - "undo_get_action_string returned null\n")); - - /* build and send the command */ - sprintf (command, "UpdateUndoItemLabel \"%s\"", string); - send_tcl_command (command); - - return(NO_ERROR); -} - -int undo_copy_action_node(void* node) -{ - xGArr_tErr array_error = xGArr_tErr_NoErr; - - /* make sure the list is open */ - if (undo_list_state!=UNDO_LIST_STATE_OPEN) - ErrorReturn(ERROR_UNDO_LIST_STATE, - (ERROR_UNDO_LIST_STATE, - "undo_copy_action_node: undo list state was not open\n")); - - /* copy the node to the action node list */ - array_error = xGArr_Add (undo_list[UNDO_LIST_POS_FIRST]->node_list, node); - if (array_error!=xGArr_tErr_NoErr) - ErrorReturn(ERROR_ARRAY, - (ERROR_ARRAY,"undo_copy_action_node: xGArr_Add failed\n")); - - return(NO_ERROR); -} - -int undo_do_first_action() -{ - int error = NO_ERROR; - int undo_index = 0; - xGArr_tErr array_error; - - /* return if we have no list */ - if (undo_list[UNDO_LIST_POS_FIRST]==NULL) - return(NO_ERROR); - - /* make sure the list is closed */ - if (undo_list_state!=UNDO_LIST_STATE_CLOSED) - ErrorReturn(ERROR_UNDO_LIST_STATE, - (ERROR_UNDO_LIST_STATE, - "undo_do_first_action: undo list state was not closed\n")); - - /* get the action and switch on its type. call the proper handler. if it - returns an error, print a msg but don't bail. */ - switch (undo_list[UNDO_LIST_POS_FIRST]->undo_type) - { - case UNDO_CUT: - error = undo_do_action_cut (undo_list[UNDO_LIST_POS_FIRST]); - break; - default: - ErrorReturn(ERROR_UNDO_ACTION, - (ERROR_UNDO_ACTION, - "undo_do_first_action: " - "invalid action type in non-null action\n")); - break; - } - if (error!=NO_ERROR) - ErrorPrintf(ERROR_UNDO_ACTION, - "undo_do_first_action: undo handler returned an error\n"); - - /* delete that action */ - array_error = xGArr_Delete (&(undo_list[UNDO_LIST_POS_FIRST]->node_list) ); - if (array_error!=xGArr_tErr_NoErr) - ErrorPrintf(ERROR_ARRAY,"undo_do_first_action: xGArr_Delete failed\n"); - free (undo_list[UNDO_LIST_POS_FIRST]); - - /* remove the action from the list and bump everything up. set the - last pos to null. */ - for (undo_index=UNDO_LIST_POS_FIRST; - undo_indexundo_type!=UNDO_CUT) - ErrorReturn(ERROR_UNDO_ACTION, - (ERROR_UNDO_ACTION, - "undo_do_action_cut: action type was not cut\n")); - - /* go thru every node in the array... */ - xGArr_ResetIterator (action->node_list); - array_error = xGArr_tErr_NoErr; - while ((array_error=xGArr_NextItem(action->node_list,(void*)&cut_action)) - ==xGArr_tErr_NoErr) - { - /* switch on the cut action type and set the face or vertex rip flag to - the stored value */ - switch (cut_action.cut_type) - { - case UNDO_CUT_VERTEX: - set_vertex_rip (cut_action.index, cut_action.rip_value, FALSE); - break; - case UNDO_CUT_FACE: - set_face_rip (cut_action.index, cut_action.rip_value, FALSE); - break; - default: - ErrorPrintf(ERROR_UNDO_ACTION, - "undo_do_action_cut: invalid cut type\n"); - } - } - - return(NO_ERROR); -} - -/* ---------------------------------------------------------------------- */ - -/* -------------------------------------------- functional volume support */ - -int func_initialize() -{ - xGArr_tErr array_error = xGArr_tErr_NoErr; - - /* init our list */ - array_error = xGArr_New (&func_selected_ras, - sizeof(FUNC_SELECTED_VOXEL), 64); - if (array_error!=xGArr_tErr_NoErr) - ErrorReturn(ERROR_ARRAY, - (ERROR_ARRAY, - "func_initialize: xGArr_New failed\n")); - - func_use_timecourse_offset = FALSE; - func_sub_prestim_avg = FALSE; - - return(ERROR_NONE); -} - -int func_load_timecourse (char* fname, FunD_tRegistrationType reg_type, - char* registration) -{ - FunD_tErr volume_error; - char tcl_cmd[1024]; - float time_resolution; - Volm_tErr volm_err = Volm_tErr_NoErr; - mriVolumeRef volm = NULL; - int good = 0; - - if (fname==NULL) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "func_load_timecourse: fname was null\n")); - - /* delete existing mriFunctionalDataRef or MRI. */ - if (func_timecourse!=NULL) - { - volume_error = FunD_Delete(&func_timecourse); - if (volume_error!=FunD_tErr_NoError) - ErrorPrintf(func_convert_error(volume_error), - "func_load_timecourse: error in FunD_Delete\n"); - } - - if (FunD_tRegistration_None == reg_type) - { - printf ("surfer: ERROR: Must specify registration type for " - "time course. Use -timecourse-reg , " - "-timecourse-reg-find, or -timecourse-reg-identity.\n"); - return ERROR_BADPARM; - } - - /* Unless they selected the none-needed registration method, we need - to load up a volume for them to use as the base for the - transform. So we use the orig header, which should already have - been loaded, to get one. */ - if (FunD_tRegistration_NoneNeeded != reg_type) - { - good = 0; - if (NULL != orig_mri_header) - { - volm_err = Volm_New (&volm); - if (Volm_tErr_NoErr == volm_err) - { - volm_err = Volm_ImportData (volm, orig_mri_header->fname); - if (Volm_tErr_NoErr == volm_err) - { - good = 1; - } - } - } - - if (!good) - { - if (NULL != volm) - Volm_Delete (&volm); - printf ("surfer: ERROR: You specified a registration type, " - "but tksurfer cannot find an anatomical volume with which " - "to calculate the registration. Please make sure the " - "orig volume is present in the subject's mri/ directory.\n"); - return ERROR_BADPARM; - } - } - - if ((FunD_tRegistration_File == reg_type) && - (registration) && - (strlen(registration)==0)) - { - printf ("surfer: func_load_timecourse, ERROR: " - "missing registration filename\n"); - return ERROR_BADPARM; - } - - /* create new volume */ - volume_error = FunD_New (&func_timecourse, - fname, - reg_type, - registration, - mris->nvertices, - volm, - mris->hemisphere == LEFT_HEMISPHERE); - - if (volume_error!=FunD_tErr_NoError) - { - if (NULL != volm) - Volm_Delete (&volm); - printf("### surfer: couldn't load %s\n",fname); - ErrorReturn(func_convert_error(volume_error), - (func_convert_error(volume_error), - "func_load_timecourse: error in FunD_New\n")); - } - - /* Notify the volume we're in tkreg space, so our transform is - correct. */ - volume_error = FunD_ClientSpaceIsTkRegRAS (func_timecourse); - if (volume_error!=FunD_tErr_NoError) - { - if (NULL != volm) - Volm_Delete (&volm); - printf("surfer: couldn't load %s\n",fname); - ErrorReturn - (func_convert_error(volume_error), - (func_convert_error(volume_error), - "func_load_timecourse: error in FunD_ClientSpaceIsTkRegRAS\n")); - } - - printf("surfer: loaded timecourse %s\n",fname); - - /* See if it's scalar */ - FunD_IsScalar (func_timecourse, &func_is_scalar_volume); - - if (func_is_scalar_volume) - { - printf ("surfer: Interpreting time course volume %s " - "as encoded scalar volume.\n", fname); - if ((func_timecourse->mpData->nframes == mris->nvertices) || - (func_timecourse->mpData->nframes == 2*mris->nvertices)) - { - char cmd[STRLEN] ; - MRI *mri_tmp, *mri_tmp2 ; - if (mris->hemisphere == LEFT_HEMISPHERE) - { - mri_tmp = MRIextractInto(func_timecourse->mpData, NULL, 0, 0, 0, - func_timecourse->mpData->width/2, - func_timecourse->mpData->height, - func_timecourse->mpData->depth, - 0,0,0) ; - mri_tmp2 = MRIcopyFrames(mri_tmp, NULL, 0, mris->nvertices-1, 0) ; - } - else - { - mri_tmp = MRIextractInto(func_timecourse->mpData, NULL, 0, 0, 0, - func_timecourse->mpData->width/2, - func_timecourse->mpData->height, - func_timecourse->mpData->depth, - mris->nvertices,0,0) ; - mri_tmp2 = MRIcopyFrames(mri_tmp, NULL, mris->nvertices, - 2*mris->nvertices-1, 0) ; - } - MRIfree(&mri_tmp) ; - MRIfree(&func_timecourse->mpData) ; func_timecourse->mpData = mri_tmp2 ; - func_timecourse->mNumTimePoints = mri_tmp2->nframes ; - enable_menu_set (MENUSET_OVERLAY_LOADED, 1); - enable_menu_set(MENUSET_TIMECOURSE_LOADED, 1) ; - sprintf (cmd, "UpdateLinkedVarGroup overlay"); - send_tcl_command (cmd); - linkvertexmode = 1 ; - fprintf(stderr, "setting linkvertexmode to %d\n", linkvertexmode) ; - } - } - else - { - printf ("surfer: Interpreting time course volume %s " - "as registered functional volume.\n", fname); - } - - /* get the time res, num conditions, and num presitm points */ - FunD_GetNumPreStimTimePoints (func_timecourse, &func_num_prestim_points); - FunD_GetTimeResolution (func_timecourse, &time_resolution); - FunD_GetNumConditions (func_timecourse, &func_num_conditions); - FunD_GetNumTimePoints (func_timecourse, &func_num_timepoints); - func_time_resolution = (double)time_resolution; - - /* send the number of conditions */ - sprintf (tcl_cmd, "Graph_SetNumConditions %d", func_num_conditions); - send_tcl_command (tcl_cmd); - - /* show the graph window */ - send_tcl_command ("Graph_ShowWindow"); - - /* enable the related menu items */ - enable_menu_set (MENUSET_TIMECOURSE_LOADED, 1); - - if (NULL != volm) - Volm_Delete (&volm); - - return(ERROR_NONE); -} - -int func_load_timecourse_offset (char* fname, FunD_tRegistrationType reg_type, - char* registration) -{ - FunD_tErr volume_error; - Volm_tErr volm_err = Volm_tErr_NoErr; - mriVolumeRef volm = NULL; - int good = 0; - - if (fname==NULL) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "func_load_timecourse_offset: fname was null\n")); - - /* delete existing */ - if (func_timecourse_offset!=NULL) - { - volume_error = FunD_Delete(&func_timecourse_offset); - if (volume_error!=FunD_tErr_NoError) - ErrorPrintf(func_convert_error(volume_error), - "func_load_timecourse_offset: error in FunD_Delete\n"); - } - - if (FunD_tRegistration_None == reg_type) - { - printf ("surfer: ERROR: Must specify registration type for " - "time course offset. Use -timecourse-offset-reg , " - "-timecourse-offset-reg-find, or " - "-timecourse-offset-reg-identity.\n"); - return ERROR_BADPARM; - } - - /* Unless they selected the none-needed registration method, we need - to load up a volume for them to use as the base for the - transform. So we use the orig header, which should already have - been loaded, to get one. */ - if (FunD_tRegistration_NoneNeeded != reg_type) - { - good = 0; - if (NULL != orig_mri_header) - { - volm_err = Volm_New (&volm); - if (Volm_tErr_NoErr == volm_err) - { - volm_err = Volm_ImportData (volm, orig_mri_header->fname); - if (Volm_tErr_NoErr == volm_err) - { - good = 1; - } - } - } - - if (!good) - { - if (NULL != volm) - Volm_Delete (&volm); - printf ("surfer: ERROR: You specified a registration type, " - "but tksurfer cannot find an anatomical volume with which " - "to calculate the registration. Please make sure the " - "orig volume is present in the subject's mri/ directory.\n"); - return ERROR_BADPARM; - } - } - - if ((FunD_tRegistration_File == reg_type) && - (registration) && - (strlen(registration)==0)) - { - printf ("surfer: func_load_timecourse_offset, ERROR: " - "missing registration filename\n"); - return ERROR_BADPARM; - } - - /* create new volume */ - volume_error = FunD_New (&func_timecourse_offset, - fname, - reg_type, - registration, - mris->nvertices, /* Try to be scalar */ - volm, - mris->hemisphere == LEFT_HEMISPHERE); - - if (volume_error!=FunD_tErr_NoError) - { - if (NULL != volm) - Volm_Delete (&volm); - ErrorReturn(func_convert_error(volume_error), - (func_convert_error(volume_error), - "func_load_timecourse_offset: error in FunD_New\n")); - } - - /* Notify the volume we're in tkreg space, so our transform is - correct. */ - volume_error = FunD_ClientSpaceIsTkRegRAS (func_timecourse_offset); - if (volume_error!=FunD_tErr_NoError) - { - if (NULL != volm) - Volm_Delete (&volm); - printf("surfer: couldn't load %s\n",fname); - ErrorReturn - (func_convert_error(volume_error), - (func_convert_error(volume_error), - "func_load_timecourse_offset: error in FunD_ClientSpaceIsTkRegRAS\n")); - } - - /* enable offset display */ - func_use_timecourse_offset = TRUE; - - printf("surfer: loaded timecourse offset %s\n",fname); - - /* turn on the offset options */ - send_tcl_command("Graph_ShowOffsetOptions 1"); - - if (NULL != volm) - Volm_Delete (&volm); - - return(ERROR_NONE); -} - -int func_select_selected_vertex() -{ - VERTEX* v = NULL; - char tcl_cmd[1024]; - - v = &(mris->vertices[selection]); - func_select_voxel (selection, v->origx,v->origy,v->origz); - - sprintf (tcl_cmd, "Graph_SetLabel \"VNO %d (%.2f, %.2f, %.2f)\"", - selection, v->origx, v->origy, v->origz); - send_tcl_command (tcl_cmd); - - return(ERROR_NONE); -} - -int func_select_marked_vertices() -{ - int vno, count; - VERTEX* v = NULL; - char tcl_cmd[1024]; - - count = 0; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &(mris->vertices[vno]); - if (v->marked) - { - func_select_voxel (vno, v->origx,v->origy,v->origz); - count++; - } - } - - sprintf (tcl_cmd, "Graph_SetLabel \"Averaging %d marked vertices\"", count); - send_tcl_command (tcl_cmd); - - printf("surfer: averaging %d marked vertices\n",count); - return(ERROR_NONE); -} - -int func_select_label() -{ - int n; - int count; - VERTEX* v = NULL; - LABEL* area; - char tcl_cmd[1024]; - - if (LABL_NONE_SELECTED == labl_selected_label) - { - sprintf (tcl_cmd, "Graph_SetLabel \"No label selected\""); - send_tcl_command (tcl_cmd); - printf ("surfer: No label selected.\n" ); - return (ERROR_BADPARM); - } - - count = 0; - area = labl_labels[labl_selected_label].label ; - for (n = 0 ; n < area->n_points ; n++) - { - if (area->lv[n].vno > 0 && area->lv[n].vno < mris->nvertices) - { - v = &mris->vertices[area->lv[n].vno] ; - func_select_voxel (area->lv[n].vno, v->origx, v->origy, v->origz); - count++; - } - } - - sprintf (tcl_cmd, "Graph_SetLabel \"Averaging label %s\"\n", - labl_labels[labl_selected_label].name); - send_tcl_command (tcl_cmd); - - printf("surfer: averaging label %s\"\n", - labl_labels[labl_selected_label].name); - return(ERROR_NONE); -} - -int func_clear_selection() -{ - xGArr_tErr array_error = xGArr_tErr_NoErr; - - if (func_selected_ras==NULL) - ErrorReturn(ERROR_NOT_INITED, - (ERROR_NOT_INITED, - "func_clear_selection: func_selected_ras is null\n")); - - /* clear our selection list */ - array_error = xGArr_Clear (func_selected_ras); - if (array_error!=xGArr_tErr_NoErr) - ErrorReturn(ERROR_ARRAY, - (ERROR_ARRAY, - "func_clear_selection: xGArr_Clear failed\n")); - - return(ERROR_NONE); -} - -int func_select_voxel (int vno, float x, float y, float z) -{ - xGArr_tErr array_error = xGArr_tErr_NoErr; - FUNC_SELECTED_VOXEL voxel; - - if (func_selected_ras==NULL) - ErrorReturn(ERROR_NOT_INITED, - (ERROR_NOT_INITED, - "func_select_voxel: func_selected_ras is null\n")); - - /* build a voxel */ - voxel.vno = vno; - voxel.x = x; - voxel.y = y; - voxel.z = z; - - /* add this voxel to the list */ - array_error = xGArr_Add (func_selected_ras, &voxel); - if (array_error!=xGArr_tErr_NoErr) - ErrorReturn(ERROR_ARRAY, - (ERROR_ARRAY, - "func_select_voxel: xGArr_Add failed\n")); - - return(ERROR_NONE); -} - -int func_graph_timecourse_selection () -{ - - int cond; - int tp; - int num_good_voxels; - float* values; - float* deviations; - char* tcl_cmd; - int tcl_cmd_size; - FunD_tErr func_error = FunD_tErr_NoError; - float second; - - /* make sure we have a volume */ - if (func_timecourse==NULL) - { - printf ("surfer: time course not loaded\n"); - return (ERROR_NONE); - } - - /* make sure the graph window is open. */ - send_tcl_command ("Graph_ShowWindow"); - - /* allocate storage arrays. */ - values = calloc (func_num_timepoints,sizeof(float)); - if (values==NULL) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "func_graph_timecourse_selection: " - "calloc(%d,float) failed for values\n", - func_num_timepoints)); - deviations = calloc (func_num_timepoints,sizeof(float)); - if (deviations==NULL) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "func_graph_timecourse_selection: " - "calloc(%d,float) failed for deviations\n", - func_num_timepoints)); - - /* allocate the argument string. */ - tcl_cmd_size = (func_num_timepoints * knLengthOfGraphDataItem) + - knLengthOfGraphDataHeader; - tcl_cmd = (char*)malloc(sizeof(char)*tcl_cmd_size); - if (tcl_cmd==NULL ) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "func_graph_timecourse_selection: " - "failed to alloc %d char string\n",tcl_cmd_size)); - - /* clear the graph so if nothing draws, we won't have any old stuff there. */ - send_tcl_command ("Graph_ClearGraph"); - send_tcl_command ("Graph_BeginData"); - - /* for each condition... */ - for (cond=0;cond0) - { - /* write the cmd name, condition number and first brace */ - sprintf (tcl_cmd, "Graph_SetPointsData %d {", cond); - - /* for each time point... */ - for (tp=0; tp < func_num_timepoints; tp++) - { - - /* convert to a second. If this is a - mriFunctionalDataRef, let it convert for us, using TR - if present, otherwise our second is just our time - point. */ - if (func_timecourse) - { - func_error = - FunD_ConvertTimePointToSecond - (func_timecourse, tp, &second); - if (func_error!=FunD_tErr_NoError) - ErrorPrintf(func_convert_error(func_error), - "func_graph_timecourse_selection: " - "error in FunD_ConvertTimePointToSecond " - "tp=%d\n",tp); - } - - /* write the second and value to the arg list */ - sprintf (tcl_cmd, "%s %1.1f %2.5f", tcl_cmd, second, values[tp]); - } - - /* write the last brace and send the cmd. */ - sprintf (tcl_cmd, "%s}", tcl_cmd); - send_tcl_command (tcl_cmd); - - /* send the error bars. write the cmd name. */ - sprintf (tcl_cmd, "Graph_SetErrorData %d {", cond); - - /* for each time point, write the deviation value. */ - for (tp=0; tp < func_num_timepoints; tp++) - sprintf (tcl_cmd, "%s %2.5f", tcl_cmd, deviations[tp]); - - /* write the last brace and send the cmd. */ - sprintf (tcl_cmd, "%s}", tcl_cmd); - send_tcl_command (tcl_cmd); - } - } - - send_tcl_command ("Graph_EndData"); - - return(ERROR_NONE); -} - -int func_print_timecourse_selection (char* fname) -{ - FILE* fp = NULL; - int cond; - int tp; - int num_good_voxels; - float* values = NULL; - float* deviations; - - if (fname==NULL) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "func_print_timecourse_selection: file name was null\n")); - - /* make sure we have a volume */ - if (func_timecourse==NULL) - ErrorReturn(ERROR_NOT_INITED, - (ERROR_NOT_INITED, - "func_print_timecourse_selection: No timecourse volume.\n")); - - /* allocate storage arrays. */ - /* allocate storage arrays. */ - values = calloc (func_num_timepoints,sizeof(float)); - if (values==NULL) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "func_print_timecourse_selection: " - "calloc(%d,float) failed for values\n", - func_num_timepoints)); - - deviations = calloc (func_num_timepoints,sizeof(float)); - if (deviations==NULL) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "func_print_timecourse_selection: " - "calloc(%d,float) failed for deviations\n", - func_num_timepoints)); - - fp = fopen (fname, "w"); - if (fp==NULL) - ErrorReturn(ERROR_NOFILE, - (ERROR_NOFILE, - "func_print_timecourse_selection: " - "file %s couldn't be opened\n", fname)); - - /* get the num of conditions. for each one... */ - FunD_GetNumConditions (func_timecourse,&func_num_conditions); - for (cond=0;cond0) - for (tp=0;tp= mris->nvertices) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "surfer: Please select a vertex.\n")); - - /* Initialize our field. */ - sprintf (label, "Corrltn %d", selection_vno); - sclv_new_empty (field, label); - - /* Build the voxel for the selected point. If it's scalar, our index - is vno,0,0, otherwise use the orig coords. */ - if (func_is_scalar_volume) - xVoxl_Set (&selection_voxel, selection_vno, 0, 0); - else - { - v = &mris->vertices[selection_vno]; - xVoxl_SetFloat (&selection_voxel, v->origx, v->origy, v->origz); - } - - /* Calc the number of frames. */ - nframes = (func_num_conditions * func_num_timepoints); - - /* For every vertex... */ - min = 1000000000; - max = -min; - for (vno = 0; vno < mris->nvertices; vno++) - { - v = &mris->vertices[vno]; - - /* If it's scalar, our index is vno,0,0, otherwise use the - orig coords. */ - if (func_is_scalar_volume) - xVoxl_Set (&cur_voxel, vno, 0, 0); - else - xVoxl_SetFloat (&cur_voxel, v->origx, v->origy, v->origz); - - num = d1 = d2 = cor = 0.0; - for (cond=0; cond < func_num_conditions; cond++) - { - for (tp=0; tp < func_num_timepoints; tp++) - { - - /* Get the value at the selection point and the current - point. This will return an error if it's a spatial - volume and these coords are out of bounds. */ - func_error = FunD_GetData( func_timecourse, - &selection_voxel, cond, tp, &val1 ); - if (func_error!=FunD_tErr_NoError ) - { - continue; - } - func_error = FunD_GetData( func_timecourse, - &cur_voxel, cond, tp, &val2 ); - if (func_error!=FunD_tErr_NoError ) - { - continue; - } - - /* Math stuff */ - cor += (val1-val2)*(val1-val2); - num += val1*val2; - d1 += (val1*val1); - d2 += (val2*val2); - } - } - - /* Calculation the correlation. */ - cor = 1 - (sqrt(cor/nframes)); - cor = (num/nframes) / sqrt((d1/nframes)*(d2/nframes)); - - /* Set the value in the field. */ - sclv_set_value(v, field, cor); - - /* Update the min and max. */ - if (cor < min) - min = cor; - if (cor > max) - max = cor; - } - - /* Set the min and max. */ - sclv_value_min = sclv_field_info[field].min_value = min; - sclv_value_max = sclv_field_info[field].max_value = max; - - /* Set the threshold so we go from -1 -> 1 */ - fthresh = sclv_field_info[field].fthresh = 0; - fmid = sclv_field_info[field].fmid = 0.5; - fslope = sclv_field_info[field].fslope = 1; - - /* Calc the frquencies */ - sclv_calc_frequencies (field); - - /* Request a redraw. Turn on the overlay flag and select this value - set. */ - vertex_array_dirty = 1 ; - overlayflag = TRUE; - sclv_set_current_field (field); - - return (ERROR_NONE); -} - -int func_normalize () -{ - FunD_tErr func_error = FunD_tErr_NoError; - - /* make sure we have a volume */ - if (func_timecourse==NULL) - ErrorReturn(ERROR_NOT_INITED, - (ERROR_NOT_INITED, - "func_normalize: No timecourse volume.\n")); - - func_error = FunD_NormalizeOverAll( func_timecourse ); - if (func_error!=FunD_tErr_NoError) - ErrorPrintf(func_convert_error(func_error), - "func_normalize: error in FunD_NormalizeOverAll"); - - return(ERROR_NONE); -} - - -int func_convert_error (FunD_tErr volume_error) -{ - int error = ERROR_NONE; - switch (volume_error) - { - case FunD_tErr_PathNotFound: - case FunD_tErr_CouldntGuessStem: - case FunD_tErr_DataNotFound: - case FunD_tErr_HeaderNotFound: - case FunD_tErr_UnrecognizedHeaderFormat: - case FunD_tErr_QuestionableHeaderFormat: - case FunD_tErr_CouldntDetermineDataType: - error = ERROR_NOFILE; - break; - case FunD_tErr_CouldntAllocateVolume: - case FunD_tErr_CouldntAllocateStorage: - case FunD_tErr_CouldntAllocateMatrix: - error = ERROR_NO_MEMORY; - break; - default: - error = ERROR_FUNC; - break; - } - return(error); -} -/* ---------------------------------------------------------------------- */ - -/* --------------------------------------------------- scalar value mgmnt */ - -int sclv_initialize () -{ - int field; - - /* no layers loaded, clear all the stuff. */ - for (field = 0; field < NUM_SCALAR_VALUES; field++) - { - sclv_field_info[field].is_functional_volume = FALSE; - sclv_field_info[field].is_scalar_volume = FALSE; - sclv_field_info[field].cur_timepoint = -1; - sclv_field_info[field].cur_condition = -1; - sclv_field_info[field].func_volume = NULL; - sclv_field_info[field].fthresh = fthresh; - sclv_field_info[field].fmid = fmid; - sclv_field_info[field].foffset = foffset; - sclv_field_info[field].fslope = fslope; - } - - return (ERROR_NONE); -} - -int sclv_unload_field (int field) -{ - - FunD_tErr volume_error; - - if (field < 0 || field > NUM_SCALAR_VALUES) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_unload_field: field was out of bounds: %d)",field)); - - /* if we have a binary volume, delete it */ - if (sclv_field_info[field].is_functional_volume && - sclv_field_info[field].func_volume != NULL ) - { - volume_error = FunD_Delete (&(sclv_field_info[field].func_volume)); - if (volume_error!=FunD_tErr_NoError) - ErrorReturn(func_convert_error(volume_error), - (func_convert_error(volume_error), - "sclv_unload_field: error in FunD_Delete\n")); - - sclv_field_info[field].is_functional_volume = FALSE; - - /* force a repaint next load */ - sclv_field_info[field].cur_timepoint = -1; - sclv_field_info[field].cur_condition = -1; - } - - return (ERROR_NONE); -} - -int -sclv_calc_frequencies(int field) -{ - int timepoint, condition; - float* values; - int bin; - float num_values; - int vno; - float valPerBin; - - if (field < 0 || field > NUM_SCALAR_VALUES) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_unload_field: field was out of bounds: %d)",field)); - - sclv_field_info[field].num_freq_bins = SCLV_NUM_FREQUENCY_BINS; - - /* get the value range. */ - num_values = (sclv_field_info[field].max_value - - sclv_field_info[field].min_value); - valPerBin = num_values / (float)sclv_field_info[field].num_freq_bins; - - /* allocate storage for each time point and condition... */ - if (NULL != sclv_field_info[field].frequencies) - free (sclv_field_info[field].frequencies); - - sclv_field_info[field].frequencies = - calloc( sclv_field_info[field].num_conditions, sizeof(int**) ); - - values = (float*) calloc( mris->nvertices, sizeof(float) ); - if (values == NULL) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "sclv_calc_frequencies: couldn't allocate values storage.")); - - /* Calc the zero bin and save it. */ - sclv_field_info[field].zero_bin_index = - (float)(0 - sclv_field_info[field].min_value) / (float)valPerBin; - sclv_field_info[field].num_zeroes_in_zero_bin = 0; - - for (condition = 0; - condition < sclv_field_info[field].num_conditions; condition++) - { - sclv_field_info[field].frequencies[condition] = - calloc( sclv_field_info[field].num_timepoints, sizeof(int*) ); - - for (timepoint = 0; - timepoint < sclv_field_info[field].num_timepoints; timepoint++) - { - - /* allocate an array of num_freq_bins ints */ - sclv_field_info[field].frequencies[condition][timepoint] = - calloc( sclv_field_info[field].num_freq_bins, sizeof(int) ); - - /* Get the values at this timepoint and condition. */ - sclv_get_values_for_field_and_timepoint (field, timepoint, condition, - values); - - /* for each vno, find the bin the value should go in and inc - the count in that bin. */ - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - if (values[vno] != 0) - { - bin = - (float)(values[vno] - - sclv_field_info[field].min_value) \ - / (float)valPerBin; - if (bin >= 0 && bin < sclv_field_info[field].num_freq_bins) - sclv_field_info[field].\ - frequencies[condition][timepoint][bin]++; - } - else - { - /* This is a zero so inc the number of zeroes. */ - sclv_field_info[field].num_zeroes_in_zero_bin++; - } - } - } - } - - free (values); - - return (ERROR_NONE); -} - -int sclv_set_overlay_alpha (double alpha) -{ - if (alpha < 0 || alpha > 1.0) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_set_overlay_alpha: alpha must be 0-1")); - - sclv_overlay_alpha = alpha; - - return (ERROR_NONE); -} - -int sclv_set_current_field (int field) -{ - if (field < 0 || field > NUM_SCALAR_VALUES) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_set_current_field: field was out of bounds: %d)", - field)); - - if (gd_fnames[field]) - { - char tcl_cmd[STRLEN]; - sprintf(tcl_cmd, "GDF_Load %s\n", gd_fnames[field]) ; - send_tcl_command (tcl_cmd); -// gdfs[i] = gdfRead(fsgd_fnames[i], 1) ; - } - - /* save the current threshold */ - sclv_field_info[sclv_current_field].fthresh = fthresh; - sclv_field_info[sclv_current_field].fmid = fmid; - ; - sclv_field_info[sclv_current_field].foffset = foffset; - ; - sclv_field_info[sclv_current_field].fslope = fslope; - sclv_field_info[sclv_current_field].cur_condition = sclv_cur_condition; - sclv_field_info[sclv_current_field].cur_timepoint = sclv_cur_timepoint; - - /* update the field */ - sclv_current_field = field; - - /* set the shared vars. */ - fthresh = sclv_field_info[sclv_current_field].fthresh; - fmid = sclv_field_info[sclv_current_field].fmid; - ; - foffset = sclv_field_info[sclv_current_field].foffset; - ; - fslope = sclv_field_info[sclv_current_field].fslope; - sclv_cur_condition = sclv_field_info[sclv_current_field].cur_condition; - sclv_cur_timepoint = sclv_field_info[sclv_current_field].cur_timepoint; - sclv_num_timepoints = sclv_field_info[sclv_current_field].num_timepoints; - sclv_num_conditions = sclv_field_info[sclv_current_field].num_conditions; - sclv_value_min = sclv_field_info[sclv_current_field].min_value; - sclv_value_max = sclv_field_info[sclv_current_field].max_value; - - /* send the info for this field */ - sclv_send_current_field_info (); - - return (ERROR_NONE); -} - -int sclv_send_current_field_info () -{ - - char cmd[1024]; - - /* printf("sending info for field=%d\n\tmin=%f - max=%f\n\tfthresh=%f fmid=%f fslope=%f\n\ttp=%d cn=%d - ntps+%d ncns=%d\n", sclv_current_field, sclv_value_min, - sclv_value_max, fthresh, fmid, fslope, sclv_cur_timepoint, - sclv_cur_condition, sclv_num_timepoints, sclv_num_conditions); */ - - /* Send the current histogram info here as well. */ - sclv_send_histogram (sclv_current_field); - - sprintf(cmd, "set gaLinkedVar(fslope) %f", fslope); - sprintf(cmd, "set gaLinkedVar(fmid) %f", fmid); - sprintf(cmd, "set gaLinkedVar(fthreshmax) %f", fthreshmax); - sprintf(cmd, "set gaLinkedVar(fthresh) %f", fthresh); - sprintf (cmd, "UpdateLinkedVarGroup overlay"); - send_tcl_command (cmd); - sprintf (cmd, "OverlayLayerChanged"); - send_tcl_command (cmd); - - return (ERROR_NONE); -} - -int sclv_set_timepoint_of_field (int field, - int timepoint, int condition) -{ - int vno; - VERTEX* v; - float* values; - - if (field < 0 || field > NUM_SCALAR_VALUES) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_set_timepoint_of_field: field was out of bounds: %d)", - field)); - - /* check if this field has a binary volume */ - if (sclv_field_info[field].is_functional_volume == FALSE) - { - /* commented out because tksurfer.tcl will call this function - even when there is a .w file in this layer. */ - /* ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_set_timepoint_of_field: " - "field %d doesn't have a binary volume",field)); */ - return (ERROR_NONE); - } - - /* make sure it actually has one */ - if ((sclv_field_info[field].is_functional_volume && - sclv_field_info[field].func_volume == NULL)) - { - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_set_timepoint_of_field: " - "field %d thinks it has a binary volume " - "but doesn't really",field)); - } - - if (timepoint < 0 || timepoint > sclv_field_info[field].num_timepoints) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_set_timepoint_of_field: " - "timepoint was out of bounds: %d (max %d)", - timepoint, sclv_field_info[field].num_timepoints)); - if (condition < 0 || condition > sclv_field_info[field].num_conditions) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_set_timepoint_of_field: " - "condition was out of bounds: %d",condition)); - - /* check the timepoint and condition. if they're not what we're already - using...*/ - if (timepoint != sclv_field_info[field].cur_timepoint || - condition != sclv_field_info[field].cur_condition ) - { - values = (float*) calloc (mris->nvertices, sizeof(float)); - if (values == NULL) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY, - "sclv_set_timepoint_of_field: " - "couldn't allocate values storage.")); - - /* Get the values here. */ - sclv_get_values_for_field_and_timepoint (field, timepoint, condition, - values); - - /* For each vertex, set the value.. */ - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - sclv_set_value (v, field, values[vno]); - } - - /* save the timepoint and condition. */ - sclv_field_info[field].cur_timepoint = timepoint; - sclv_field_info[field].cur_condition = condition; - - /* send the info for the current field */ - if (field == sclv_current_field) - sclv_send_current_field_info(); - - free (values); - } - - /* This is kind of a hack to update the caption in case it has time - point and condition codes in it. Otherwise it won't get updated - until we click a vertex. */ - update_labels (LABELSET_CURSOR, selection, 0); - - return (ERROR_NONE); -} - -int sclv_get_values_for_field_and_timepoint (int field, int timepoint, - int condition, float* values) -{ - int vno; - VERTEX* v; - xVoxel voxel; - FunD_tErr volume_error; - float func_value; - - if (field < 0 || field > NUM_SCALAR_VALUES) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_get_values_for_field_and_timepoint: " - "field was out of bounds: %d)",field)); - - /* Check timepoint and condition */ - if (timepoint < 0 || timepoint > sclv_field_info[field].num_timepoints) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_get_values_for_field_and_timepoint: " - "timepoint was out of bounds: %d",timepoint)); - if (condition < 0 || condition > sclv_field_info[field].num_conditions) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_get_values_for_field_and_timepoint: " - "condition was out of bounds: %d",condition)); - - /* Make sure we have some output. */ - if (values == NULL ) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_get_values_for_field_and_timepoint: " - "values was NULL")); - - DisableDebuggingOutput; - - /* for each vertex, grab a value out of the volume and stick it - in the field */ - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - - /* skip ripped verts */ - if (v->ripflag) - { - values[vno] = 0; - continue; - } - - /* Get value from the right volume. */ - if (sclv_field_info[field].is_functional_volume && - sclv_field_info[field].func_volume ) - { - - /* If it's scalar, our index is vno,0,0, otherwise use the - orig coords. */ - if (sclv_field_info[field].is_scalar_volume) - { - xVoxl_Set (&voxel, vno, 0, 0); - } - else - { - xVoxl_SetFloat (&voxel, v->origx, v->origy, v->origz); - } - - /* If the voxel is valid here, use the value, else set - to 0. */ - volume_error = FunD_GetData(sclv_field_info[field].func_volume, - &voxel, condition, timepoint, - &func_value); - if (volume_error == FunD_tErr_NoError) - { - values[vno] = func_value; - } - else - { - values[vno] = 0; - } - } - else - { - /* There is no volume so we can just copy the proper sclv - field value into our output. */ - sclv_get_value (v, field, &values[vno] ); - } - } - EnableDebuggingOutput; - - return (ERROR_NONE); -} - - -int sclv_set_current_threshold_from_percentile (float thresh, float mid, - float max) -{ - HISTOGRAM *h ; - int bthresh, bmid, bmax ; - float thresh_value, mid_value, max_value, slope ; - - h = MRISgetHistogram(mris, 1000, sclv_current_field); - if (ignorezeroesinhistogramflag) - HISTOclearZeroBin(h) ; - HISTOmakeCDF(h, h) ; - if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) - HISTOplot(h, "h.plt") ; - bthresh = HISTOfindBinWithCount(h, thresh) ; - bmid = HISTOfindBinWithCount(h, mid) ; - bmax = HISTOfindBinWithCount(h, max) ; - thresh_value = h->bins[bthresh] ; mid_value = h->bins[bmid] ; max_value = h->bins[bmax] ; - if (FEQUAL(max_value, thresh_value)) - slope = 1.0 ; - else - slope = .5 / (max_value - mid_value) ; - if (thresh_value < 0) - { - sclv_field_info[sclv_current_field].foffset = foffset = thresh_value - (mid_value-thresh_value) ; - printf("setting foffset to %f\n", foffset) ; - thresh_value -= foffset ; - mid_value -= foffset ; - max_value -= foffset ; - printf("HISTO vals should be %f, %f, %f (slope = .5/(mx-md) = %2.2f)\n", - thresh_value, mid_value, max_value, slope) ; - } - else - { - - sclv_field_info[sclv_current_field].foffset = foffset = 0; - printf("HISTO vals should be %f, %f, %f (slope = .5/(mx-md) = %2.2f)\n", - thresh_value, mid_value, max_value, slope) ; - } - - - HISTOfree(&h) ; - fthresh = sclv_field_info[sclv_current_field].fthresh = thresh_value; - fmid = sclv_field_info[sclv_current_field].fmid = mid_value; - fslope = sclv_field_info[sclv_current_field].fslope = slope ; - fthreshmax = sclv_field_info[sclv_current_field].max_value = max_value ; - vertex_array_dirty = 1; -#if 0 - sclv_set_threshold_from_percentile(sclv_current_field, - thresh, mid, max); -#endif - - sclv_send_current_field_info(); - redraw() ; - - return (ERROR_NONE); -} - -int sclv_set_threshold_from_percentile (int field, float thresh, float mid, - float max) -{ - float thresh_value=0, mid_value=0, max_value=0; - - if (field < 0 || field >= NUM_SCALAR_VALUES) - return (ERROR_BADPARM); - if (thresh < 0 || thresh > 100.0) - return (ERROR_BADPARM); - if (mid < 0 || mid > 100.0) - return (ERROR_BADPARM); - if (max < 0 || max > 100.0) - return (ERROR_BADPARM); - - sclv_get_value_for_percentile (field, thresh, &thresh_value); - sclv_get_value_for_percentile (field, mid, &mid_value); - sclv_get_value_for_percentile (field, max, &max_value); - - printf("%2.2f --> %2.2f\n", thresh, thresh_value) ; - printf("%2.2f --> %2.2f\n", mid, mid_value) ; - printf("%2.2f --> %2.2f\n", max, max_value) ; - - sclv_field_info[field].fthresh = thresh_value; - sclv_field_info[field].fmid = mid_value; - if (max_value - mid_value < epsilon) - { - sclv_field_info[field].fslope = 1.0; - } - else - { - sclv_field_info[field].fslope = 1.0 / (max_value - mid_value); - } - - vertex_array_dirty = 1; - - printf ("fthresh %.2f fmid %.2f max %.2f slope %.2f\n", - thresh_value, mid_value, max_value, sclv_field_info[field].fslope); - - return (ERROR_NONE); -} - -int sclv_get_value_for_percentile (int field, float percentile, float* value) -{ - int target_count; - int bin, sum; - - if (field < 0 || field >= NUM_SCALAR_VALUES) - return (ERROR_BADPARM); - if (percentile < 0 || percentile > 100.0) - return (ERROR_BADPARM); - - target_count = (float)mris->nvertices * (percentile / 100.0); - - sum = 0; - bin = 0; - while (sum < target_count && bin < sclv_field_info[field].num_freq_bins) - { - sum += sclv_field_info[field].\ - frequencies[sclv_field_info[field].\ - cur_condition][sclv_field_info[field].\ - cur_timepoint][bin]; - bin++; - } - - *value = sclv_field_info[field].min_value + - ( ((sclv_field_info[field].max_value - - sclv_field_info[field].min_value + 1) * bin) \ - / sclv_field_info[field].num_freq_bins); - - return (ERROR_NONE); -} - -int sclv_set_threshold_using_fdr (int field, float rate, int only_marked) -{ - float *saved_val; - float *saved_val2; - float current_value=0; - double threshold; - int err; - int sign; - int *saved_undefval = NULL; - int vno; - int num_marked; - VERTEX* v; - - /* if they are truncating, they only want the positive or negative - values. if inverse is on, they want the negative values, else - they just want the positive. */ - sign = 0; - if (truncphaseflag) - { - if (invphaseflag) - sign = -1; - else - sign = 1; - } - - /* since the fdr function only works on val and overwrites val2, we - need to back up these fields, and then write our current field - into val. we'll restore everything later. */ - saved_val = (float*) calloc (mris->nvertices, sizeof(float)); - if (NULL == saved_val) - { - ErrorReturn(ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, - "sclv_set_threshold_using_fdr: " - "couldn't allocated saved_val array\n")); - } - saved_val2 = (float*) calloc (mris->nvertices, sizeof(float)); - if (NULL == saved_val2) - { - ErrorReturn(ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, - "sclv_set_threshold_using_fdr: " - "couldn't allocated saved_val2 array\n")); - } - for (vno = 0; vno < mris->nvertices; vno++) - { - /* save val and val2. */ - v = &mris->vertices[vno]; - sclv_get_value (v, SCLV_VAL, &saved_val[vno]); - sclv_get_value (v, SCLV_VAL2, &saved_val2[vno]); - - /* get the current value and put it into val. */ - sclv_get_value (v, field, ¤t_value); - sclv_set_value (v, SCLV_VAL, current_value); - } - - /* if we're only doing marked verts, go through the surface. save - undefval, set undefval to 1 if marked. */ - if (only_marked) - { - saved_undefval = (int*) calloc (mris->nvertices, sizeof(int)); - if (NULL == saved_undefval) - { - ErrorReturn(ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, - "sclv_set_threshold_using_fdr: " - "couldn't allocated saved_undefval array\n")); - } - num_marked = 0; - for (vno = 0; vno < mris->nvertices; vno++) - { - v = &mris->vertices[vno]; - saved_undefval[vno] = v->undefval; - if (v->marked) - { - v->undefval = 1; - num_marked++; - } - else - v->undefval = 0; - } - printf ("surfer: performing FDR on %d vertices\n", num_marked); - } - - /* call the fdr function. we pass our surface, the rate, the sign we - got before, only_marked for masked (we set undefval before), and - get the threshold back. */ - err = MRISfdr2vwth(mris, rate, sign, 1, only_marked, &threshold); - fprintf (stderr, "MRISfdr2vwth(rate=%f, sign=%d, 1, only_marked=%d) = %f\n", - rate, sign, only_marked, threshold); - if ( err ) - { - printf ("surfer: Error calculating threshold with FDR.\n"); - if (only_marked) free (saved_undefval); - return (err); - } - printf ("surfer: MRISfdr2vwth with rate %.2f and sign %d returned " - "threshold %f\n", rate, sign, threshold ); - - /* we we're only doing marked verts, go through and restore the - undefval values. */ - if (only_marked) - { - for (vno = 0; vno < mris->nvertices; vno++) - { - v = &mris->vertices[vno]; - v->undefval = saved_undefval[vno]; - } - free (saved_undefval); - } - - /* restore val and val2 */ - for (vno = 0; vno < mris->nvertices; vno++) - { - v = &mris->vertices[vno]; - sclv_set_value (v, SCLV_VAL, saved_val[vno]); - sclv_set_value (v, SCLV_VAL2, saved_val2[vno]); - } - free (saved_val); - free (saved_val2); - - sclv_field_info[field].fthresh = threshold; - sclv_field_info[field].fmid = threshold + 1.5; - sclv_field_info[field].fslope = 0.66; - - if (field == sclv_current_field) - { - fthresh = sclv_field_info[field].fthresh; - fmid = sclv_field_info[field].fmid; - fslope = sclv_field_info[field].fslope; - vertex_array_dirty = 1; - sclv_send_current_field_info(); - } - - return (ERROR_NONE); -} - -int sclv_copy_view_settings_from_field (int field, int fromfield) -{ - if (field < 0 || field >= NUM_SCALAR_VALUES) - return (ERROR_BADPARM); - if (fromfield < 0 || fromfield >= NUM_SCALAR_VALUES) - return (ERROR_BADPARM); - - /* if fromfield is the current field, update from the shared variables. */ - if (fromfield == sclv_current_field) - { - sclv_field_info[fromfield].fthresh = fthresh; - sclv_field_info[fromfield].fmid = fmid; - sclv_field_info[fromfield].foffset = foffset; - sclv_field_info[fromfield].fslope = fslope; - } - - sclv_field_info[field].fthresh = sclv_field_info[fromfield].fthresh; - sclv_field_info[field].fmid = sclv_field_info[fromfield].fmid; - sclv_field_info[field].foffset = sclv_field_info[fromfield].foffset; - sclv_field_info[field].fslope = sclv_field_info[fromfield].fslope; - - /* if this is the current field, update the shared variables and - send the current info. */ - if (field == sclv_current_field) - { - fthresh = sclv_field_info[sclv_current_field].fthresh; - fmid = sclv_field_info[sclv_current_field].fmid; - ; - foffset = sclv_field_info[sclv_current_field].foffset; - ; - fslope = sclv_field_info[sclv_current_field].fslope; - - sclv_send_current_field_info(); - } - - return (ERROR_NONE); -} - -int sclv_copy_view_settings_from_current_field (int field) -{ - sclv_copy_view_settings_from_field (field, sclv_current_field); - - return (ERROR_NONE); -} - -int sclv_copy_all_view_settings_from_current_field () -{ - int field; - - for (field = 0; field < NUM_SCALAR_VALUES; field++) - { - if (field != sclv_current_field) - sclv_copy_view_settings_from_field (field, sclv_current_field); - } - - return (ERROR_NONE); -} - -int sclv_swap_fields ( int fielda, int fieldb ) -{ - - SCLV_FIELD_INFO swap_field; - char cmd[STRLEN]; - int k; - float a, b; - a=0; - b=0; - - if (fielda < 0 || fielda >= NUM_SCALAR_VALUES) - return (ERROR_BADPARM); - if (fieldb < 0 || fieldb >= NUM_SCALAR_VALUES) - return (ERROR_BADPARM); - - /* swap the field values */ - for (k=0;knvertices;k++) - { - sclv_get_value(&(mris->vertices[k]), fielda, &a ); - sclv_get_value(&(mris->vertices[k]), fieldb, &b ); - sclv_set_value(&(mris->vertices[k]), fielda, b ); - sclv_set_value(&(mris->vertices[k]), fieldb, a ); - } - - /* swap the field data */ - swap_field = sclv_field_info[fielda]; - sclv_field_info[fielda] = sclv_field_info[fieldb]; - sclv_field_info[fieldb] = swap_field; - - /* swap the field names in the interface */ - sprintf (cmd, "SwapValueLabelNames %d %d", fielda, fieldb); - send_tcl_command (cmd); - - return (ERROR_NONE); -} - -int sclv_send_histogram ( int field ) -{ - - float increment; - char *tcl_cmd; - int condition, timepoint; - int bin; - int count; - - /* calculate the number of values and the increment between - each value */ - increment = - (sclv_field_info[field].max_value - sclv_field_info[field].min_value) / - (float)(sclv_field_info[field].num_freq_bins); - - /* start a string of the proper size; give us the length of the - command, and then 10 characters per number, begin + end + - increment + num values */ - // Careful -- tcl_cmd string len can easily exceed STRLEN - tcl_cmd = (char*)calloc(21 + (sclv_field_info[field].num_freq_bins + 4) * 10, - sizeof(char)); - if (NULL == tcl_cmd) - { - return (ERROR_NO_MEMORY); - } - - /* add the command name to the string, the min value, the max value, - the number of values, and the increment */ - sprintf (tcl_cmd, "UpdateHistogramData %.5f %.5f %.5f %d {", - sclv_field_info[field].min_value, sclv_field_info[field].max_value, - increment, sclv_field_info[field].num_freq_bins); - - /* for each frequency bin, add the value. */ - condition = sclv_field_info[field].cur_condition; - timepoint = sclv_field_info[field].cur_timepoint; - for (bin = 0; bin < sclv_field_info[field].num_freq_bins; bin++) - { - count = sclv_field_info[field].frequencies[condition][timepoint][bin]; - - /* If this is the zero bin, switch on - ignorezeroesinhistogramflag to see whether or not we include - the count in there. If we are ignoring, don't include it, - otherwise add it in. */ - if (bin == sclv_field_info[field].zero_bin_index) - { - if (!ignorezeroesinhistogramflag) - count += sclv_field_info[field].num_zeroes_in_zero_bin; - } - - /* Add to the command string. */ - sprintf (tcl_cmd, "%s %d", tcl_cmd, count); - } - - /* close up the command and send it off */ - strcat (tcl_cmd, "}"); - send_tcl_command (tcl_cmd); - - free (tcl_cmd); - - return (ERROR_NONE); -} - -int sclv_get_normalized_color_for_value (int field, float value, - float *outRed, - float *outGreen, - float *outBlue) -{ - GLubyte r, g, b; - get_color_vals (value, 0, REAL_VAL, &r, &g, &b); - *outRed = ((float)r / 255.0); - *outGreen = ((float)g / 255.0); - *outBlue = ((float)b / 255.0); - return (ERROR_NONE); -} - -int sclv_apply_color_for_value (float f, float opacity, - GLubyte* pr, GLubyte* pg, GLubyte* pb ) -{ - float r,g,b; - float ftmp,c1,c2; - float min, mid, max; - float or, ob, og; - float br, bg, bb; - float tmpoffset, f2, fr, fg, fb; - // extern double fcurv; // sets curv thresh - - /* Adjust by foffset. */ - f -= foffset; // foffset default is 0 (can be changed on gui) - - r = g = b = 0.0f ; - if (invphaseflag) f = -f; - if (truncphaseflag && f<0) f = 0; - if (rectphaseflag) f = fabs(f); - - /* rkt: same way values are calc'd in tkmedit. The main difference - is that max is 0.5/slope + mid instead of 1/slope + mid, to make - the linear version work better. */ - min = (float)(fthresh); - mid = (float)(fmid); - max = (0.5 / (float)fslope) + (float)fmid; - - /* Calculate the background colors. */ - br = (float)*pr / 255.0; - bg = (float)*pg / 255.0; - bb = (float)*pb / 255.0; - - // Apparently, fcurv is always 0, which would mean this - // section of code does nothing (dng) - if (fabs(f)>fthresh && fabs(f)=0){ - if(sclv_opaque){ - /* If opaque, don't use blending at all. Min->mid is all - red, and mid->max gets yellower. Who decided that this - was a good idea? */ - // br,bg,bb are background values - // f0 AND f= min){ - ftmp = (f-min)/(max-min); // normalize - dngheat(ftmp, &r, &g, &b); - } else { - r=br; g=bg; b=br; - } - } - else{ - /* the offset is a portion of the color that is 'blended' - into the functional color so that a func value right at - the threshold doesn't look black, but translucent. the - rest is a standard interpolated color scale. */ - or = br * ((f= min){ - ftmp = (f-min)/(max-min); // normalize - dngheat(-ftmp, &r, &g, &b); - } else { - r=br; g=bg; b=br; - } - } - else - { - or = br * ((f1)?1:f); - set_positive_color(f2,&fr,&fg,&fb,tmpoffset); - r=fr; - g=fg; - b=fb; - } - } - else if (colscale==BLUE_TO_RED_SIGNED || - colscale==GREEN_TO_RED_SIGNED) - { - tmpoffset = (float)*pr; - if (fabs(f)>fthresh) - { - if (fslope!=0) - { - if (fmid==0) - f2 = tanh(fslope*(f)); - else - { - if (f<0) - f2 = -(tanh(fslope*fmid) + tanh(fslope*(-f-fmid)))/ - (2-tanh(fslope*fmid)); - else - f2 = (tanh(fslope*fmid) + tanh(fslope*( f-fmid)))/ - (2-tanh(fslope*fmid)); - } - - } - else - { - f2 = (f<-1)?-1:((f>1)?1:f); - } - set_signed_color(f2,&fr,&fg,&fb,tmpoffset); - r=fr; - g=fg; - b=fb; - } - } - - /* Blend the color into the input color with the given opacity.*/ - *pr = (int)((1.0 - opacity) * (float)*pr) + (opacity * r); - *pg = (int)((1.0 - opacity) * (float)*pg) + (opacity * g); - *pb = (int)((1.0 - opacity) * (float)*pb) + (opacity * b); - - return (NO_ERROR); -} - - -int sclv_load_label_value_file (char *fname, int field) -{ - FILE* fp = NULL; - int line_number = 0; - char line[1024] = ""; - int num_read = 0; - char label_name[256] = ""; - float value = 0; - char hemisphere[256] = ""; - float min, max; - int label_index = 0; - LABEL* label = NULL; - int label_vno = 0; - int vno = 0; - VERTEX* v = NULL; - char val_name[1024]; - char cmd[1024]; - - /* unload this field if it already exists */ - sclv_unload_field (field); - - /* Go through the file line by line. */ - fp = fopen (fname, "r"); - if (NULL == fp) - { - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "sclv_load_label_value_file: " - "couldn't read file %s\n", fname)); - } - - line_number = 1; - min = 9999; - max = -9999; - while (!feof(fp)) - { - /* Read a label name, value, and hemisphere. */ - fgetl (line, 1024, fp); - num_read = sscanf (line, "%s %f %s", label_name, &value, hemisphere); - if (3 != num_read) - { - printf ("sclv_load_label_value_file: error reading line " - "%d: %s\n", line_number, line); - continue; - } - - /* If this is our hemisphere... */ - if (0 == strcmp (hemisphere, stem)) - { - - /* Update min/max. */ - if (value < min) - min = value; - if (value > max) - max = value; - - /* Go through the labels. If one's name matches this label name... */ - for (label_index = 0; label_index < labl_num_labels; label_index++) - { - if (0 == strcmp (labl_labels[label_index].name, label_name)) - { - label = labl_labels[label_index].label; - - /* Go through the label points and set the sclv to - this value. */ - for (label_vno = 0; label_vno < label->n_points; label_vno++) - { - vno = label->lv[label_vno].vno; - if ( vno < 0 || vno >= mris->nvertices ) - continue; - - v = &mris->vertices[vno]; - - sclv_set_value (v, field, value); - } - } - } - } - - line_number++; - } - - fclose (fp); - - - /* mark this field as not binary */ - sclv_field_info[field].is_functional_volume = FALSE; - sclv_field_info[field].is_scalar_volume = FALSE; - - /* save the range */ - sclv_field_info[field].min_value = min; - sclv_field_info[field].max_value = max; - - /* dummy info for time point and conditions, since .w files only have - one plane of info */ - sclv_field_info[field].cur_timepoint = 0; - sclv_field_info[field].cur_condition = 0; - sclv_field_info[field].num_timepoints = 1; - sclv_field_info[field].num_conditions = 1; - - /* calc the frquencies */ - sclv_calc_frequencies (field); - - /* request a redraw. turn on the overlay flag and select this value set */ - vertex_array_dirty = 1 ; - overlayflag = TRUE; - sclv_set_current_field (field); - - /* set the field name to the name of the file loaded */ - if (NULL != g_interp) - { - FileNameOnly (fname, val_name); - sprintf (cmd, "UpdateValueLabelName %d \"%s\"", field, val_name); - send_tcl_command (cmd); - sprintf (cmd, "ShowValueLabel %d 1", field); - send_tcl_command (cmd); - sprintf (cmd, "UpdateLinkedVarGroup view"); - send_tcl_command (cmd); - sprintf (cmd, "UpdateLinkedVarGroup overlay"); - send_tcl_command (cmd); - } - - /* enable the menu items */ - enable_menu_set (MENUSET_OVERLAY_LOADED, 1); - - return (ERROR_NONE); -} - -/* krish -- linktimepoint with ROI(avg or normalized avg ) mode */ -void link_timepoint_ROI(int vno) -{ - LABEL* area; - int n, current_vno, tmpvno; - float *values, *average, *stddev; - int label_index = -1; - int num_found; - - /* try and find the label corresponding to the clicked vertex number */ - labl_find_label_by_vno (vno, labl_selected_label+1, - &label_index, 1, &num_found); - /* idea is to get the list of vertices belonging to this label (area) */ - area = labl_labels[label_index].label ; - /* allocate memory for values and average*/ - values = (float*) calloc( mris->nvertices, sizeof(float) ); - average = (float*) calloc( mris->nvertices, sizeof(float) ); - stddev = (float*) calloc( mris->nvertices, sizeof(float) ); - if (values == NULL || average == NULL || stddev == NULL){ - printf("link_timepoint_ROI(): couldn't allocate one or more of values/average/stddev storage .\n"); - return; - } - /* for every vertex in the area ( label ) , get the associated timepoint values - * add them all to the average array ( also calculate variance)*/ - for (n = 0 ; n < area->n_points ; n++) - { - if (area->lv[n].vno > 0 && area->lv[n].vno < mris->nvertices) - { - current_vno = area->lv[n].vno ; - sclv_get_values_for_field_and_timepoint (sclv_current_field, current_vno, - sclv_cur_condition, values); - for (tmpvno=0; tmpvno < mris->nvertices; tmpvno++) - average[tmpvno] += values[tmpvno] / area->n_points; - /* calculate the variance */ - if (linkvertexmode == 3) - for (tmpvno=0; tmpvno < mris->nvertices; tmpvno++) - stddev[tmpvno] += pow(values[tmpvno]-average[tmpvno], 2); - } - } - - - /* in every vertex v, set average[vno] or stddev[vno] as the timepoint value */ - for (tmpvno = 0 ; tmpvno < mris->nvertices ; tmpvno++) - { - VERTEX *v; - v = &mris->vertices[tmpvno] ; - if (linkvertexmode == 2) - sclv_set_value(v, sclv_current_field, average[tmpvno] ); - if ( linkvertexmode == 3 ) { - stddev[tmpvno] = sqrt(stddev[tmpvno] / area->n_points); - if ( fabs(stddev[tmpvno]) < epsilon ) { - sclv_set_value(v, sclv_current_field, average[tmpvno] / stddev[tmpvno] ); - } - else { - sclv_set_value(v, sclv_current_field, average[tmpvno] ); - } - } - } - - free(values); - free(average); - free(stddev); - send_tcl_command ("UpdateAndRedraw"); -} -/* ---------------------------------------------------------------------- */ - -/* ------------------------------------------------------ multiple labels */ - -int labl_initialize () -{ - - int label; - - /* initialize the array of labels to empty. */ - for (label = 0; label < LABL_MAX_LABELS; label++) - { - labl_labels[label].label = NULL; - labl_labels[label].structure = -1; - labl_labels[label].r = 0; - labl_labels[label].g = 0; - labl_labels[label].b = 0; - labl_labels[label].visible = 0; - labl_labels[label].border_vno = NULL; - labl_labels[label].num_border_vnos = 0; - labl_labels[label].cached = 0; - } - - labl_num_labels = 0; - labl_selected_label = LABL_NONE_SELECTED; - labl_ctab = NULL; - //labl_draw_style = LABL_STYLE_FILLED; // initiallized in declaration - labl_num_labels_created = 0; - labl_color_table_name = (char*) calloc (NAME_LENGTH, sizeof(char)); - labl_draw_flag = 1; - labl_cache = NULL; - labl_num_labels_at_cache_vno = NULL; - labl_cache_updated = FALSE; - - return (ERROR_NONE); -} - -int labl_update_cache (int force_rebuild_all) -{ - - int label_index; - LABEL* label; - int label_vno; - int vno; - int* new; - - /* if our basic stuff is not inited, do so now. */ - if (NULL == labl_cache) - { - labl_cache = (int**) calloc (mris->nvertices, sizeof(int*)); - } - if (NULL == labl_num_labels_at_cache_vno) - { - labl_num_labels_at_cache_vno = - (int*) calloc (mris->nvertices, sizeof(int)); - } - - if (force_rebuild_all) - { - for (vno = 0; vno < mris->nvertices; vno++) - labl_num_labels_at_cache_vno[vno] = 0; - } - - for (label_index = 0; label_index < labl_num_labels; label_index++) - { - label = labl_labels[label_index].label; - if (!labl_labels[label_index].cached || force_rebuild_all) - { - for (label_vno = 0; label_vno < label->n_points; label_vno++) - { - vno = label->lv[label_vno].vno; - if ( vno < 0 || vno >= mris->nvertices ) - continue; - - if (NULL == labl_cache[vno]) - { - labl_cache[vno] = (int*) calloc (1, sizeof(int)); - labl_cache[vno][0] = label_index; - labl_num_labels_at_cache_vno[vno] = 1; - } - else - { - new = (int*) - calloc (labl_num_labels_at_cache_vno[vno]+1, sizeof(int)); - memmove (new, labl_cache[vno], - labl_num_labels_at_cache_vno[vno] * sizeof(int)); - free (labl_cache[vno]); - labl_cache[vno] = new; - labl_cache[vno][labl_num_labels_at_cache_vno[vno]] = - label_index; - labl_num_labels_at_cache_vno[vno]++; - } - } - labl_labels[label_index].cached = TRUE; - } - } - - labl_cache_updated = TRUE; - - return (NO_ERROR); -} - -int labl_load_color_table (char* fname) -{ - COLOR_TABLE* ctab; - int label_index; - LABL_LABEL* label; - int r, g, b, a; - - /* Attempt to read the color table. */ - ctab = CTABreadASCII (fname); - if (NULL == ctab) - { - ErrorReturn(ERROR_BADFILE, (ERROR_BADFILE, "Couldn't open %s\n", fname)); - } - - /* Save it in the surface. */ - if (NULL != mris->ct) - { - CTABfree (&mris->ct); - } - mris->ct = ctab; - - /* save the name of the color table */ - strcpy (labl_color_table_name, fname); - - /* send the color table to tcl. */ - labl_send_color_table_info (); - - /* Update all currently loaded structural labels. */ - for (label_index = 0; label_index < labl_num_labels; label_index++) - { - label = &(labl_labels[label_index]); - if (LABL_TYPE_FREE != label->structure) - { - CTABcopyName (mris->ct, label->structure, - label->name, sizeof(label->name)); - r = 255; - g = b = 0; - a = 255; - CTABrgbaAtIndexi (mris->ct, label->structure, &r, &g, &b, &a); - labl_set_color (label_index, r, g, b); - labl_set_alpha (label_index, a); - labl_send_info (label_index); - } - } - - redraw(); - - return (ERROR_NONE); -} - -int -labl_send_color_table_info () -{ - COLOR_TABLE* ctab; - int num_valid_entries; - int num_entries; - int structure; - char structure_label[1024]; - char* structure_label_list = NULL; - int valid; - - /* if we have our own table, get the names from there, otherwise - use our external table. */ - if (NULL != mris->ct) - ctab = mris->ct; - else - ctab = labl_ctab; - - /* Find out how many valid and total entries we have. */ - CTABgetNumberOfValidEntries (ctab, &num_valid_entries); - CTABgetNumberOfTotalEntries (ctab, &num_entries); - - /* allocate a string long enough for the update command and all - our labels. */ - structure_label_list = (char*) - malloc (256 * num_valid_entries * sizeof(char)); - if (NULL != structure_label_list) - { - /* build a string out of all the label names and send them to the - tcl label list. */ - strcpy (structure_label_list, "LblLst_SetStructures {"); - - /* Iterate over all the entries, but only get names for the - valid ones. */ - for (structure = 0; structure < num_entries; structure++ ) - { - /* If not valid, skip it. */ - CTABisEntryValid (ctab, structure, &valid); - if (!valid) - continue; - - CTABcopyName (ctab, structure, - structure_label, sizeof(structure_label)); - sprintf (structure_label_list, "%s %d %s", - structure_label_list, structure, structure_label); - } - sprintf (structure_label_list, "%s }", structure_label_list); - send_tcl_command (structure_label_list); - - free( structure_label_list ); - } - else - { - fprintf (stderr, "labl_send_color_table_info: couldn't allocate " - "string for %d structres\n", labl_num_structures ); - return (ERROR_NO_MEMORY); - } - - return (NO_ERROR); -} - -int labl_load (char* fname) -{ - LABEL* label = NULL; - LABEL *lnew; - int label_index; - char name[NAME_LENGTH]; - int unassigned; - - if (white_surf_loaded == 0) - read_white_vertex_coordinates() ; - - if (NULL == fname) - return (ERROR_BADPARM); - - if (MRISfileNameType(fname) == MRIS_GIFTI_FILE) - { - printf("\n\n INFO: use File->Label->Import Annotation to load Gifti " - "format label files!\n\n"); - return(ERROR_NO_FILE); - } - - /* load label file. */ - label = LabelRead (pname, fname); - if (NULL == label) - { - return (ERROR_NO_FILE); - } - { - int n, nonzero = 0 ; - - for (n = 0 ; n < label->n_points ; n++) - if (!FZERO(label->lv[n].stat)) - nonzero++ ; - printf("******************** %d nonzero vertices found ********************\n", nonzero) ; - if (nonzero== 0) - { - printf("label stat field identically zero - setting to 1\n") ; - for (n = 0 ; n < label->n_points ; n++) - label->lv[n].stat = 1 ; - } - } - - if (reassign) - LabelUnassign(label) ; - - /* load the orig vertex positions if we haven't already. */ - if (!origsurfloaded) - read_orig_vertex_coordinates(orfname) ; - LabelToWhite (label, mris); - - /* See if the label is completely unassigned. If it is, we'll fill - it after we assign the verts. */ - LabelIsCompletelyUnassigned (label, &unassigned); - - /* assign mris vertex numbers to unnumbered vertices based on their - locations. */ - LabelFillUnassignedVertices (mris, label, WHITE_VERTICES); - - /* If we were unassigned before, fill it now. */ - if (unassigned) - { - lnew = LabelFillHoles(label, mris, WHITE_VERTICES) ; - LabelFree(&label) ; - label = lnew ; - } - - /* make a new entry in the label list. */ - labl_add (label, &label_index); - - /* set the name to the tail of the filename. make this a free label, - i.e. with no assigned strucutre. make it visible. */ - FileNameOnly (fname, name); - labl_set_info (label_index, name, LABL_TYPE_FREE, 1, - LABL_DEFAULT_COLOR_R, LABL_DEFAULT_COLOR_G, - LABL_DEFAULT_COLOR_B ); - - /* Unmark it. */ - LabelUnmark (label, mris); - - /* select this label */ - labl_select (label_index); - - surface_compiled = 0 ; - - - return (ERROR_NONE); -} - -int labl_save (int index, char* fname) -{ - LABEL* label = NULL; - int n; - int vno; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - if (NULL == fname) - return (ERROR_BADPARM); - - /* Get a copy of our label. */ - printf("label at index %d with %d points\n", - index, labl_labels[index].label->n_points) ; - label = LabelCopy (labl_labels[index].label, NULL); - if (NULL == label) - return (ERROR_BADPARM); - - /* read original vertex positions if we haven't already. */ - if (!origsurfloaded) - read_orig_vertex_coordinates(orfname) ; - - /* fill in the current overlay value in the stat field of our label - verts. this is for the LabelWrite call. */ - for (n = 0 ; n < label->n_points ; n++) - { - vno = label->lv[n].vno; - if ( vno < 0 || vno >= mris->nvertices ) - continue; - - sclv_get_value (&(mris->vertices[vno]), - sclv_current_field, &(label->lv[n].stat) ); - } - - /* write the label. */ - fprintf (stderr, "writing %d labeled vertices to %s.\n", - label->n_points, fname) ; - LabelToWhite (label, mris); - LabelWrite (label, fname); - - /* Delete the label. */ - LabelFree (&label); - - return (ERROR_NONE); -} - -int labl_save_all (char* prefix) -{ - int label; - char fname[NAME_LENGTH]; - - /* for each label we have, build a decent name based on the prefix - we got, and save it normally. */ - for (label = 0; label < labl_num_labels; label++ ) - { - sprintf (fname, "%s-%d", prefix, label); - labl_save (label, fname); - } - - return (ERROR_NONE); -} - - -int labl_find_and_set_all_borders () -{ - int label; - - /* for each label we have, find the border */ - for (label = 0; label < labl_num_labels; label++ ) - { - labl_find_and_set_border (label); - } - - return (ERROR_NONE); -} - -int labl_find_and_set_border (int index) -{ - int label_vno; - LABEL* label; - VERTEX* v; - int vno; - int neighbor_vno; - char* border = NULL; - int num_borders = 0; - int label_index_array[LABL_MAX_LABELS]; - int num_labels_found, found_label_index; - int vno_in_label, vno_in_other_label; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* make an array of border flags for just the outline. */ - border = (char*) calloc (mris->nvertices, sizeof(char)); - num_borders = 0; - - /* for each vertex in the label... */ - label = labl_labels[index].label; - for (label_vno = 0; label_vno < label->n_points; label_vno++) - { - /* The label vno could be < 0 if it couldn't find a close vertex - for this label point. */ - vno = label->lv[label_vno].vno; - if (vno < 0 || vno >= mris->nvertices) - continue; - - /* get the vno and look at this vertex in the mris. for each - neighbor, if we still haven't determined that this vno is a - border, the neighbor is not in the same label... */ - v = &(mris->vertices[vno]); - for (neighbor_vno = 0; - neighbor_vno < v->vnum && !border[vno]; - neighbor_vno++ ) - { - /* See if there's a label at this neighbor vno. */ - labl_find_label_by_vno (v->v[neighbor_vno], 0, label_index_array, - LABL_MAX_LABELS, &num_labels_found); - if ( num_labels_found > 0 ) - { - /* We found at least one label, check to see if it's - this label or somethign else. */ - vno_in_other_label = 0; - vno_in_label = 0; - for (found_label_index = 0; - found_label_index < num_labels_found; - found_label_index++) - { - if (label_index_array[found_label_index] != index) - vno_in_other_label = 1; - if (label_index_array[found_label_index] == index) - vno_in_label = 1; - } - - /* it's a border if this vno is in a different (or no) - label and not in this label. mark it so in the real - border flag array and our temp one. */ - if (vno_in_other_label && !vno_in_label && - !border[vno]) - { - border[vno] = TRUE; - num_borders++; - } - } - else - { - /* it's also a border if the vno is in no label. */ - border[vno] = TRUE; - num_borders++; - } - } - - /* Now we want to expand the border. If we determined this is a - border, check its surrounding vertices. For each one, if it's - not already also a border, and if it's inside the label, mark - it in the border list. */ - if (border[vno]) - { - for (neighbor_vno = 0; - neighbor_vno < v->vnum && !border[v->v[neighbor_vno]]; - neighbor_vno++ ) - { - /* If it's inside the label...*/ - labl_find_label_by_vno (v->v[neighbor_vno], 0, label_index_array, - LABL_MAX_LABELS, &num_labels_found); - if ( num_labels_found > 0 ) - { - for (found_label_index = 0; - found_label_index < num_labels_found; - found_label_index++) - { - if (label_index_array[found_label_index] == index && - !border[v->v[neighbor_vno]]) - { - /* Also make it a border. */ - border[v->v[neighbor_vno]] = TRUE; - num_borders++; - } - } - } - } - } - } - - /* Allocate the array on the label and go through the border array, - writing index numbers to the label array. */ - if (NULL != labl_labels[index].border_vno) - free (labl_labels[index].border_vno); - - labl_labels[index].border_vno = (int*) calloc (num_borders, sizeof(int)); - - labl_labels[index].num_border_vnos = 0; - for (label_vno = 0; label_vno < label->n_points; label_vno++) - { - vno = label->lv[label_vno].vno; - if (vno < 0 || vno >= mris->nvertices) - continue; - - v = &(mris->vertices[vno]); - if (border[vno]) - { - labl_labels[index].border_vno[labl_labels[index].num_border_vnos] = - vno; - labl_labels[index].num_border_vnos++; - - /* By unmarking it now, we make sure that a duplicate label - point will not also be added. */ - border[vno] = FALSE; - } - } - - free (border); - - return (ERROR_NONE); -} - -int labl_vno_is_border (int index, int vno) -{ - int border_index; - - if (index < 0 || index >= labl_num_labels) - return 0; - - if (NULL == labl_labels[index].border_vno) - return 0; - - for (border_index = 0; - border_index < labl_labels[index].num_border_vnos; border_index++) - { - if (labl_labels[index].border_vno[border_index] == vno) - return 1; - } - - return 0; -} - -int labl_import_annotation (char *fname) -{ - int mris_err; - int ctab_err; - COLOR_TABLE* ctab; - int annotation_vno; - int vno; - unsigned int annotation, max_annot; - int num_verts_in_annotation; - LABEL* label = NULL; - int label_vno; - VERTEX* v = NULL; - int new_index; - char name[NAME_LENGTH]; - int r, g, b; - int structure; - unsigned int* done; - int num_labels; - - /* init our done array. */ - r = g = b = 255; - MRISRGBToAnnot(r,g,b,max_annot); - done = (unsigned int*) calloc( max_annot, sizeof(int) ); - if ( NULL == done ) - { - printf( "calloc of size %d failed\n", max_annot ); - return (ERROR_NO_MEMORY); - } - num_labels = 0; - - /* read the annotation. */ - for (vno = 0; vno < mris->nvertices; vno++) - mris->vertices[vno].annotation = 0; - mris_err = MRISreadAnnotation (mris, fname); - if (mris_err) - { - printf("\n"); - printf("ERROR: could not load %s\n",fname); - printf("\n"); - return (ERROR_NO_FILE); - } - - /* Check if we got an embedded color table. */ - if (mris->ct) - { - printf ("Found embedded color table in annotation.\n"); - } - else - { - printf ("No embedded color table found in annotation.\n"); - } - - int vertices_wo_annotation = 0; // count vertices that dont have annotation - - /* check all annotations... */ - for (annotation_vno = 0; annotation_vno < mris->nvertices; annotation_vno++) - { - /* get the annotation. if there is one... */ - annotation = mris->vertices[annotation_vno].annotation; - - if (annotation) - { - /* get the rgb colors. */ - if (annotation > max_annot) - { - printf("Warning: vertex %d with annotation %x - out of range!\n", - annotation_vno, annotation) ; - annotation &= max_annot ; - } - MRISAnnotToRGB( annotation, r, g, b ); - - /* if we haven't imported this label yet... */ - if ( !done[annotation] ) - { - - /* mark it imported. */ - done[annotation] = 1; - num_labels++; - - /* find out how many verts have this annotation value. */ - num_verts_in_annotation = 0; - for (vno = 0; vno < mris->nvertices; vno++) - if (mris->vertices[vno].annotation == annotation) - num_verts_in_annotation++; - - /* make a new label, and go through again, setting the label - values. */ - label = LabelAlloc(num_verts_in_annotation, NULL, NULL); - if (NULL != label) - { - strncpy( label->subject_name, pname, 100 ); - label->n_points = num_verts_in_annotation; - label_vno = 0; - for (vno = 0; vno < mris->nvertices; vno++) - if (mris->vertices[vno].annotation == annotation) - { - v = &mris->vertices[vno]; - label->lv[label_vno].x = v->x; - label->lv[label_vno].y = v->y; - label->lv[label_vno].z = v->z; - label->lv[label_vno].vno = vno; - label_vno++; - } - - /* add the label to our list. */ - labl_add (label, &new_index); - - /* now we need to set the information about the - label from a color table. older parcellation - files use the external color table, but newer - ones have their own. so we'll check the ct - member; if it's null, use the external, otherwise - use the color info specified in the mris. */ - if (mris->ct) - ctab = mris->ct; - else - ctab = labl_ctab; - - /* If not found, structure will be -1. */ - CTABfindRGBi (ctab, r, g, b, &structure); - - /* make a name for it. if we got a color from the - color table, get the label, else use the color. */ - if (structure != -1) - { - ctab_err = CTABcopyName (ctab, structure, - name, sizeof(name) ); - if (NO_ERROR != ctab_err) - sprintf (name, "Parcellation %d, %d, %d", r, g, b); - } - else - { - sprintf (name, "Parcellation %d, %d, %d", r, g, b); - } - - /* set its other data. set the color; if we found a - structure index from the LUT, it will use that, - otherwise it will color it as a free label with - the given colors (which really has the same - effect, just doesn't give it a valid structure - index. */ - labl_set_info (new_index, name, structure, 1, r, g, b); - } - } - } - else - { - vertices_wo_annotation++; // vertex does not have annotation - } - } - - if (vertices_wo_annotation) - { - printf("%d vertices did not have an annotation!\n",vertices_wo_annotation); - } - - /* any labels imported? */ - if (num_labels > 0) - { - - /* if we have our own color table, now is the time to send it to the - tcl side of things. */ - if (mris->ct) - labl_send_color_table_info (); - - free (done); - - /* show the label label in the interface. */ - send_tcl_command ("ShowLabel kLabel_Label 1"); - labl_draw_flag = 1; - send_tcl_command ("UpdateLinkedVarGroup label"); - - } - else - { - printf ("surfer: WARNING: no labels imported; annotation was empty\n" ); - } - - return(ERROR_NONE); -} - -int labl_export_annotation (char *fname) -{ - int vno; - int label_index; - int color; - LABL_LABEL* label; - int label_vno; - - if (NULL == fname) - return (ERROR_BADPARM); - - for (vno = 0; vno < mris->nvertices; vno++) - mris->vertices[vno].annotation = 0; - - /* for each label.. */ - for (label_index = 0; label_index < labl_num_labels; label_index++) - { - - label = &(labl_labels[label_index]); - - /* if this is not a free label... */ - if ( LABL_TYPE_FREE != label->structure) - { - - /* make the composed color int for this label. */ - MRISRGBToAnnot (label->r, label->g, label->b, color); - - /* for every vertex in the label... */ - for (label_vno = 0; label_vno < label->label->n_points; label_vno++) - { - if ( label->label->lv[label_vno].vno < 0 || - label->label->lv[label_vno].vno >= mris->nvertices ) - continue; - - /* set the annotation value. */ - mris->vertices[label->label->lv[label_vno].vno].annotation = - color; - } - - if (labl_debug) - { - printf( "saved label %d with %d vertices, color %d %d %d " - "anot value %d\n", label_index, label->label->n_points, - label->r, label->g, label->b, color ); - } - } - } - - /* write out the annotation. */ - MRISwriteAnnotation (mris, fname); - - return (ERROR_NONE); -} - -int labl_new_from_marked_vertices (int *new_index_out) -{ - LABEL* label = NULL; - int num_marked_verts; - int vno; - int label_vno; - VERTEX* v = NULL; - int new_index; - char tcl_command[NAME_LENGTH + 50]; - float val = 0; - - /* count the number of marked vertices. */ - num_marked_verts = 0; - for (vno = 0 ; vno < mris->nvertices ; vno++) - if (mris->vertices[vno].marked) - num_marked_verts++; - - /* if we didn't get any, return. */ - if (0 == num_marked_verts) - { - fprintf (stderr, "no marked vertices...\n"); - return (ERROR_NONE); - } - - /* allocate a label. */ - label = LabelAlloc(num_marked_verts, NULL, NULL); - strncpy( label->subject_name, pname, 100 ); - - /* for every vertex, if it's marked, save its vertex coords, - index. don't fill the value of the current overlay, as that - should only be done when the label is actually written to - file. */ - label_vno = 0; - for (vno = 0; vno < mris->nvertices; vno++) - { - v = &mris->vertices[vno]; - if (v->marked) - { - sclv_get_value(v, sclv_current_field, &val) ; - label->lv[label_vno].x = v->x; - label->lv[label_vno].y = v->y; - label->lv[label_vno].z = v->z; - label->lv[label_vno].stat = val ; - label->lv[label_vno].vno = vno; - label_vno++; - } - } - label->n_points = num_marked_verts; - - /* convert to original positions. */ - if (!origsurfloaded) - read_orig_vertex_coordinates(orfname); - LabelToWhite (label, mris); - - /* add this label to our list. */ - labl_add (label, &new_index); - - /* select this label */ - labl_select (new_index); - - /* clear the marked verts. */ - clear_all_vertex_marks (); - - surface_compiled = 0 ; - - /* return the new index if they want it. */ - if (NULL != new_index_out) - *new_index_out = new_index; - - /* if the fill dlog is open, this will update it. */ - sprintf (tcl_command, "LabelsChanged"); - send_tcl_command (tcl_command); - - return (ERROR_NONE); -} - -int labl_add_marked_vertices_to_label (int index) -{ - int* vnos_to_add; - int* found_labels; - int in_label; - int num_found; - int found_label; - LABEL* curlabel = NULL; - LABEL* newlabel = NULL; - int num_marked_verts; - int num_label_verts; - int num_new_verts; - int curlabel_vno; - int newlabel_vno; - int vno; - VERTEX* v = NULL; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* Look at all the marked verts and find the ones that aren't - already in this label. Make a list of them. */ - vnos_to_add = (int*) calloc (mris->nvertices, sizeof(int)); - if (NULL == vnos_to_add) - { - return (ERROR_NO_MEMORY); - } - found_labels = (int*) calloc (LABL_MAX_LABELS, sizeof(int)); - if (NULL == found_labels) - { - free (vnos_to_add); - return (ERROR_NO_MEMORY); - } - num_marked_verts = 0; - for (vno = 0; vno < mris->nvertices; vno++) - { - v = &mris->vertices[vno]; - if (v->marked) - { - labl_find_label_by_vno (vno, 0, found_labels, - sizeof(found_labels), &num_found); - - in_label = FALSE; - if (num_found > 0) - for (found_label = 0; found_label < num_found; found_label++) - if (found_labels[found_label] == index) - in_label = TRUE; - - if (!in_label) - vnos_to_add[num_marked_verts++] = vno; - - } - } - free (found_labels); - - /* if we didn't get any, return. */ - if (0 == num_marked_verts) - { - free (vnos_to_add); - printf ("surfer: no marked vertices (that aren't already in the label)"); - return (ERROR_NONE); - } - - /* get the number of points in the label */ - curlabel = labl_labels[index].label; - num_label_verts = curlabel->n_points; - - /* create a new label with the combined number of points */ - num_new_verts = num_marked_verts + num_label_verts; - newlabel = LabelAlloc (num_new_verts, NULL, NULL); - if (NULL == newlabel) - { - free (vnos_to_add); - return (ERROR_NO_MEMORY); - } - - strncpy( newlabel->subject_name, pname, 100 ); - - /* add the label's points (note we're going through both the - curlabel and newlabel vnos in this loop */ - newlabel_vno = 0; - for (curlabel_vno = 0; curlabel_vno < curlabel->n_points; curlabel_vno++) - { - newlabel->lv[newlabel_vno].x = curlabel->lv[curlabel_vno].x; - newlabel->lv[newlabel_vno].y = curlabel->lv[curlabel_vno].y; - newlabel->lv[newlabel_vno].z = curlabel->lv[curlabel_vno].z; - newlabel->lv[newlabel_vno].vno = curlabel->lv[curlabel_vno].vno; - newlabel_vno++; - } - - /* add the marked verts */ - for (vno = 0; vno < num_marked_verts; vno++) - { - v = &mris->vertices[vnos_to_add[vno]]; - newlabel->lv[newlabel_vno].x = v->x; - newlabel->lv[newlabel_vno].y = v->y; - newlabel->lv[newlabel_vno].z = v->z; - newlabel->lv[newlabel_vno].vno = vnos_to_add[vno]; - newlabel_vno++; - } - newlabel->n_points = num_new_verts; - - /* delete the old label */ - LabelFree (&labl_labels[index].label); - - /* point to the newlabel in the labl structure */ - labl_labels[index].label = newlabel; - - /* update this label. */ - labl_changed (index, FALSE); - - free (vnos_to_add); - - return (ERROR_NONE); -} - -int labl_remove_marked_vertices_from_label (int index) -{ - - LABEL* curlabel = NULL; - LABEL* newlabel = NULL; - int num_marked_verts; - int num_label_verts; - int num_new_verts; - int curlabel_vno; - int newlabel_vno; - int vno; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* count the number of marked vertices. */ - num_marked_verts = 0; - for (vno = 0 ; vno < mris->nvertices ; vno++) - if (mris->vertices[vno].marked) - num_marked_verts++; - - /* if we didn't get any, return. */ - if (0 == num_marked_verts) - { - printf ("surfer: no marked vertices\n"); - return (ERROR_NONE); - } - - /* get the number of points in the label */ - curlabel = labl_labels[index].label; - num_label_verts = curlabel->n_points; - - /* calc the number of points in the new label. start with the same - num as the label. for each point in the label, see if it's marked - on the surface. if so, dec the count. */ - num_new_verts = num_label_verts; - for (curlabel_vno = 0; curlabel_vno < curlabel->n_points; curlabel_vno++) - { - vno = curlabel->lv[curlabel_vno].vno; - if ( vno < 0 || vno >= mris->nvertices ) - continue; - - if (mris->vertices[vno].marked) - { - num_new_verts--; - } - } - - /* if the count is the same as the original label, there were no - intersecting marked and label points. */ - if (num_new_verts == num_label_verts) - { - printf ("surfer: no intersection with label\n"); - return (ERROR_NONE); - } - - /* create a new label with the difference of points */ - newlabel = LabelAlloc (num_new_verts, NULL, NULL); - if (NULL == newlabel) - { - return (ERROR_NO_MEMORY); - } - - strncpy (newlabel->subject_name, pname, 100); - - /* for each of the labels verts, add it to the new label if the - corresponding surface vert is not marked. */ - newlabel_vno = 0; - for (curlabel_vno = 0; curlabel_vno < curlabel->n_points; curlabel_vno++) - { - vno = curlabel->lv[curlabel_vno].vno; - if ( vno < 0 || vno >= mris->nvertices ) - continue; - - if (!mris->vertices[vno].marked && newlabel_vno < num_new_verts) - { - newlabel->lv[newlabel_vno].x = curlabel->lv[curlabel_vno].x; - newlabel->lv[newlabel_vno].y = curlabel->lv[curlabel_vno].y; - newlabel->lv[newlabel_vno].z = curlabel->lv[curlabel_vno].z; - newlabel->lv[newlabel_vno].vno = curlabel->lv[curlabel_vno].vno; - newlabel_vno++; - } - } - newlabel->n_points = num_new_verts; - - /* delete the old label */ - LabelFree (&labl_labels[index].label); - - /* point to the newlabel in the labl structure */ - labl_labels[index].label = newlabel; - - /* recalc stuff */ - labl_changed (index, TRUE); - - return (ERROR_NONE); -} - -int labl_mark_vertices (int index) -{ - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* mark the verts. */ - LabelMark (labl_labels[index].label, mris); - - return (ERROR_NONE); -} - -int labl_select (int index) -{ - char tcl_command[NAME_LENGTH + 50]; - int old_selected; - /* mark this label as selected. */ - old_selected = labl_selected_label; - labl_selected_label = index; - - /* if something changed... */ - if (old_selected != labl_selected_label) - { - /* if something was selected, send the select cpmmand and the - update command to the tcl label list with this label's - information. */ - if ((index >= 0 && index < labl_num_labels) && g_interp) - { - sprintf (tcl_command, "LblLst_SelectLabel %d", index); - send_tcl_command (tcl_command); - - labl_send_info (index); - } - - /* redraw. */ - redraw (); - } - - return (ERROR_NONE); -} - -int labl_set_name_from_table (int index) -{ - char name[NAME_LENGTH]; - LABL_LABEL* label; - COLOR_TABLE* ctab; - int ctab_err; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - if (NULL == labl_ctab) - return (ERROR_NONE); - - label = &(labl_labels[index]); - - /* if the surface has a color table, use that to get the name, - otherwise use the external file. */ - if (mris->ct) - ctab = mris->ct; - else - ctab = labl_ctab; - - ctab_err = CTABcopyName (ctab, label->structure, name, sizeof(name)); - if (NO_ERROR == ctab_err) - labl_set_info (index, name, label->structure, label->visible, - label->r, label->g, label->b); - - return (ERROR_NONE); -} - -int labl_set_info (int index, char* name, int structure, int visible, - int ir, int ig, int ib) -{ - int ctab_err; - COLOR_TABLE* ctab; - int r, g, b, a; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - if (NULL == name) - return (ERROR_BADPARM); - if (0 != visible && 1 != visible) - return (ERROR_BADPARM); - - /* set the info in this label. */ - strncpy (labl_labels[index].name, name, NAME_LENGTH); - labl_labels[index].structure = structure; - labl_labels[index].visible = visible; - - /* if we have a table (in mris or external), and the structure is - not free, get the color from the table. otherwise, use the color - that they gave us. */ - if ((labl_ctab || mris->ct) && - LABL_TYPE_FREE != labl_labels[index].structure) - { - if (mris->ct) - ctab = mris->ct; - else - ctab = labl_ctab; - - ctab_err = CTABrgbaAtIndexi (ctab, structure, &r, &g, &b, &a); - if (NO_ERROR == ctab_err) - { - labl_set_color (index, r, g, b); - labl_set_alpha (index, a); - } - } - else - { - labl_set_color (index, ir, ig, ib); - labl_set_alpha (index, 255); - } - - /* send the label info to tcl */ - labl_send_info (index); - - return (ERROR_NONE); -} - -int labl_set_color (int index, int r, int g, int b) -{ - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) - return (ERROR_BADPARM); - - /* set the color */ - labl_labels[index].r = r; - labl_labels[index].g = g; - labl_labels[index].b = b; - - /* send the label info to tcl */ - labl_send_info (index); - - return (ERROR_NONE); -} - -int labl_set_alpha (int index, int alpha) -{ - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - if (alpha < 0 || alpha > 255) - return (ERROR_BADPARM); - - /* set the color */ - labl_labels[index].a = alpha; - - /* send the label info to tcl */ - labl_send_info (index); - - return (ERROR_NONE); -} - -int labl_send_info (int index) -{ - char tcl_command[NAME_LENGTH + 50]; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* send the update command to the tcl label list with this label's - information. */ - sprintf (tcl_command, "LblLst_UpdateInfo %d \"%s\" %d %d %d %d %d", - index, labl_labels[index].name, - labl_labels[index].structure, labl_labels[index].visible, - labl_labels[index].r, labl_labels[index].g, - labl_labels[index].b ); - send_tcl_command (tcl_command); - - /* if the fill dlog is open, this will update it. */ - sprintf (tcl_command, "LabelsChanged"); - send_tcl_command (tcl_command); - - return (ERROR_NONE); -} - -int labl_add (LABEL* label, int* new_index) -{ - int index; - char tcl_command[NAME_LENGTH + 50]; - - if (NULL == label) - return (ERROR_BADPARM); - - /* make sure we can add one. */ - if (labl_num_labels >= LABL_MAX_LABELS) - { - printf("max labels exceeded!\n") ; - return (ERROR_NO_MEMORY); - } - - /* add a new node at the end of the list. */ - index = labl_num_labels; - labl_num_labels++; - - /* copy the label in and init the other data. make it a free label - by default, with the default color. */ - labl_labels[index].label = label; - labl_labels[index].structure = LABL_TYPE_FREE; - labl_labels[index].r = LABL_DEFAULT_COLOR_R; - labl_labels[index].g = LABL_DEFAULT_COLOR_G; - labl_labels[index].b = LABL_DEFAULT_COLOR_B; - labl_labels[index].a = LABL_DEFAULT_COLOR_A; - labl_labels[index].visible = 1; - labl_labels[index].border_vno = NULL; - labl_labels[index].num_border_vnos = 0; - - /* set the name using a global counter and increment the counter. */ - labl_num_labels_created++; - sprintf (labl_labels[index].name, "Label %d", labl_num_labels_created); - - /* calc the extent and stuff. */ - labl_changed (index, FALSE); - - /* notify tcl of the new label. */ - sprintf (tcl_command, "LblLst_AddLabel \"%s\"", labl_labels[index].name); - send_tcl_command (tcl_command); - - /* if the fill dlog is open, this will update it. */ - sprintf (tcl_command, "LabelsChanged"); - send_tcl_command (tcl_command); - - /* enable our label menu items. */ - enable_menu_set (MENUSET_LABEL_LOADED, 1); - - /* if they want the new index, return it. */ - if (NULL != new_index) - *new_index = index; - - return (ERROR_NONE); -} - -int labl_changed (int index, int vertices_were_removed) -{ - LABEL* label; - float min_x, max_x; - float min_y, max_y; - float min_z, max_z; - int label_vno; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - label = labl_labels[index].label; - - /* go through the label and find the bounds. */ - min_x = min_y = min_z = 500; - max_x = max_y = max_z = -500; - for (label_vno = 0; label_vno < label->n_points; label_vno++) - { - if (label->lv[label_vno].x < min_x) - min_x = label->lv[label_vno].x; - if (label->lv[label_vno].y < min_y) - min_y = label->lv[label_vno].y; - if (label->lv[label_vno].z < min_z) - min_z = label->lv[label_vno].z; - if (label->lv[label_vno].x > max_x) - max_x = label->lv[label_vno].x; - if (label->lv[label_vno].y > max_y) - max_y = label->lv[label_vno].y; - if (label->lv[label_vno].z > max_z) - max_z = label->lv[label_vno].z; - } - - /* set the bounds in the label, modifying it by the fudge value. */ - labl_labels[index].min_x = min_x - LABL_FUDGE; - labl_labels[index].min_y = min_y - LABL_FUDGE; - labl_labels[index].min_z = min_z - LABL_FUDGE; - labl_labels[index].max_x = max_x + LABL_FUDGE; - labl_labels[index].max_y = max_y + LABL_FUDGE; - labl_labels[index].max_z = max_z + LABL_FUDGE; - - /* this label needs to be recached */ - labl_labels[index].cached = FALSE; - labl_cache_updated = FALSE; - - /* if vertices were removed, we need to force rebuild the entire - cache. */ - if (vertices_were_removed) - labl_update_cache (TRUE); - - /* find the border. */ - labl_find_and_set_border (index); - - return (ERROR_NONE); -} - -int labl_all_changed () -{ - - int label; - - for ( label = 0; label < labl_num_labels; label++ ) - { - labl_changed( label, 0 ); - } - - return (ERROR_NONE); -} - -int labl_remove (int index) -{ - int next; - char tcl_command[NAME_LENGTH]; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* free the label here. */ - LabelFree (&labl_labels[index].label); - - /* Free the border storage. */ - free (labl_labels[index].border_vno); - - /* for every label above it, copy it one slot down. */ - next = index + 1; - while (next < labl_num_labels) - { - labl_labels[next-1] = labl_labels[next]; - next++; - } - - /* decrement the number of labels. */ - labl_num_labels--; - - /* rebuild the cache index. */ - labl_update_cache (TRUE); - - /* notify tcl that this label is gone. */ - sprintf (tcl_command, "LblLst_RemoveLabel %d", index ); - send_tcl_command (tcl_command); - - /* if the fill dlog is open, this will update it. */ - sprintf (tcl_command, "LabelsChanged"); - send_tcl_command (tcl_command); - - /* if this was our selected label, select nothing. */ - if (labl_selected_label == index) - labl_select (-1); - - /* if our selection was above label selected, decrement it. */ - else if (labl_selected_label > index) - labl_selected_label--; - - /* find all the borders again. */ - labl_find_and_set_all_borders (); - - return (ERROR_NONE); -} - -int labl_mark_threshold_vertices (int index, float threshold) -{ - int n, vno ; - VERTEX* v; - LABEL* area = labl_labels[index].label ; - - for (n = 0 ; n < area->n_points ; n++) - { - /* for the nth vertex in the label */ - vno = area->lv[n].vno ; - if (vno < 0 || vno >= mris->nvertices) - return (ERROR_BADPARM) ; - - /* mark the vertex if it's less than threshold */ - if ( area->lv[n].stat < threshold ) - { - v = &mris->vertices[vno] ; - v->marked = 1 ; - } - } - return (ERROR_NONE) ; -} - -int labl_threshold (int index, float threshold) -{ - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* mark all the vertices below the threshold */ - labl_mark_threshold_vertices(index, threshold); - - /* remove the marked vertices from the label */ - labl_remove_marked_vertices_from_label(index); - - labl_update_cache (TRUE); - - labl_find_and_set_border (index); - - /* clear the marked vertices */ - clear_all_vertex_marks(); - - return (ERROR_NONE); -} - -int labl_remove_all () -{ - - int labels; - - /* delete all the labels. */ - labels = labl_num_labels; - while (labels > 0) - { - labl_remove (0); - labels--; - } - labl_num_labels_created = 0; - labl_num_labels = 0 ; - - return (ERROR_NONE); -} - -int labl_find_label_by_vno (int vno, int min_label, int* index_array, - int array_size, int* out_num_found) -{ - int num_to_copy, num_to_copy_from_beginning; - int i; - - /* if they passed -1 for min_label, they really want 0. (ugh) */ - if (min_label < 0) - min_label = 0; - - /* update the cache if necessary */ - if (!labl_cache_updated) - labl_update_cache (TRUE); - - /* return some points. */ - num_to_copy = MIN(array_size,labl_num_labels_at_cache_vno[vno]); - num_to_copy_from_beginning = 0; - if (num_to_copy > 0) - { - if (min_label != 0) - { - /* find the first label index <= min_label */ - i = 0; - while (labl_cache[vno][i] < min_label && - i < labl_num_labels_at_cache_vno[vno]) - i++; - - num_to_copy = labl_num_labels_at_cache_vno[vno] - i; - if (num_to_copy > array_size) num_to_copy = array_size; - - num_to_copy_from_beginning = i; - if (num_to_copy_from_beginning > array_size - num_to_copy) - num_to_copy_from_beginning = array_size - num_to_copy; - if ( num_to_copy_from_beginning < 0 ) - num_to_copy_from_beginning = 0; - - - memmove (index_array, &(labl_cache[vno][i]), - num_to_copy * sizeof(int)); - - memmove (&(index_array[num_to_copy]), labl_cache[vno], - num_to_copy_from_beginning * sizeof(int)); - } - else - { - memmove (index_array, labl_cache[vno], num_to_copy * sizeof(int)); - } - } - - *out_num_found = num_to_copy + num_to_copy_from_beginning; - - return (ERROR_NONE); -} - -int labl_select_label_by_vno (int vno) -{ - int label_index = -1; - int num_found; - - if (vno < 0 || vno >= mris->nvertices) - return (ERROR_BADPARM); - - /* try and find a label. if found, select it. */ - labl_debug = 1; - labl_find_label_by_vno (vno, labl_selected_label+1, - &label_index, 1, &num_found); - labl_debug = 0; - if (num_found > 0) - labl_select (label_index); - else - labl_select (-1); - - return (ERROR_NONE); -} - -int labl_apply_color_to_vertex (int vno, GLubyte* r, GLubyte* g, GLubyte* b ) -{ - int label_index_array[LABL_MAX_LABELS]; - int num_labels_found, found_label_index; - float br, bg, bb; - float lr, lg, lb; - int label_index; - - if (vno < 0 || vno >= mris->nvertices) - return (ERROR_BADPARM); - - /* if our display flag is off, do nothing. */ - if ( !labl_draw_flag ) - { - return (ERROR_NONE); - } - - /* try and find a label. if found... */ - labl_find_label_by_vno (vno, 0, label_index_array, - LABL_MAX_LABELS, &num_labels_found); - if (num_labels_found > 0) - { - for (found_label_index = 0; found_label_index < num_labels_found; - found_label_index++) - { - label_index = label_index_array[found_label_index]; - - /* if this is the selected label and this is a border of width 1 - or 2, make it our outline color. */ - if (labl_selected_label == label_index && - labl_vno_is_border(labl_selected_label, vno)) - { - *r = labl_outline_color[0]; - *g = labl_outline_color[1]; - *b = labl_outline_color[2]; - } - /* else if this label is visible... */ - else if (labl_labels[label_index].visible) - { - /* color it in the given drawing style. */ - switch (labl_draw_style) - { - case LABL_STYLE_FILLED: - /* If this is filled, we're going to blend the - background with the label color with the alpha - level from the color table. */ - br = ((float)(*r) / 255.0) * - (1.0 - ((float)labl_labels[label_index].a / 255.0)); - bg = ((float)(*g) / 255.0) * - (1.0 - ((float)labl_labels[label_index].a / 255.0)); - bb = ((float)(*b) / 255.0) * - (1.0 - ((float)labl_labels[label_index].a / 255.0)); - - lr = ((float)labl_labels[label_index].r / 255.0) * - ((float)labl_labels[label_index].a / 255.0); - lg = ((float)labl_labels[label_index].g / 255.0) * - ((float)labl_labels[label_index].a / 255.0); - lb = ((float)labl_labels[label_index].b / 255.0) * - ((float)labl_labels[label_index].a / 255.0); - - *r = (GLubyte)((br + lr) * 255.0); - *g = (GLubyte)((bg + lg) * 255.0); - *b = (GLubyte)((bb + lb) * 255.0); - break; - case LABL_STYLE_OUTLINE: - /* if this is a border of width 1, color it the color of the - label. */ - if (labl_vno_is_border (label_index, vno)) - { - *r = labl_labels[label_index].r; - *g = labl_labels[label_index].g; - *b = labl_labels[label_index].b; - } - break; - default: - ; - } - } - } - } - - return (ERROR_NONE); -} - -int labl_erode (int index) -{ - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* Perform the erode. */ - LabelErode (labl_labels[index].label, mris, 1); - - /* Label is changed and we removed points. */ - labl_changed (index, TRUE); - - return (ERROR_NONE); -} - -int labl_dilate (int index) -{ - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* Dilate the label. */ - LabelDilate (labl_labels[index].label, mris, 1, CURRENT_VERTICES); - - /* Label is changed but we didn't remove points. */ - labl_changed (index, FALSE); - - return (ERROR_NONE); -} - -int labl_fill_holes (int index) -{ - LABEL* filled; - - if (index < 0 || index >= labl_num_labels) - return (ERROR_BADPARM); - - /* Fill the holes in the label. */ -#if 1 - filled = LabelFillHoles (labl_labels[index].label, mris, WHITE_VERTICES); -#else - filled = LabelFillHolesWithOrig (labl_labels[index].label, mris); -#endif - if (NULL != filled) - { - /* Save the new label. */ - LabelFree (&labl_labels[index].label); - labl_labels[index].label = filled; - - /* Label is changed. */ - labl_changed (index, TRUE); - } - - /* This marks verts as a byproduct, so unmark them. */ - clear_all_vertex_marks(); - - return (ERROR_NONE); -} - -int labl_print_list () -{ - int label_index; - LABL_LABEL* label; - - printf ("Num labels: %d (%d) Num strucutres: %d\n", - labl_num_labels, labl_selected_label, labl_num_structures ); - for (label_index = 0; label_index < labl_num_labels; label_index++) - { - label = &(labl_labels[label_index]); - - printf ("Label %d\n", label_index ); - printf ("\tName: %s, %d vertices\n", - label->name, label->label->n_points ); - printf ("\tStructure: %d Color: %d %d %d Visible: %d\n", - label->structure, label->r, label->g, label->b, label->visible ); - printf ("\tBounds: x %f %f y %f %f z %f %f\n", - label->min_x, label->max_x, - label->min_y, label->max_y, - label->min_z, label->max_z); - } - - return (ERROR_NONE); -} - -int labl_print_table () -{ - int structure_index; - COLOR_TABLE* ctab; - int r, g, b, a; - char structure_label[1024]; - - printf( "Num strucutres: %d\n", labl_num_structures ); - for (structure_index = 0; structure_index < labl_num_structures; - structure_index++) - { - if (mris->ct) - ctab = mris->ct; - else - ctab = labl_ctab; - - CTABrgbaAtIndexi (ctab, structure_index, &r, &g, &b, &a); - CTABcopyName (ctab, structure_index, - structure_label, sizeof(structure_label)); - - printf ("Structure %d: %s r %d g %d b %d a %d", - structure_index, structure_label, r, g, b, a); - } - - return (ERROR_NONE); -} - -/* ---------------------------------------------------------------------- */ - -/* ------------------------------------------------------ fill paths */ -static int -path_set_marks(PATH_PATH *b, MRI_SURFACE *mris, int mark) -{ - int i, vno ; - - for (i = 0 ; i < b->num_vertices ; i++) - { - vno = b->vertices[i] ; - if (vno < 0 || vno >= mris->nvertices) - continue ; - mris->vertices[vno].marked = mark ; - } - return(NO_ERROR) ; - -} - -PATH_PATH * -path_copy(PATH_PATH *bsrc, PATH_PATH *bdst) -{ - int vno ; - - if (!bdst) - { - bdst = (PATH_PATH *)calloc(1, sizeof(PATH_PATH)) ; - bdst->vertices = (int *)calloc(bsrc->num_vertices, sizeof(int)) ; - if (!bdst->vertices) - ErrorExit(ERROR_NOMEMORY, "%s: could not copy path with %d vertices", - Progname, bdst->num_vertices) ; - } - - bdst->num_vertices = bsrc->num_vertices ; - bdst->min_x = bsrc->min_x ; - bdst->max_x = bsrc->max_x ; - bdst->min_y = bsrc->min_y ; - bdst->max_y = bsrc->max_y ; - bdst->min_z = bsrc->min_z ; - bdst->max_z = bsrc->max_z ; - for (vno = 0 ; vno < bdst->num_vertices ; vno++) - bdst->vertices[vno] = bsrc->vertices[vno] ; - return(bdst) ; -} - -int path_initialize () -{ - int path; - - /* Clear the path array. */ - for (path = 0; path < PATH_MAX_PATHS; path++) - { - path_paths[path].num_vertices = 0; - path_paths[path].vertices = NULL; - } - - /* No paths present. */ - path_selected_path = PATH_NONE_SELECTED; - path_num_paths = 0; - - /* This will be itialized in path_update_surface_paths. */ - if (NULL != path_is_path) - free (path_is_path); - path_is_path = NULL; - - return (ERROR_NONE); -} - -int path_new_path_from_marked_vertices () -{ - int* path; - int path_length; - - /* Initialize a new path. */ - path = (int*) calloc (mris->nvertices, sizeof(int)); - - /* Find the actual vnos in this path between the currently marked - vertices. */ - find_path (marked, nmarked, "making path", mris->nvertices, - path, &path_length); - - /* Add the vertices we found to a new path. */ - path_add (path_length, path, NULL); - - /* Free the storage for our path finder. */ - free (path); - - return (ERROR_NONE); -} - -int path_remove_selected_path () -{ - /* Call path_remove on currently selected path. */ - if (path_selected_path >= 0 && - path_selected_path < path_num_paths) - path_remove (path_selected_path); - - return (ERROR_NONE); -} - -int path_add (int num_vertices, int* vertices, int* new_index) -{ - int index; - float min_x, max_x; - float min_y, max_y; - float min_z, max_z; - int path; - VERTEX* v; - - /* Make sure we have vertices. */ - if (num_vertices <= 0) - return (ERROR_BADPARM); - if (NULL == vertices) - return (ERROR_BADPARM); - - /* Make sure we can add one. */ - if (path_num_paths >= PATH_MAX_PATHS) - return (ERROR_NO_MEMORY); - - /* Add a new one at the end of our array of paths. */ - index = path_num_paths; - path_num_paths++; - - /* Allocate the vertices array and copy everything in. */ - path_paths[index].num_vertices = num_vertices; - path_paths[index].vertices = (int*) calloc (num_vertices, sizeof(int)); - if (NULL == path_paths[index].vertices) - { - printf ("path_add: calloc failed with %d elements\n", num_vertices); - return (ERROR_NO_MEMORY); - } - memmove (path_paths[index].vertices, vertices, num_vertices * sizeof(int)); - - /* Go through the path and find the bounds of the vertices. */ - min_x = min_y = min_z = 500; - max_x = max_y = max_z = -500; - for (path = 0; - path < path_paths[index].num_vertices; - path++) - { - v = &(mris->vertices[ path_paths[index].vertices[path] ]); - - if (v->x < min_x) - min_x = v->x; - if (v->y < min_y) - min_y = v->y; - if (v->z < min_z) - min_z = v->z; - if (v->x > max_x) - max_x = v->x; - if (v->y > max_y) - max_y = v->y; - if (v->z > max_z) - max_z = v->z; - } - - /* Set the bounds in the path, modifying it by the fudge value. */ - path_paths[index].min_x = min_x - PATH_FUDGE; - path_paths[index].min_y = min_y - PATH_FUDGE; - path_paths[index].min_z = min_z - PATH_FUDGE; - path_paths[index].max_x = max_x + PATH_FUDGE; - path_paths[index].max_y = max_y + PATH_FUDGE; - path_paths[index].max_z = max_z + PATH_FUDGE; - - /* Update the path flags. This will mark all vertices that are in - paths in our path_is_path array. */ - path_update_surface_paths (); - - /* Return the new index if they want it. */ - if (NULL != new_index) - *new_index = index; - - return (ERROR_NONE); -} - -int path_remove (int index) -{ - int next; - - if (index < 0 || index >= path_num_paths) - return (ERROR_BADPARM); - - /* Free the vertices array. */ - free (path_paths[index].vertices); - - /* Bump everything above this index down one. */ - next = index + 1; - while (next < path_num_paths) - { - path_paths[next-1] = path_paths[next]; - next++; - } - - /* Decrement the number of paths. */ - path_num_paths--; - - /* Update the paths flags */ - path_update_surface_paths (); - - /* If this was our selected path, select nothing. */ - if (path_selected_path == index) - path_select (-1); - - /* If our selection was above path selected, decrement it so the - same path is still selected. */ - else if (path_selected_path > index) - path_selected_path--; - - return (ERROR_NONE); -} - -int path_update_bounding_boxes () -{ - - VERTEX* v; - int path, path_vno; - float min_x, min_y, min_z; - float max_x, max_y, max_z; - - /* For every path... */ - for (path = 0; path < path_num_paths; path++) - { - - /* Go through the path and find the bounds of the vertices. */ - min_x = min_y = min_z = 500; - max_x = max_y = max_z = -500; - for (path_vno = 0; - path_vno < path_paths[path].num_vertices; - path_vno++ ) - { - - v = &(mris->vertices[ path_paths[path].vertices[path_vno] ]); - - if (v->x < min_x) - min_x = v->x; - if (v->y < min_y) - min_y = v->y; - if (v->z < min_z) - min_z = v->z; - if (v->x > max_x) - max_x = v->x; - if (v->y > max_y) - max_y = v->y; - if (v->z > max_z) - max_z = v->z; - } - - /* Set the bounds in the path, modifying it by the fudge value. */ - path_paths[path].min_x = min_x - PATH_FUDGE; - path_paths[path].min_y = min_y - PATH_FUDGE; - path_paths[path].min_z = min_z - PATH_FUDGE; - path_paths[path].max_x = max_x + PATH_FUDGE; - path_paths[path].max_y = max_y + PATH_FUDGE; - path_paths[path].max_z = max_z + PATH_FUDGE; - - } - - return (ERROR_NONE); -} - -int path_select (int index) -{ - int old_selected; - - /* Select this path. */ - old_selected = path_selected_path; - path_selected_path = index; - - /* If this changes which path is selected, redraw. */ - if (old_selected != path_selected_path) - redraw(); - - return (ERROR_NONE); -} - -int path_mark_selected_path () -{ - - /* Call path_mark on currently selected path. */ - path_mark (path_selected_path); - - return (ERROR_NONE); -} - -int path_mark (int index) -{ - - int path_vno; - - if (path_selected_path < 0 || - path_selected_path >= path_num_paths) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, "path_mark: path index not valid")); - - /* Mark all vertices in the path. */ - for (path_vno = 0; - path_vno < path_paths[index].num_vertices; - path_vno++ ) - { - mark_vertex (path_paths[index].vertices[path_vno], TRUE); - } - - return (ERROR_NONE); -} - -int path_update_surface_paths () -{ - int path; - int path_vno; - - /* Make our path flag array if we haven't already. It's just the - size of nvertices. All are initialized to FALSE. */ - if (NULL == path_is_path) - { - path_is_path = (char*) calloc (mris->nvertices, sizeof(char)); - if (NULL == path_is_path) - return (ERROR_NO_MEMORY); - } - else - { - /* Erase the current array. */ - bzero (path_is_path, mris->nvertices*sizeof(char) ); - } - - /* For every path... */ - for (path = 0; path < path_num_paths; path++) - { - /* For every vertex, mark that vertex in the array as a path. */ - for (path_vno = 0; - path_vno < path_paths[path].num_vertices; - path_vno++ ) - { - path_is_path[path_paths[path].vertices[path_vno]] = TRUE; - } - } - - return (ERROR_NONE); -} - -char path_is_vertex_on_path (int vno) -{ - if (vno < 0 || vno >= mris->nvertices) - return (FALSE); - if (NULL == path_is_path) - return (FALSE); - - /* Return the value of the path flag here. */ - return (path_is_path[vno]); -} - -int path_select_path_by_vno (int vno) -{ - int path; - int path_vno; - float x, y, z; - VERTEX *u; - VERTEX *v; - float dist_uv; - int smallest_distance; - int closest_path=-1; - - if (vno < 0 || vno >= mris->nvertices) - return (FALSE); - if (NULL == path_is_path) - return (FALSE); - - /* Get this vertex. */ - v = &(mris->vertices[vno]); - - /* Get the RAS coords. */ - x = v->x; - y = v->y; - z = v->z; - - /* For each path.. */ - smallest_distance = 1000; - path = -1; - for (path = 0; path < path_num_paths; path++) - { - /* Preflight test sees if this point is in the bounding cube of - the path. */ - if (x >= path_paths[path].min_x && - x <= path_paths[path].max_x && - y >= path_paths[path].min_y && - y <= path_paths[path].max_y && - z >= path_paths[path].min_z && - z <= path_paths[path].max_z) - { - /* For each vertex in the path... */ - for (path_vno = 0; - path_vno < path_paths[path].num_vertices; - path_vno++) - { - /* Get the vertex. */ - u = &(mris->vertices[path_paths[path].vertices[path_vno]]); - - /* Find the distance between our input vertex and this one. */ - dist_uv = ((v->x - u->x) * (v->x - u->x)) + - ((v->y - u->y) * (v->y - u->y)) + - ((v->z - u->z) * (v->z - u->z)); - - /* If any is less than the select distance and closer - than the closest path so far, select this path. */ - if (dist_uv < PATH_DISTANCE_TO_SELECT && - dist_uv < smallest_distance) - { - smallest_distance = dist_uv; - closest_path = path; - } - } - } - } - - /* If we didn't find anything, path will be -1 and this will - deselect the current path. */ - path_select (closest_path); - return (ERROR_NONE); -} - -int path_apply_color_to_vertex (int vno, GLubyte* r, GLubyte* g, GLubyte* b ) -{ - float x, y, z; - char selected; - int path_vno; - - if (vno < 0 || vno >= mris->nvertices) - return (ERROR_BADPARM); - if (NULL == r || NULL == g || NULL == b) - return (ERROR_BADPARM); - - /* If this is a path.. */ - if (path_is_vertex_on_path(vno)) - { - - /* Get the location of this vertex. */ - x = mris->vertices[vno].x; - y = mris->vertices[vno].y; - z = mris->vertices[vno].z; - - /* See if it's in the selected bound cube, then in the selectd - path vertex list. */ - selected = FALSE; - if (x >= path_paths[path_selected_path].min_x && - x <= path_paths[path_selected_path].max_x && - y >= path_paths[path_selected_path].min_y && - y <= path_paths[path_selected_path].max_y && - z >= path_paths[path_selected_path].min_z && - z <= path_paths[path_selected_path].max_z) - for (path_vno = 0; - path_vno < path_paths[path_selected_path].num_vertices; - path_vno++) - if (vno == - path_paths[path_selected_path].vertices[path_vno]) - selected = TRUE; - - if (selected) - { - /* If it's selected, mark it yellow. */ - *r = 255; - *g = 255; - *b = 0; - } - else - { - /* Else just color it red. */ - *r = 255; - *g = 0; - *b = 0; - } - } - - return (ERROR_NONE); -} - -int path_save (char* fname) -{ - PATH** paths; - int path_index; - int path_del_index; - int path_vno; - int vno; - int err = ERROR_NONE; - - /* We need to convert out vertex paths to PATH object. Make a list - of them of the size of the number of paths we have. */ - paths = (PATH**) calloc (path_num_paths, sizeof(PATH)); - if (NULL == paths) - { - ErrorReturn (ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, "Couldn't allocate %d paths", - path_num_paths)); - - } - - for (path_index = 0; path_index < path_num_paths; path_index++) - { - - /* Allocate a path. */ - paths[path_index] = - PathAlloc (path_paths[path_index].num_vertices, ""); - if (NULL == paths[path_index]) - { - for (path_del_index = 0; path_index < path_index; path_del_index++) - { - PathFree( &paths[path_del_index] ); - } - free (paths); - ErrorReturn (ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, "Couldn't path with %d points", - path_paths[path_index].num_vertices)); - } - - /* Put the orig coordinates into the path we just created. */ - for (path_vno = 0; - path_vno < path_paths[path_index].num_vertices; path_vno++) - { - vno = path_paths[path_index].vertices[path_vno]; - - paths[path_index]->points[path_vno].x = mris->vertices[vno].origx; - paths[path_index]->points[path_vno].y = mris->vertices[vno].origy; - paths[path_index]->points[path_vno].z = mris->vertices[vno].origz; - paths[path_index]->points[path_vno].vno = vno; - } - } - - /* Write the paths. */ - err = PathWriteMany (fname, path_num_paths, paths); - if (err != ERROR_NONE) - { - printf ("ERROR: Couldn't write paths.\n"); - err = ERROR_NO_FILE; - } - - /* Delete the stuff we allocated. */ - for (path_index = 0; path_index < path_num_paths; path_index++) - { - PathFree( &paths[path_index] ); - } - free (paths); - - return err; -} - -int path_load (char* fname) -{ - int err; - int num_read; - int* vertices = NULL; - int* connected_verts = NULL; - int size_connected_path; - PATH** paths = NULL; - int path_index; - PATH* path = NULL; - LABEL* label = NULL; - int pno; - int path_vno; - - /* Try to read the paths file. */ - err = PathReadMany (fname, &num_read, &paths); - if (err != ERROR_NONE || - num_read <= 0 || paths == NULL) - { - ErrorReturn (ERROR_BADFILE, - (ERROR_BADFILE, "Couldn't read any paths.")); - } - - /* Allocate temp vno storage for our conversions. */ - vertices = (int*) calloc (mris->nvertices, sizeof(int)); - if (NULL == vertices) - { - ErrorReturn (ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, "Couldn't allocate vertex storage.")); - } - - connected_verts = (int*) calloc (mris->nvertices, sizeof(int)); - if (NULL == connected_verts) - { - ErrorReturn (ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, "Couldn't allocate vertex storage.")); - } - - for (path_index = 0; path_index < num_read; path_index++) - { - /* Get the path. */ - path = paths[path_index]; - - /* We'll do our coordinate->vertex conversion using the - LabelFillUnassignedVertices, but it only takes LABEL - structures, so we'll fill one of those out with the - path's coords. */ - label = LabelAlloc (path->n_points, NULL, NULL); - if (NULL == label) - { - free (vertices); - ErrorReturn(ERROR_BADPARM,(ERROR_BADPARM, - "Couldn't allocate label for %d vertices\n", - path->n_points)); - } - label->n_points = path->n_points; - - /* Put the path coords in the label. */ - for (pno = 0; pno < path->n_points; pno++) - { - label->lv[pno].x = path->points[pno].x; - label->lv[pno].y = path->points[pno].y; - label->lv[pno].z = path->points[pno].z; - label->lv[pno].vno = path->points[pno].vno; - } - - /* This will find vertex numbers for all those points. */ - LabelFillUnassignedVertices (mris, label, WHITE_VERTICES); - - /* Copy the vertex numbers from the label into our vertices - array. */ - for (path_vno = 0; path_vno < path->n_points; path_vno++) - { - vertices[path_vno] = label->lv[path_vno].vno; - } - LabelFree (&label); - - size_connected_path = 0; - - /* Make sure the path is connected. */ - find_path (vertices, path->n_points, "Connecting path", - mris->nvertices, connected_verts, &size_connected_path); - - /* Make a new path from our num_vertices and vertices - array. */ - path_add (size_connected_path, connected_verts, NULL); - - /* Free this path. */ - PathFree (&paths[path_index]); - - } - - free (vertices); - free (connected_verts); - free (paths); - - return (ERROR_NONE); -} - -/* ---------------------------------------------------------------------- */ - -/* ------------------------------------------------------- floodfill mark */ - -int fill_flood_from_seed (int seed_vno, FILL_PARAMETERS* params) -{ - char* filled; - int num_filled_this_iter; - int num_filled; - int iter; - int min_vno, max_vno, step_vno; - int vno; - int this_label = 0; - int neighbor_index; - int neighbor_vno; - VERTEX* v; - VERTEX* neighbor_v; - float fvalue = 0; - float seed_curv = 0; - float seed_fvalue = 0; - int new_index; - int label_index_array[LABL_MAX_LABELS]; - int num_labels_found, found_label_index; - int skip; - int count; - - if (seed_vno < 0 || seed_vno >= mris->nvertices) - return (ERROR_BADPARM); - if (NULL == params) - return (ERROR_BADPARM); - if (params->action < 0 || params->action >= NUM_FILL_ACTIONS) - return (ERROR_BADPARM); - - /* init filled array. */ - filled = (char*) calloc (mris->nvertices, sizeof(char)); - - /* start with the seed filled.*/ - filled[seed_vno] = TRUE; - - /* find seed values for some conditions. */ - if (params->dont_cross_label) - this_label = labl_selected_label; - if (params->dont_cross_cmid) - seed_curv = mris->vertices[seed_vno].curv; - if (params->dont_cross_fthresh) - sclv_get_value (&mris->vertices[seed_vno], - sclv_current_field, &seed_fvalue); - - /* Start listing for cancel */ - printf ("surfer: filling (ctrl-c to cancel)"); - cncl_start_listening (); - - /* while we're still filling stuff in a pass... */ - num_filled_this_iter = 1; - num_filled = 0; - iter = 0; - while (num_filled_this_iter > 0) - { - if (cncl_user_canceled()) - { - goto cancel; - } - - num_filled_this_iter = 0; - - /* switch between iterating forward and backwards. */ - if ((iter%2)==0) - { - min_vno = 0; - max_vno = mris->nvertices-1; - step_vno = 1; - } - else - { - min_vno = mris->nvertices-1; - max_vno = 0; - step_vno = -1; - } - - /* for each vertex, if it's filled, check its neighbors. for the - rules that are up-to-and-including, make the check on this - vertex. for the rules that are up-to-and-not-including, check - on the neighbor. */ - for (vno = min_vno; vno != max_vno; vno += step_vno) - { - if (filled[vno]) - { - - /* check the neighbors... */ - v = &mris->vertices[vno]; - - /* if this vert is ripped, move on. */ - if (v->ripflag) - { - continue; - } - - /* if we're not crossing paths, check if this is a - path. if so, move on. */ - if (params->dont_cross_path && - path_is_vertex_on_path (vno)) - { - continue; - } - - /* if we're not crossing the cmid, see if the cmid at this - vertex is on the other side of the cmid as the seed - point. if so, move on. */ - if (params->dont_cross_cmid && - ((seed_curv <= cmid && v->curv > cmid) || - (seed_curv >= cmid && v->curv < cmid))) - { - continue; - } - - for (neighbor_index = 0; - neighbor_index < v->vnum; - neighbor_index++) - { - neighbor_vno = v->v[neighbor_index]; - neighbor_v = &mris->vertices[neighbor_vno] ; - - /* if the neighbor is filled, move on. */ - if (filled[neighbor_vno]) - continue; - - /* if we're not crossing labels, check if the label at - this vertex is the same as the one at the seed. if not, - move on. */ - if (params->dont_cross_label || - params->dont_fill_unlabeled) - { - - labl_find_label_by_vno (neighbor_vno, 0, - label_index_array, - LABL_MAX_LABELS, - &num_labels_found); - if (num_labels_found > 0 && - params->dont_cross_label) - { - skip = 0; - for (found_label_index = 0; - found_label_index < num_labels_found; - found_label_index++) - { - if (label_index_array[found_label_index] != - this_label) - { - skip = 1; - break; - } - } - if (skip) continue; - } - if (num_labels_found == 0 && - params->dont_fill_unlabeled) - { - continue; - } - } - - /* if we're not crossing the fthresh, make sure this - point is above it, or, if our initial functional - value was negative, make sure it's not above - -fthresh. if not, move on. */ - if (params->dont_cross_fthresh) - { - sclv_get_value (neighbor_v, sclv_current_field, &fvalue); - if ((fthresh != 0 && - seed_fvalue > 0 && - fvalue < fthresh) || - (fthresh != 0 && - seed_fvalue < 0 && - fvalue > -fthresh) || - (fthresh == 0 && (fvalue * seed_fvalue < 0))) - { - continue; - } - } - - /* mark this vertex as filled. */ - filled[neighbor_vno] = TRUE; - num_filled_this_iter++; - num_filled++; - } - } - } - - iter++; - - if ((iter % 2) == 0) - { - printf ("."); - fflush (stdout); - } - } - - /* mark all filled vertices. */ - count = 0; - for (vno = 0; vno < mris->nvertices; vno++ ) - if (filled[vno]) - { - mris->vertices[vno].marked = TRUE; - count++; - } - - switch (params->action) - { - case FILL_ACTION_NEW_LABEL: - /* make a new label from the marked vertices. */ - labl_new_from_marked_vertices (&new_index); - params->new_label_index = new_index; - break; - case FILL_ACTION_ADD_LABEL: - /* add the marked vertices to the label spec'd in the argument. */ - labl_add_marked_vertices_to_label (params->argument); - break; - case FILL_ACTION_REMOVE_LABEL: - /* remove the marked vertices from the label spec'd in the argument. */ - labl_remove_marked_vertices_from_label (params->argument); - break; - default: - break; - } - - printf (" done, %d vertices filled\n", count); - fflush (stdout); - - goto done; - -cancel: - printf (" canceled\n"); - fflush (stdout); - -done: - cncl_stop_listening (); - - free (filled); - - return (ERROR_NONE); -} -/* ---------------------------------------------------------------------- */ - -int edit_vertex_at_cursor ( int action, int argument ) -{ - return edit_vertex (selection, action, argument); -} - -int edit_vertex ( int vno, int action, int argument ) -{ - int i; - int* saved_marks; - int saved_nmarked; - int found_labels[LABL_MAX_LABELS]; - int num_found; - int label; - - if (vno < 0 || vno > mris->nvertices) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "edit_vertex_at_cursor: vno is oob: %d)", vno)); - - if (action < 0 || action >= NUM_VEDIT_ACTIONS) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "edit_vertex_at_cursor: action was invalid: %d)", action)); - - /* Save the old marks. */ - saved_marks = (int*) calloc (mris->nvertices, sizeof(int)); - memmove (saved_marks, marked, sizeof(int) * mris->nvertices); - saved_nmarked = nmarked; - - /* Clear marks. */ - clear_all_vertex_marks (); - - /* Mark this vertex. */ - mark_vertex (vno, TRUE); - - /* Work on stuff based on this one marked vertex. */ - switch (action) - { - case VEDIT_ACTION_NEW_LABEL: - labl_new_from_marked_vertices (NULL); - break; - case VEDIT_ACTION_ADD_LABEL: - labl_add_marked_vertices_to_label (argument); - break; - case VEDIT_ACTION_REMOVE_LABEL: - labl_remove_marked_vertices_from_label (argument); - break; - case VEDIT_ACTION_CLEAR_LABELS: - labl_find_label_by_vno (vno, 0, found_labels, - sizeof(found_labels), &num_found); - for (label = 0; label < num_found; label++) - labl_remove_marked_vertices_from_label (found_labels[label]); - break; - default: - break; - } - - /* Restore the marks. */ - memmove (marked, saved_marks, sizeof(int) * mris->nvertices); - for (i = 0; i < mris->nvertices; i++) - mris->vertices[i].marked = saved_marks[i]; - nmarked = saved_nmarked; - - return (ERROR_NONE); -} - -/* ---------------------------------------------------------------------- */ - -int find_path ( int* vert_vno, int num_vno, char* message, int max_path_length, - int* path, int* path_length ) -{ - - - int cur_vert_vno; - int src_vno; - int dest_vno; - int vno; - char* check; - float* dist; - int* pred; - char done; - VERTEX* v; - VERTEX* u; - float closest_dist; - int closest_vno; - int neighbor; - int neighbor_vno; - float dist_uv; - int path_vno; - int num_path = 0; - int num_checked; - float vu_x, vu_y, vu_z; - - dist = (float*) calloc (mris->nvertices, sizeof(float)); - pred = (int*) calloc (mris->nvertices, sizeof(int)); - check = (char*) calloc (mris->nvertices, sizeof(char)); - num_path = 0; - num_checked = 0; - (*path_length) = 0; - - if (NULL != message) - { - fprintf (stdout, "surfer: %s (ctrl-c to cancel)", message); - } - cncl_start_listening (); - for (cur_vert_vno = 0; cur_vert_vno < num_vno-1; cur_vert_vno++) - { - if (cncl_user_canceled()) - { - goto cancel; - } - - /* clear everything */ - for (vno = 0; vno < mris->nvertices; vno++) - { - dist[vno] = 999999; - pred[vno] = -1; - check[vno] = FALSE; - } - - /* Set src and dest */ - src_vno = vert_vno[cur_vert_vno+1]; - dest_vno = vert_vno[cur_vert_vno]; - - /* make sure both are in range. */ - if (src_vno < 0 || src_vno >= mris->nvertices || - dest_vno < 0 || dest_vno >= mris->nvertices) - continue; - - if (src_vno == dest_vno) - continue; - - /* pull the src vertex in. */ - dist[src_vno] = 0; - pred[src_vno] = vno; - check[src_vno] = TRUE; - - done = FALSE; - while (!done) - { - if (cncl_user_canceled()) - { - goto cancel; - } - - /* find the vertex with the shortest edge. */ - closest_dist = 999999; - closest_vno = -1; - for (vno = 0; vno < mris->nvertices; vno++) - if (check[vno]) - if (dist[vno] < closest_dist) - { - closest_dist = dist[vno]; - closest_vno = vno; - } - v = &(mris->vertices[closest_vno]); - check[closest_vno] = FALSE; - - /* if this is the dest node, we're done. */ - if (closest_vno == dest_vno) - { - done = TRUE; - } - else - { - /* relax its neighbors. */ - for (neighbor = 0; neighbor < v->vnum; neighbor++) - { - neighbor_vno = v->v[neighbor]; - u = &(mris->vertices[neighbor_vno]); - - /* calc the vector from u to v. */ - vu_x = u->x - v->x; - vu_y = u->y - v->y; - if (flag2d) - vu_z = 0; - else - vu_z = u->z - v->z; - - /* recalc the weight. */ - if (flag2d) - dist_uv = sqrt(((v->x - u->x) * (v->x - u->x)) + - ((v->y - u->y) * (v->y - u->y))); - else - dist_uv = sqrt(((v->x - u->x) * (v->x - u->x)) + - ((v->y - u->y) * (v->y - u->y)) + - ((v->z - u->z) * (v->z - u->z))); - - /* if this is a new shortest path, update the predecessor, - weight, and add it to the list of ones to check next. */ - if (dist_uv + dist[closest_vno] < dist[neighbor_vno]) - { - pred[neighbor_vno] = closest_vno; - dist[neighbor_vno] = dist_uv + dist[closest_vno]; - check[neighbor_vno] = TRUE; - } - } - } - num_checked++; - if ((num_checked % 100) == 0) - { - printf ("."); - fflush (stdout); - } - } - - /* add the predecessors from the dest to the src to the path. */ - path_vno = dest_vno; - path[(*path_length)++] = dest_vno; - while (pred[path_vno] != src_vno && - (*path_length) < max_path_length ) - { - path[(*path_length)++] = pred[path_vno]; - path_vno = pred[path_vno]; - } - } - printf (" done\n"); - fflush (stdout); - - goto done; - -cancel: - printf (" canceled\n"); - fflush (stdout); - *path_length = 0; - -done: - cncl_stop_listening (); - - free (dist); - free (pred); - free (check); - - return (ERROR_NONE); -} - -/* ---------------------------------------------------------------------- */ - -#define TCL_CACHE_INC 10 -void send_tcl_command (char* cmd) -{ - char** new_cached_tcl_commands = NULL; - char* new_cmd = NULL; - int n; - int tcl_err; - - /* If g_interp is NULL we'll cache the command. */ - if (NULL == g_interp) - { - - /* If we need more space... */ - if (num_cached_tcl_commands >= max_num_cached_tcl_commands) - { - /* Allocate a new batch of cached command space. */ - new_cached_tcl_commands = - (char**)calloc (max_num_cached_tcl_commands + - TCL_CACHE_INC,sizeof(char*)); - - /* Copy in old commands if necessary. Note we just copy the - pointers, we don't allocate new strings.*/ - if (NULL != cached_tcl_commands) - for (n = 0; n < num_cached_tcl_commands; n++ ) - { - new_cached_tcl_commands[n] = cached_tcl_commands[n]; - } - - /* Free the old storage, we're still pointing to the strings - in the new array. */ - free (cached_tcl_commands); - - /* Store new array. */ - cached_tcl_commands = new_cached_tcl_commands; - - max_num_cached_tcl_commands = - max_num_cached_tcl_commands + TCL_CACHE_INC; - } - - /* Make a copy of the command. Don't use strdup because that's - been replaced by tixStrDup and we might not have called - tixInit yet. */ - new_cmd = (char*) calloc( strlen(cmd) + 1, sizeof(char) ); - if (NULL != new_cmd) - { - strcpy( new_cmd, cmd ); - cached_tcl_commands[num_cached_tcl_commands] = new_cmd; - num_cached_tcl_commands++; - } - else - { - printf ("surfer: Error creating command storage of size %d\n", - (int)strlen(cmd)); - } - } - else - { - /* Send the command. */ - tcl_err = Tcl_Eval (g_interp, cmd); - - /* Print an error message if we got one. */ - if (TCL_OK != tcl_err) - { - printf ("surfer: Error sending tcl command %s:\n\t%s\n", - cmd, Tcl_GetStringResult (g_interp)); - } - } -} - -void send_cached_tcl_commands () -{ - int n; - - if (NULL == g_interp) - { - printf ("surfer: Can't send cached commands, no interpreter present.\n"); - } - - /* For each command, send it. Then free the string. */ - for (n = 0; n < num_cached_tcl_commands; n++ ) - { - send_tcl_command (cached_tcl_commands[n]); - free (cached_tcl_commands[n]); - } - - num_cached_tcl_commands = 0; -} - -/* ---------------------------------------------------------------------- */ - -int -cptn_initialize () -{ - cptn_format_string = (char*) calloc (CPTN_STRING_LEN+1, sizeof(char)); - if (NULL == cptn_format_string) - ErrorReturn - (ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, - "cptn_initialize: Couldn't init format string")); - - cptn_value_string = (char*) calloc (CPTN_STRING_LEN+1, sizeof(char)); - if (NULL == cptn_value_string) - ErrorReturn - (ERROR_NO_MEMORY, - (ERROR_NO_MEMORY, - "cptn_initialize: Couldn't init value string")); - - /* Initial value. */ - strncpy (cptn_format_string, "Vertex: !V", CPTN_STRING_LEN); - - return ERROR_NONE; -} - -int -cptn_set_format_string ( char* in ) -{ - if (NULL == in) - ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "cptn_set_format_string: in was NULL")); - - if (NULL == cptn_format_string) - ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "cptn_set_format_string: format string was NULL")); - - strncpy (cptn_format_string, in, CPTN_STRING_LEN); - - return ERROR_NONE; -} - -int cptn_clear_value_string () -{ - if (NULL == cptn_value_string) - ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "cptn_clear_value_string: value string was NULL")); - - strncpy (cptn_value_string, cptn_format_string, CPTN_STRING_LEN); - - return ERROR_NONE; -} - - -int -cptn_sprintf_for_code (const char* code, const char* format, ... ) -{ - va_list args; - char value[1024]; - - if (NULL == cptn_value_string) - ErrorReturn - (ERROR_BADPARM, - (ERROR_BADPARM, - "cptn_sprintf_for_code: value string was NULL")); - - /* sprintf the value into a string */ - va_start (args, format); - vsnprintf (value, sizeof(value), format, args); - va_end (args); - - /* Make the substitution in the caption. */ - cptn_substitute_code_with_value (cptn_value_string, - CPTN_STRING_LEN, code, value); - - return ERROR_NONE; -} - -int -cptn_draw () -{ - int cur_char; - - if (NULL == cptn_value_string) - ErrorReturn (ERROR_BADPARM, - (ERROR_BADPARM, "cptn_draw: value string was NULL")); - - glPushMatrix(); - glLoadIdentity(); - - /* Draw a rectangle under our caption, both to clear the old caption - and to provide a contrasting background. */ - glNormal3f (0.0, 0.0, 1.0); - glColor3f (0.0, 0.0, 0.0); - glBegin (GL_QUADS); - glVertex3f (fov*sf * CPTN_LOC_RECTANGLE_LEFT, - fov*sf * CPTN_LOC_RECTANGLE_BOTTOM, fov*sf * 10 ); - glVertex3f (fov*sf * CPTN_LOC_RECTANGLE_RIGHT, - fov*sf * CPTN_LOC_RECTANGLE_BOTTOM, fov*sf * 10 ); - glVertex3f (fov*sf * CPTN_LOC_RECTANGLE_RIGHT, - fov*sf * CPTN_LOC_RECTANGLE_TOP, fov*sf * 10 ); - glVertex3f (fov*sf * CPTN_LOC_RECTANGLE_LEFT, - fov*sf * CPTN_LOC_RECTANGLE_TOP, fov*sf * 10 ); - glEnd (); - - /* Note that the color of bitmaps is taken from the raster color, - which is only set when glRasterPos is called. So set the color - first, then call glRasterPos. */ - glDisable(GL_LIGHTING); // necessary to get color setting to work - glNormal3f (0.0, 0.0, 1.0); - glColor3f (1.0, 1.0, 1.0); - glRasterPos3f (fov*sf * CPTN_LOC_CAPTION_X, - fov*sf * CPTN_LOC_CAPTION_Y, fov*sf * 10 ); - - /* Draw the caption. */ - for (cur_char = 0; cur_char < strlen(cptn_value_string); cur_char++) - { - glutBitmapCharacter (CPTN_FONT, cptn_value_string[cur_char]); - } - glEnable(GL_LIGHTING); // restore - - glFinish(); - - glPopMatrix(); - - return ERROR_NONE; -} - -int -cptn_substitute_code_with_value (char* caption, int caption_size, - const char* code, char* value) -{ - - char tmp[1024]; - char* found; - - if (strlen(code) < 2) - ErrorReturn(ERROR_BADPARM, - (ERROR_BADPARM, - "cptn_subtitute_code_with_value: code invalid.\n")); - - /* Copy the caption into a tmp string, find the code and replace it - with %s, then use sprintf to copy the value in there. Then copy - it back into the caption and back into the tmp string, and try to - find it again..*/ - strncpy (tmp, caption, sizeof(tmp)); - - found = strstr (tmp, code); - while (NULL != found) - { - found[0] = '%'; /* So "Vertex !V" turns into "Vertex %s" */ - found[1] = 's'; /* which we can use as a sprintf argument. */ - - /* If the code is longer than 2 chars, we need to copy the - string back for each extra char to take up the space. */ - if (strlen(code) > 2) - strcpy (&found[2], &found[strlen(code)]); - - /* Sprintf the value in. */ - snprintf (caption, caption_size, tmp, value); - - /* Copy caption into tmp and find again. */ - strncpy (tmp, caption, sizeof(tmp)); - found = strstr (tmp, code ); - } - - return ERROR_NONE; -} - -/* ---------------------------------------------------------------------- */ - -/* This code only exists if DEBUG_DRAWING_TOOLS is set. */ -#if DEBUG_DRAWING_TOOLS - -int -ddt_initialize () -{ - if (NULL != mris) - { - if (NULL != ddt_hilited_vnos) - free (ddt_hilited_vnos); - if (NULL != ddt_hilited_fnos) - free (ddt_hilited_fnos); - - ddt_hilited_vnos = (int*)calloc (mris->nvertices, sizeof(int)); - ddt_hilited_fnos = (int*)calloc (mris->nvertices, sizeof(int)); - - if (NULL == ddt_hilited_vnos || NULL == ddt_hilited_fnos) - ErrorExit(ERROR_NOMEMORY, - "Couldn't allocate ddt storage for verts or fnos"); - } - else - { - ErrorReturn(ERROR_NOT_INITED, - (ERROR_NOT_INITED, - "ddt_initialize called without mris.\n")); - } - - return (ERROR_NONE); -} - -int -ddt_clear () -{ - if (NULL != ddt_hilited_vnos) - bzero (ddt_hilited_vnos, sizeof(int) * mris->nvertices); - if (NULL != ddt_hilited_fnos) - bzero (ddt_hilited_fnos, sizeof(int) * mris->nvertices); - - return (ERROR_NONE); -} - -int ddt_hilite_vertex (int vno, int type) -{ - if (vno < 0 || vno >= mris->nvertices) - ErrorReturn(ERROR_BADPARM,(ERROR_BADPARM,"ddt_hilite_vertex: bad vno.\n")); - - /* Mark it, but only with a higher type value. */ - if (NULL != ddt_hilited_vnos && - ddt_hilited_vnos[vno] < type) - ddt_hilited_vnos[vno] = type; - - return (ERROR_NONE); -} - -int ddt_get_hilite_vertex_color (int vno, GLubyte* r, GLubyte* g, GLubyte* b) -{ - if (ddt_hilited_vnos[vno]) - { - switch (ddt_hilited_vnos[vno]) - { - case 1: - *r = 200; - *g = 0; - *b = 0; - break; - case 2: - *r = 0; - *g = 255; - *b = 0; - break; - } - } - return (ERROR_NONE); -} - -int ddt_hilite_face (int fno, int type) -{ - FACE* f; - int fvno, vno; - - if (fno < 0 || fno >= mris->nfaces) - ErrorReturn(ERROR_BADPARM,(ERROR_BADPARM,"ddt_hilite_face: bad fno.\n")); - - if (NULL != ddt_hilited_fnos) - { - f = &mris->faces[fno]; - for (fvno = 0; fvno < VERTICES_PER_FACE; fvno++) - { - vno = f->v[fvno]; - /* Mark it, but only with a higher type value. */ - if (ddt_hilited_fnos[vno] < type) - ddt_hilited_fnos[vno] = type; - } - } - - return (ERROR_NONE); -} - - -int ddt_get_hilite_face_color (int vno, GLubyte* r, GLubyte* g, GLubyte* b) -{ - - if (ddt_hilited_fnos[vno]) - { - switch (ddt_hilited_fnos[vno]) - { - case 1: - *r = 100; - *g = 0; - *b = 0; - break; - case 2: - *r = 0; - *g = 100; - *b = 0; - break; - } - } - return (ERROR_NONE); -} - -#endif - -/* ---------------------------------------------------------------------- */ - -int save_tiff (char* fname) -{ - GLint rowlength, skiprows, skippixels, alignment; - GLboolean swapbytes, lsbfirst; - GLubyte* pixel_data = NULL; - GLenum gl_error; - TIFF *tiff = NULL; - tsize_t line_bytes; - unsigned char* line_buffer = NULL; - int scan_line_size; - int strip_size; - int row; - int height, width; - - width = frame_xdim; - height = frame_ydim; - - /* Allocate a buffer for pixels. */ - pixel_data = (GLubyte*) malloc (width * height * 3); - if (NULL == pixel_data) - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY,"Error allocating pixel storage.")); - - /* Read from the front buffer. */ - glReadBuffer (GL_FRONT); - - /* Save our unpack attributes. */ - glGetBooleanv (GL_PACK_SWAP_BYTES, &swapbytes); - glGetBooleanv (GL_PACK_LSB_FIRST, &lsbfirst); - glGetIntegerv (GL_PACK_ROW_LENGTH, &rowlength); - glGetIntegerv (GL_PACK_SKIP_ROWS, &skiprows); - glGetIntegerv (GL_PACK_SKIP_PIXELS, &skippixels); - glGetIntegerv (GL_PACK_ALIGNMENT, &alignment); - - /* Set them. */ - glPixelStorei (GL_PACK_SWAP_BYTES, GL_FALSE); - glPixelStorei (GL_PACK_ROW_LENGTH, 0); - glPixelStorei (GL_PACK_SKIP_ROWS, 0); - glPixelStorei (GL_PACK_SKIP_PIXELS, 0); - glPixelStorei (GL_PACK_ALIGNMENT, 1); - - /* Read RGB pixel data. */ - glReadPixels (0, 0, width, height, GL_RGB, - GL_UNSIGNED_BYTE, (GLvoid*)pixel_data); - - /* Check error at this point. */ - gl_error = glGetError (); - - /* Restore the attributes. */ - glPixelStorei (GL_PACK_SWAP_BYTES, swapbytes); - glPixelStorei (GL_PACK_LSB_FIRST, lsbfirst); - glPixelStorei (GL_PACK_ROW_LENGTH, rowlength); - glPixelStorei (GL_PACK_SKIP_ROWS, skiprows); - glPixelStorei (GL_PACK_SKIP_PIXELS, skippixels); - glPixelStorei (GL_PACK_ALIGNMENT, alignment); - - /* Handle error now. We can bail safely as we've restored the GL - context. */ - if (GL_NO_ERROR != gl_error) - { - free (pixel_data); - ErrorReturn(ERROR_NOMEMORY,(ERROR_NOMEMORY,"Error reading pixels.")); - } - - /* Open a TIFF. */ - tiff = TIFFOpen( fname, "w" ); - if (NULL == tiff) - { - free (pixel_data); - ErrorReturn(ERROR_NOFILE,(ERROR_NOFILE,"Couldn't create file.")); - } - - /* Set the TIFF info. */ - TIFFSetField (tiff, TIFFTAG_IMAGEWIDTH, width); - TIFFSetField (tiff, TIFFTAG_IMAGELENGTH, height); - TIFFSetField (tiff, TIFFTAG_SAMPLESPERPIXEL, 3); - TIFFSetField (tiff, TIFFTAG_BITSPERSAMPLE, 8); - TIFFSetField (tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT); - TIFFSetField (tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); - TIFFSetField (tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); - - /* Calculate some sizes and allocate a line buffer. */ - line_bytes = 3 * width; - line_buffer = NULL; - scan_line_size = TIFFScanlineSize (tiff); - if (scan_line_size != line_bytes) - { - fprintf (stderr,"surfer: scan_line_size %d, line_bytes %d\n", - scan_line_size, (int)line_bytes); - } - - line_buffer = (unsigned char*) _TIFFmalloc( scan_line_size ); - if (NULL == line_buffer) - { - free (pixel_data); - TIFFClose (tiff); - ErrorReturn(ERROR_NOMEMORY, - (ERROR_NOMEMORY,"Couldn't create tiff storage.")); - } - - /* Set the strip size to default. */ - strip_size = TIFFDefaultStripSize (tiff, width * 3); - TIFFSetField (tiff, TIFFTAG_ROWSPERSTRIP, strip_size); - - /* Write line by line (bottom to top). */ - for (row = 0; row < height; row++) - { - memmove (line_buffer, &pixel_data[(height-row-1) * line_bytes], - line_bytes); - TIFFWriteScanline (tiff, line_buffer, row, 0); - } - - /* Close the tiff file and free the line buffer. */ - TIFFClose (tiff); - _TIFFfree (line_buffer); - - free (pixel_data); - - return (NO_ERROR); -} - -/* end rkt */ - -static int -is_val_file(char *fname) -{ - char *dot ; - - dot = strrchr(fname, '.') ; - if (!dot) - return(0) ; - return (!stricmp(dot+1, "w")); -} - -#include "cdflib.h" -#include "sig.h" - -static void -f_to_p(int numer_dof, int denom_dof) -{ - int vno ; - VERTEX *v ; - float sig ; - - surface_compiled = 0 ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - sig = sigf(v->val, numer_dof, denom_dof) ; - if (v->val > 0) - v->stat = -log10(sig) ; - else - v->stat = log10(sig) ; - } -} - -static void -t_to_p(int dof) -{ - int vno ; - VERTEX *v ; - float sig ; - - surface_compiled = 0 ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - sig = sigt(v->val, dof) ; - if (v->val > 0) - v->stat = -log10(sig) ; - else - v->stat = log10(sig) ; - } -} - -static void -f_to_t(void) -{ - int vno ; - VERTEX *v ; - float f ; - - surface_compiled = 0 ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->ripflag) - continue ; - f = v->val ; - v->val = sqrt(abs(f)) ; - if (f < 0) - v->val = -v->val ; - } -} - -static void -label_to_stat(int field) -{ - sclv_new_from_label (field, labl_selected_label); -} - -#include "stc.h" - -static double get_dipole_value(int dipno, int ilat, int plot_type, STC *stc); -static STC *stc ; - - -static void -read_soltimecourse(char *fname) -{ - - surface_compiled = 0 ; - stc = StcRead(fname) ; - if (!stc) - return ; - if (stc->nvertices < stc->m_vals->rows) - sol_nperdip = 3 ; - else - sol_nperdip = 1 ; - printf("setting nperdip to %d\n", sol_nperdip) ; - complexvalflag = 0 ; - colscale = HEAT_SCALE ; - overlayflag = TRUE ; -} - -static void -sol_plot(int timept, int plot_type) -{ - int ilat0,ilat1, nsum, ilat ; - double avgval; - int vno, dip ; - VERTEX *v ; - double val ; - - if (!stc) - { - fprintf(stderr, "stc file not loaded.\n") ; - return ; - } - - surface_compiled = 0 ; - if (sol_nperdip < 1) - { - fprintf(stderr, - "set # of dipoles per location (nperdip) before plotting\n") ; - return ; - } - - ilat0 = floor((timept-dlat/2-stc->epoch_begin_lat)/stc->sample_period+0.5); - ilat1 = floor((timept+dlat/2-stc->epoch_begin_lat)/stc->sample_period+0.5); - printf("ilat0=%d, ilat1=%d\n",ilat0,ilat1); - nsum = ilat1-ilat0+1; - - MRISsetVals(mris, 0.0) ; - MRISclearMarks(mris) ; - for (dip = 0 ; dip < stc->nvertices ; dip++) - { - vno = stc->vertices[dip] ; - if (vno < 0 || vno >= mris->nvertices) - { - printf("vertex # %d out of range\n", vno); - return ; - } - - v = &mris->vertices[vno] ; - avgval = 0.0 ; - for (ilat = ilat0 ; ilat <= ilat1 ; ilat++) - { - val = get_dipole_value(dip, ilat, plot_type, stc) ; - avgval += val ; - } - avgval /= nsum ; - - /* put fMRI weighting in here potentially */ - - v->val = avgval ; - v->fixedval = 1 ; - } - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (v->fixedval || v->ripflag) - continue ; - v->undefval = TRUE ; - } -} - -static double -get_dipole_value(int dipno, int ilat, int plot_type, STC *stc) -{ - double sum, val ; - int i ; - - val = *MATRIX_RELT(stc->m_vals, dipno+1, ilat+1) ; - switch (plot_type) - { - default: - case 0: - if (sol_nperdip == 1) - val = fabs(val) ; - else - { - /* take sqrt of sum of squares */ - sum = 0.0 ; - for (i = 0 ; i < sol_nperdip ; i++) - { - val = *MATRIX_RELT(stc->m_vals, dipno+1+i, ilat+1) ; - sum += (val*val) ; - } - val = sqrt(sum) ; - } - break ; - case 1: - if (sol_nperdip == 3) - { -#if 0 - val = - *MATRIX_RELT(stc->m_vals, sol_nperdip*dip+0+1,ilat+1)*v->dipnx+ - *MATRIX_RELT(stc->m_vals, sol_nperdip*dip+1+1,ilat+1)*v->dipny+ - *MATRIX_RELT(stc->m_vals, sol_nperdip*dip+2+1,ilat+1)*v->dipnz; -#endif - } - break ; - } - return(val) ; -} -#if 1 -double -dipval(int cond_num, int nzdip_num, int ilat) -{ -#if 0 - int ic; - double sum,val; - - val = 0 ; - if (sol_plot_type==0) - { - sum = 0; - for (ic=0;icvertices[sol_dipindex[nzdip_num]].dipnx + - sol_dipcmp_val[cond_num][sol_nperdip*nzdip_num+1][ilat]* - mris->vertices[sol_dipindex[nzdip_num]].dipny + - sol_dipcmp_val[cond_num][sol_nperdip*nzdip_num+2][ilat]* - mris->vertices[sol_dipindex[nzdip_num]].dipnz; - } - if (sol_plot_type==2) val = fabs(val); - } - return val; -#else - return 0.0 ; -#endif -} -#endif -static void -remove_triangle_links(void) -{ - MRISremoveTriangleLinks(mris) ; - surface_compiled = 0 ; -} - -static void -drawcb(void) -{ - draw_colscalebar(); - glFlush() ; -} - - -static void -set_value_label_name(char *label_name, int field) -{ - char cmd[STRLEN] ; - - sprintf (cmd, "UpdateValueLabelName %d \"%s\"", field, label_name); - send_tcl_command (cmd); - sprintf (cmd, "ShowValueLabel %d 1", field); - send_tcl_command (cmd); - sprintf (cmd, "UpdateLinkedVarGroup view"); - send_tcl_command (cmd); -} -static int -draw_curvature_line(void) -{ - static int firsttime = 1 ; - int start_vno, current_vno, end_vno, n, best_n ; - double dot, dx, dy, dz, odx, ody, odz, best_dot, len ; - VERTEX *vn, *vend, *vstart, *vcurrent ; - - if (nmarked < 2) - { - fprintf(stderr, "must origin and end points (previous two)\n"); - return(NO_ERROR) ; - } - - if (firsttime) - { - MRISsaveVertexPositions(mris, TMP_VERTICES) ; - read_inflated_vertex_coordinates() ; - read_white_vertex_coordinates() ; - MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ; - MRISaverageVertexPositions(mris, 25) ; - MRIScomputeMetricProperties(mris) ; - MRIScomputeSecondFundamentalForm(mris) ; - /* compute local basis in tangent bundle */ - MRISrestoreVertexPositions(mris, TMP_VERTICES) ; - firsttime = 0 ; - } - - start_vno = current_vno = marked[0] ; - vstart = &mris->vertices[start_vno] ; - end_vno = marked[1] ; - vend = &mris->vertices[end_vno] ; - vend->marked = 0 ; - - odx = vend->x - vstart->x ; - ody = vend->y - vstart->y ; - odz = vend->z - vstart->z ; - do - { - vcurrent = &mris->vertices[current_vno] ; - vcurrent->marked = 1 ; - odx = vend->infx - vcurrent->infx ; - ody = vend->infy - vcurrent->infy ; - odz = vend->infz - vcurrent->infz ; - best_n = -1 ; - best_dot = 0.0 ; - for (n = 0 ; n < vcurrent->vnum ; n++) - { - vn = &mris->vertices[vcurrent->v[n]] ; - if (vn->marked) - continue ; /* already in line */ - dx = vn->infx - vcurrent->infx ; - dy = vn->infy - vcurrent->infy ; - dz = vn->infz - vcurrent->infz ; - dot = dx*odx + dy*ody + dz*odz ; - if (dot < 0) - continue ; - dx = vn->x - vcurrent->x ; - dy = vn->y - vcurrent->y ; - dz = vn->z - vcurrent->z ; - len = sqrt(dx*dx + dy*dy + dz*dz) ; - if (FZERO(len)) - continue ; - dx /= len ; - dy /= len ; - dz /= len ; - dot = dx*vcurrent->e2x + dy*vcurrent->e2y + dz*vcurrent->e2z ; - if (fabs(dot) > best_dot) - { - best_dot = fabs(dot) ; - best_n = n ; - } - } - if (best_n < 0) - break ; - draw_cursor(current_vno, FALSE) ; - current_vno = vcurrent->v[best_n] ; - if (current_vno != end_vno) - { -#if 1 - marked[nmarked++] = current_vno ; -#else - mark_vertex(current_vno, TRUE) ; - draw_cursor(current_vno, TRUE) ; - /* redraw() ;*/ -#endif - } - } - while (current_vno != end_vno) ; - - redraw() ; - return(NO_ERROR) ; -} - -void -transform_brain(void) -{ - int vno ; - VERTEX *v ; - float x, y, z, xt, yt, zt ; - float xlo, ylo, zlo, xhi, yhi, zhi ; - - if (!lta) - return ; - - xhi=yhi=zhi= -10000; - xlo=ylo=zlo= 10000; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - x = v->x ; - y = v->y ; - z = v->z ; - LTAworldToWorld(lta, x, y, z, &xt, &yt, &zt) ; - v->x = xt ; - v->y = yt ; - v->z = zt ; - if (v->x > xhi) xhi = v->x; - if (v->x < xlo) xlo = v->x; - if (v->y > yhi) yhi = v->y; - if (v->y < ylo) ylo = v->y; - if (v->z > zhi) zhi = v->z; - if (v->z < zlo) zlo = v->z; - } - - mris->xlo = xlo ; - mris->ylo = ylo ; - mris->zlo = zlo ; - mris->xctr = (xhi + xlo)/2 ; - mris->yctr = (yhi + ylo)/2 ; - mris->zctr = (zhi + zlo)/2 ; - MRIScomputeMetricProperties(mris) ; - vset_save_surface_vertices(VSET_MAIN) ; - vset_set_current_set(vset_current_set) ; - redraw() ; -} - -static void -label_set_stats(float val) -{ - int i ; - LABEL *area ; - - if (labl_selected_label< 0) - return; - area = labl_labels[labl_selected_label].label ; - for (i = 0 ; i < area->n_points ; i++) - area->lv[i].stat = val ; -} - -static void -label_from_stats(int field) -{ - int n, vno, new_index ; - VERTEX *v ; - float val =0.0; - LABEL *l ; - char tcl_command[STRLEN] ; - - for (n = vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (vno == Gdiag_no) - DiagBreak() ; - if (v->ripflag) - continue ; - - sclv_get_value(v, field, &val) ; - if (!FZERO(val)) - n++ ; - } - - l = LabelAlloc(n, NULL, NULL) ; - strncpy( l->subject_name, pname, 100 ); - for (n = vno = 0 ; vno < mris->nvertices ; vno++) - { - v = &mris->vertices[vno] ; - if (vno == Gdiag_no) - DiagBreak() ; - if (v->ripflag) - continue ; - - sclv_get_value(v, field, &val) ; - if (!FZERO(val)) - { - l->lv[n].vno = vno ; - l->lv[n].x = v->x ; - l->lv[n].y = v->y ; - l->lv[n].z = v->z ; - l->lv[n].stat = val ; - n++ ; - } - } - l->n_points = n ; - LabelToWhite (l, mris); - /* add this label to our list. */ - labl_add (l, &new_index); - printf("new label created at index %d with %d points\n", new_index, n) ; - - /* select this label */ - labl_select (new_index); - - surface_compiled = 0 ; - - /* if the fill dlog is open, this will update it. */ - sprintf (tcl_command, "LabelsChanged"); - send_tcl_command (tcl_command); -} - -/*! - \fn void LoadMRISMask(void) - \brief Part of a crude hack to allow masking -*/ -void LoadMRISMask(void) -{ - extern MRI *mrismask; - extern double mrismaskthresh; - extern char *mrismaskfile; - extern MRIS *mris; - int reshapefactor; - char *threshstring; - MRI *mritmp; - - // check whether already loaded - if (mrismask != NULL) return; - - if (mrismaskfile == NULL) - { - mrismaskfile = getenv("TKS_MRIS_MASK_FILE"); - if (mrismaskfile == NULL) return; - } - - printf("Reading mris mask %s\n",mrismaskfile); - mrismask = MRIread(mrismaskfile); - if (mrismask == NULL) exit(1); - - if (mrismask->height != 1 || mrismask->depth != 1) - { - reshapefactor = mrismask->height * mrismask->depth; - printf("Reshaping %d\n",reshapefactor); - mritmp = mri_reshape(mrismask, reshapefactor*mrismask->width, - 1, 1, mrismask->nframes); - MRIfree(&mrismask); - mrismask = mritmp; - reshapefactor = 0; /* reset for output */ - } - if (mrismask->width != mris->nvertices) - { - printf("ERROR: dimension mismatch between mask and surf\n"); - exit(1); - } - - if (mrismaskthresh < 0) - { - threshstring = getenv("TKS_MRIS_MASK_THRESH"); - if (threshstring == NULL) return; - sscanf(threshstring,"%lf",&mrismaskthresh); - printf("mris mask thresh = %lf\n",mrismaskthresh); - } -} - -int dngheat(float f, float *r, float *g, float *b) -{ - static float x0 = 0.0; - static float x1 = 1.0/3.0; - static float x2 = 1.0; - static float a1 = 0.5625; - static float a2 = 0.4375; //1-a1 - float absf, c1=0, cg=0, c3=0; - - absf = fabs(f); - - if(absf >= x0 && absf <= x1){ - c1 = a1 + a2*absf/(x1-x0); - cg = 0.0; - c3 = 0.0; - } - if(absf > x1 && absf <= x2){ - c1 = 1; - cg = (absf-x1)/(x2-x1); - c3 = 0.0; - } - if(absf > x2){ - c1 = 1.0; - cg = 1.0; - c3 = 0.0; - } - - *g = cg; - if(f >= 0.0){ - *r = c1; - *b = c3; - } else { - *r = c3; - *b = c1; - } - return(0); -} - -int dngcolorwheel(float f, float *r, float *g, float *b) -{ - static float x0 = 0.0; - static float x1 = 1.0/6.0; - static float x2 = 2.0/6.0; - static float x3 = 3.0/6.0; - static float x4 = 4.0/6.0; - static float x5 = 5.0/6.0; - static float x6 = 1.0; - float f2, xA, xB; - - f2 = f/2; // expecting -1 <= f <= +1, so -0.5 <= f2 <= +0.5 - if(fabs(f2) > 0.5) f2 = remainder(f2,0.5); // force it - f2 = f2 + 0.5; // recenter so that 0 <= f2 <= +1 - - xA = x0; - xB = x1; - if(f2 >= xA && f2 < xB){ - *r = 1.0; - *g = (f2-xA)/(xB-xA); - *b = 0.0; - return(0); - } - - xA = x1; - xB = x2; - if(f2 >= xA && f2 < xB){ - *r = 1.0 - (f2-xA)/(xB-xA); - *g = 1.0; - *b = 0.0; - return(0); - } - - xA = x2; - xB = x3; - if(f2 >= xA && f2 < xB){ - *r = 0.0; - *g = 1.0; - *b = (f2-xA)/(xB-xA); - return(0); - } - - xA = x3; - xB = x4; - if(f2 >= xA && f2 < xB){ - *r = 0.0; - *g = 1.0 - (f2-xA)/(xB-xA); - *b = 1.0; - return(0); - } - - xA = x4; - xB = x5; - if(f2 >= xA && f2 < xB){ - *r = (f2-xA)/(xB-xA); - *g = 0.0; - *b = 1.0; - return(0); - } - - xA = x5; - xB = x6; - *r = 1.0; - *g = 0.0; - *b = 1.0 - (f2-xA)/(xB-xA); - return(0); - -} -#define MAX_STEPS 100 -void -set_area_thresh(float target_area) -{ - char cmd[STRLEN]; - int vno ; - float thresh_min, thresh, thresh_max, val, area, best_thresh, thresh_step, best_area ; - - val = 0 ; - thresh_min = 1e10 ; thresh_max = -thresh_min ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - sclv_get_value( &mris->vertices[vno],sclv_current_field, &val); - if (val < thresh_min) - thresh_min = val ; - if (val > thresh_max) - thresh_max = val ; - } - - thresh_step = (thresh_max - thresh_min) / MAX_STEPS ; - best_thresh = thresh_min ; - best_area = -1 ; - for (thresh = thresh_min ; thresh <= thresh_max ; thresh += thresh_step) - { - area = 0 ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - sclv_get_value( &mris->vertices[vno],sclv_current_field, &val); - if (val > thresh) - area += mris->vertices[vno].area ; - } - if (best_area < 0 || fabs(area-target_area) < best_area) - { - best_area = area ; - best_thresh = thresh ; - } - } - fthresh = best_thresh ; - fslope = 1/best_thresh ; - fmid = 2*fthresh ; - printf("best threshold at %2.5f (%2.5f), %2.2fmm\n", fthresh, fslope, best_area) ; - sclv_field_info[sclv_current_field].fslope = fslope ; - sclv_field_info[sclv_current_field].fthresh = fthresh; - vertex_array_dirty = 1 ; - sprintf (cmd, "UpdateLinkedVarGroup overlay"); - send_tcl_command (cmd); -} - -void -set_thresh(float target_area) -{ - char cmd[STRLEN]; - int vno ; - float thresh_min, thresh, thresh_max, val, area, best_thresh, thresh_step, best_area ; - - val = 0 ; - thresh_min = 1e10 ; thresh_max = -thresh_min ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - sclv_get_value( &mris->vertices[vno],sclv_current_field, &val); - if (val < thresh_min) - thresh_min = val ; - if (val > thresh_max) - thresh_max = val ; - } - - thresh_step = (thresh_max - thresh_min) / MAX_STEPS ; - best_thresh = thresh_min ; - best_area = -1 ; - for (thresh = thresh_min ; thresh <= thresh_max ; thresh += thresh_step) - { - area = 0 ; - for (vno = 0 ; vno < mris->nvertices ; vno++) - { - sclv_get_value( &mris->vertices[vno],sclv_current_field, &val); - if (val > thresh) - area += mris->vertices[vno].area ; - } - if (best_area < 0 || fabs(area-target_area) < best_area) - { - best_area = area ; - best_thresh = thresh ; - } - } - fthresh = best_thresh ; - fslope = 1/best_thresh ; - fmid = 2*fthresh ; - printf("best threshold at %2.5f (%2.5f), %2.2fmm\n", fthresh, fslope, best_area) ; - sclv_field_info[sclv_current_field].fslope = fslope ; - sclv_field_info[sclv_current_field].fthresh = fthresh; - vertex_array_dirty = 1 ; - sprintf (cmd, "UpdateLinkedVarGroup overlay"); - send_tcl_command (cmd); -} - diff --git a/trc/dmri_forrest.cxx b/trc/dmri_forrest.cxx index 59a90ee72fb..3ccfe98eff3 100644 --- a/trc/dmri_forrest.cxx +++ b/trc/dmri_forrest.cxx @@ -76,7 +76,7 @@ vector tractFileList; struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -106,7 +106,7 @@ int main(int argc, char **argv) { Forrest myforrest; - TimerStart(&cputimer); + cputimer.reset(); cout << "Reading test subject data..." << endl; myforrest.ReadTestSubject(testDir, maskFile, asegFile, orientFile); @@ -188,7 +188,7 @@ int main(int argc, char **argv) { } } - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); cout << "Done in " << cputime/1000.0 << " sec." << endl; cout << "dmri_forrest done" << endl; diff --git a/trc/dmri_group.cxx b/trc/dmri_group.cxx index 78576f7e687..872e93cf7f3 100644 --- a/trc/dmri_group.cxx +++ b/trc/dmri_group.cxx @@ -79,7 +79,7 @@ char *inListFile = NULL, *outRefFile = NULL, *outBase = NULL; struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -127,7 +127,7 @@ int main(int argc, char **argv) { dump_options(stdout); - TimerStart(&cputimer); + cputimer.reset(); // Read output reference volume if (outRefFile) { @@ -758,7 +758,7 @@ if (0) { MatrixFree(&outv2r); } - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); cout << "Done in " << cputime/1000.0 << " sec." << endl; cout << "dmri_group done" << endl; diff --git a/trc/dmri_mergepaths.cxx b/trc/dmri_mergepaths.cxx index 34441041acd..d580b9d6804 100644 --- a/trc/dmri_mergepaths.cxx +++ b/trc/dmri_mergepaths.cxx @@ -76,7 +76,7 @@ char *inDir = NULL, *inFile[100], *outFile = NULL, *ctabFile = NULL; struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -106,7 +106,7 @@ int main(int argc, char **argv) { dump_options(stdout); - TimerStart(&cputimer); + cputimer.reset(); for (int iframe = 0; iframe < nframe; iframe++) { float inmax = 0; @@ -163,7 +163,7 @@ int main(int argc, char **argv) { exit(1); } - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); printf("Done in %g sec.\n", cputime/1000.0); printf("dmri_mergepaths done\n"); diff --git a/trc/dmri_motion.cxx b/trc/dmri_motion.cxx index 15912323dd9..f808fbd6f4e 100644 --- a/trc/dmri_motion.cxx +++ b/trc/dmri_motion.cxx @@ -82,7 +82,7 @@ MRI *dwi; struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -115,7 +115,7 @@ int main(int argc, char **argv) { dump_options(); - TimerStart(&cputimer); + cputimer.reset(); if (inMatFile) { // Estimate between-volume motion int nframe = 0; @@ -385,7 +385,7 @@ int main(int argc, char **argv) { outfile.close(); } - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); cout << "Done in " << cputime/1000.0 << " sec." << endl; cout << "dmri_motion done" << endl; diff --git a/trc/dmri_paths.cxx b/trc/dmri_paths.cxx index 2224c549307..a137a3b5623 100644 --- a/trc/dmri_paths.cxx +++ b/trc/dmri_paths.cxx @@ -87,7 +87,7 @@ vector outDir, inDirList, initFile, roiFile1, roiFile2, struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -187,7 +187,7 @@ int main(int argc, char **argv) { cout << "Processing pathway " << iout+1 << " of " << outDir.size() << "..." << endl; - TimerStart(&cputimer); + cputimer.reset(); //if (mycoffin.RunMcmcFull()) if (mycoffin.RunMcmcSingle()) @@ -195,7 +195,7 @@ int main(int argc, char **argv) { else cout << "ERROR: Pathway reconstruction failed" << endl; - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); printf("Done in %g sec.\n", cputime/1000.0); } diff --git a/trc/dmri_pathstats.cxx b/trc/dmri_pathstats.cxx index 5509657853b..b61db8a7e17 100644 --- a/trc/dmri_pathstats.cxx +++ b/trc/dmri_pathstats.cxx @@ -87,7 +87,7 @@ MRI *l1, *l2, *l3, *v1; struct utsname uts; char *cmdline, cwd[2000], subjName[100], pathName[100] ; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -120,7 +120,7 @@ int main(int argc, char **argv) { dump_options(stdout); printf("Computing statistics on %s...\n", inTrcDir?inTrcDir:inTrkFile); - TimerStart(&cputimer); + cputimer.reset(); if (dtBase) { sprintf(fname, "%s_L1.nii.gz", dtBase); @@ -494,7 +494,7 @@ int main(int argc, char **argv) { fvox.close(); } - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); printf("Done in %g sec.\n", cputime/1000.0); printf("dmri_pathstats done\n"); diff --git a/trc/dmri_spline.cxx b/trc/dmri_spline.cxx index 42b11e35822..69d17658dca 100644 --- a/trc/dmri_spline.cxx +++ b/trc/dmri_spline.cxx @@ -77,7 +77,7 @@ char *inFile = NULL, *maskFile = NULL, struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -108,11 +108,11 @@ int main(int argc, char **argv) { Spline myspline(inFile, maskFile); printf("Computing spline...\n"); - TimerStart(&cputimer); + cputimer.reset(); myspline.InterpolateSpline(); - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); printf("Done in %g sec.\n", cputime/1000.0); if (outVolFile) @@ -125,13 +125,13 @@ int main(int argc, char **argv) { char fname[PATH_MAX]; printf("Computing analytical tangent, normal, and curvature...\n"); - TimerStart(&cputimer); + cputimer.reset(); myspline.ComputeTangent(true); myspline.ComputeNormal(true); myspline.ComputeCurvature(true); - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); printf("Done in %g sec.\n", cputime/1000.0); // Write tangent, normal, and curvature (analytical) to text files @@ -143,13 +143,13 @@ int main(int argc, char **argv) { myspline.WriteCurvature(fname); printf("Computing discrete tangent, normal, and curvature...\n"); - TimerStart(&cputimer); + cputimer.reset(); myspline.ComputeTangent(false); myspline.ComputeNormal(false); myspline.ComputeCurvature(false); - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); printf("Done in %g sec.\n", cputime/1000.0); // Write tangent, normal, and curvature (discrete) to text files diff --git a/trc/dmri_train.cxx b/trc/dmri_train.cxx index 108e61ab2ef..a989b30248c 100644 --- a/trc/dmri_train.cxx +++ b/trc/dmri_train.cxx @@ -82,7 +82,7 @@ char *outDir = NULL, *outTestDir = NULL, struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -151,7 +151,7 @@ int main(int argc, char **argv) { cout << "Processing pathway " << itrk+1 << " of " << trainTrkList.size() << "..." << endl; - TimerStart(&cputimer); + cputimer.reset(); myblood.ComputePriors(); @@ -170,7 +170,7 @@ int main(int argc, char **argv) { else myblood.WriteOutputs(fbase); - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); cout << "Done in " << cputime/1000.0 << " sec." << endl; } diff --git a/trc/dmri_trk2trk.cxx b/trc/dmri_trk2trk.cxx index 3def8d4b203..360910a1b14 100644 --- a/trc/dmri_trk2trk.cxx +++ b/trc/dmri_trk2trk.cxx @@ -87,7 +87,7 @@ vector incMask, excMask; struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -164,7 +164,7 @@ int main(int argc, char **argv) { cout << "Processing input file " << itract+1 << " of " << nTract << "..." << endl; - TimerStart(&cputimer); + cputimer.reset(); if (!inTrkList.empty()) { // Read streamlines from .trk file if (inDir) @@ -713,7 +713,7 @@ int main(int argc, char **argv) { trkwriter.Close(); } - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); cout << "Done in " << cputime/1000.0 << " sec." << endl; } diff --git a/trc/dmri_vox2vox.cxx b/trc/dmri_vox2vox.cxx index 653f75d9a3c..9ae26f82364 100644 --- a/trc/dmri_vox2vox.cxx +++ b/trc/dmri_vox2vox.cxx @@ -78,7 +78,7 @@ char *inDir = NULL, *inFile[100], struct utsname uts; char *cmdline, cwd[2000]; -struct timeb cputimer; +Timer cputimer; /*--------------------------------------------------*/ int main(int argc, char **argv) { @@ -136,7 +136,7 @@ int main(int argc, char **argv) { vector inpts; printf("Processing coordinate file %d of %d...\n", k+1, nout); - TimerStart(&cputimer); + cputimer.reset(); // Read input text file if (inDir) @@ -201,7 +201,7 @@ int main(int argc, char **argv) { outfile.close(); - cputime = TimerStop(&cputimer); + cputime = cputimer.milliseconds(); printf("Done in %g sec.\n", cputime/1000.0); } diff --git a/tridec/CMakeLists.txt b/tridec/CMakeLists.txt index 93f5814e29c..5c37ce2d260 100644 --- a/tridec/CMakeLists.txt +++ b/tridec/CMakeLists.txt @@ -2,7 +2,7 @@ project(tridec) include_directories(${FS_INCLUDE_DIRS}) -add_executable(tridec tridec.c) +add_executable(tridec tridec.cpp) target_link_libraries(tridec utils) install(TARGETS tridec DESTINATION bin) diff --git a/tridec/tridec.c b/tridec/tridec.cpp similarity index 100% rename from tridec/tridec.c rename to tridec/tridec.cpp diff --git a/utils/Bruker.c b/utils/Bruker.cpp similarity index 99% rename from utils/Bruker.c rename to utils/Bruker.cpp index 97b51837546..109a6e3e515 100644 --- a/utils/Bruker.c +++ b/utils/Bruker.cpp @@ -142,8 +142,6 @@ /* Martin Hoerrmann. */ -char *BRUCKER_C_VERSION = "$Revision: 1.12 $"; - #include #include #include @@ -784,10 +782,6 @@ int readBrukerReco(char *recoFile, BrukerTransform *pTran) return 1; } -#ifdef Linux -extern void swab(const void *from, void *to, size_t n); -#endif - int readBrukerVolume(MRI *mri, char *dataFile) { FILE *fp = 0; diff --git a/utils/CMakeLists.txt b/utils/CMakeLists.txt index baccc99701c..52522832fa7 100644 --- a/utils/CMakeLists.txt +++ b/utils/CMakeLists.txt @@ -1,314 +1,216 @@ project(utils) +add_compile_options(-Wno-pointer-arith) + include_directories( - ${FS_INCLUDE_DIRS} - ${CMAKE_SOURCE_DIR}/include/dicom - ${CMAKE_SOURCE_DIR}/include/NrrdIO + ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/packages/jpeg - ${CMAKE_SOURCE_DIR}/packages/expat ${CMAKE_SOURCE_DIR}/packages/tiff ${CMAKE_SOURCE_DIR}/packages/xml2 - ${CMAKE_SOURCE_DIR}/packages/glut + ${CMAKE_SOURCE_DIR}/packages/minc + ${CMAKE_SOURCE_DIR}/packages/netcdf + ${CMAKE_SOURCE_DIR}/packages/nrrdio + ${CMAKE_SOURCE_DIR}/packages/dicom + ${CMAKE_SOURCE_DIR}/packages/cephes + ${CMAKE_SOURCE_DIR}/packages/nifti + ${CMAKE_SOURCE_DIR}/packages/gifti ${X11_INCLUDE_DIR} ${ITK_INCLUDE_DIRS} ) -set(SOURCES - afni.c - annotation.c - art1.c - artmap.c - aseg_edit_svm.c - autoencoder.c - backprop.c - bfileio.c - box.c - Bruker.c - chklc.c - chronometer.c +add_library(utils STATIC + afni.cpp + annotation.cpp + argparse.cpp + autoencoder.cpp + bfileio.cpp + box.cpp + Bruker.cpp + chklc.cpp + chronometer.cpp chronometerpp.cpp - class_array.c - cluster.c - cma.c - cmat.c - cmat.c - cmdargs.c - colortab.c - connectcomp.c - corio.c + class_array.cpp + cluster.cpp + cma.cpp + cmat.cpp + cmat.cpp + cmdargs.cpp + colortab.cpp + connectcomp.cpp + corio.cpp cpputils.cpp - ctrpoints.c - cvector.c - dcdflib.c - dct.c - density.c - diag.c - DICOMRead.c - diffuse.c - dmatrix.c - dti.c - dtk.fs.c - error.c - evschutils.c - fcd.c - fftutils.c - field_code.c - filter.c - fio.c - flash.c - fmarchmesh.c - fmriutils.c + ctrpoints.cpp + cvector.cpp + dct.cpp + density.cpp + diag.cpp + DICOMRead.cpp + diffuse.cpp + dmatrix.cpp + dti.cpp + dtk.fs.cpp + error.cpp + evschutils.cpp + fcd.cpp + fftutils.cpp + field_code.cpp + filter.cpp + fio.cpp + flash.cpp + fmriutils.cpp fs_cost_function.cpp fs_lbfgs.cpp fs_lbfgs_observer.cpp fs_lbfgs_subject.cpp fs_powell.cpp - fsenv.c - fsgdf.c - fsglm.c - fsinit.c - fsPrintHelp.c - gca.c - gcaboundary.c + fsenv.cpp + fsgdf.cpp + fsglm.cpp + fsinit.cpp + fsPrintHelp.cpp + gca.cpp + gcaboundary.cpp gcalinearnode.cpp gcalinearprior.cpp gcamcomputeLabelsLinearCPU.cpp - gcamorph.c + gcamorph.cpp gcamorphtestutils.cpp - gcarray.c gcautils.cpp - gclass.c - gcsa.c - geos.c - getdelim.c - getline.c - gifti_io.c - gifti_local.c - gifti_xml.c - gtm.c - gw_ic2562.c - gw_utils.c - handle.c - heap.c - hippo.c - histo.c - ic12.c - ic163842.c - ic2562.c - ic42.c - ic642.c - icosahedron.c - image.c - imageio.c - imautils.c - intensity_eig.c - ipmpar.c - joint_histo.c - kernel.c - kinput.c - label.c - lpafile.c - machine.c - MARS_DT_Boundary.c - matfile.c - matrix.c - mgh_filter.c - mgh_matrix.c - min_heap.c - mincutils.c - minmaxrc.c - morph.c - mosaic.c - mri.c - mri2.c - mri_conform.c + gclass.cpp + gcsa.cpp + geos.cpp + getdelim.cpp + getline.cpp + gifti.cpp + gtm.cpp + gw_ic2562.cpp + gw_utils.cpp + hippo.cpp + hips.cpp + histo.cpp + ic12.cpp + ic163842.cpp + ic2562.cpp + ic42.cpp + ic642.cpp + icosahedron.cpp + image.cpp + imageio.cpp + imautils.cpp + intensity_eig.cpp + ipmpar.cpp + joint_histo.cpp + kernel.cpp + label.cpp + log.cpp + lut.cpp + machine.cpp + MARS_DT_Boundary.cpp + matfile.cpp + matrix.cpp + mgh_filter.cpp + min_heap.cpp + morph.cpp + mosaic.cpp + mri.cpp + mri2.cpp + mri_conform.cpp mri_fastmarching.cpp - mri_identify.c - mri_level_set.c - mri_tess.c - mri_topology.c - mri_transform.c - mriBSpline.c - mriclass.c - mricurv.c - mrifilter.c - mriflood.c - mriFunctionalDataAccess.c - mriHeadPointList.c - mrihisto.c - mriio.c - mriio_nrrd.c - mriio_nrrd_itk.cpp - MRIio_old.c - mrimorph.c - mrinorm.c - mripolv.c - mriprob.c - mris_compVolFrac.c - mrisbiorthogonalwavelets.c - mrisegment.c - mriset.c - mrishash.c - mrisp.c - MRISrigidBodyAlignGlobal.c - mrisurf.c - mrisurf_base.c - mrisurf_deform.c - mrisurf_defect.c - mrisurf_integrate.c - mrisurf_io.c - mrisurf_metricProperties.c - mrisurf_mri.c - mrisurf_obsolete.c - mrisurf_timeStep.c - mrisurf_topology.c - mrisurf_vals.c - mriSurface.c - mrisutils.c - mriTransform.c - mriVolume.c - mrivoxel.c - nifti1_io.c + mri_identify.cpp + mri_level_set.cpp + mri_tess.cpp + mri_topology.cpp + mriBSpline.cpp + mriclass.cpp + mricurv.cpp + mrifilter.cpp + mriflood.cpp + mrihisto.cpp + mriio.cpp + MRIio_old.cpp + mrimorph.cpp + mrinorm.cpp + mripolv.cpp + mriprob.cpp + mris_compVolFrac.cpp + mris_fastmarching.cpp + mrisegment.cpp + mriset.cpp + mrishash.cpp + mrisp.cpp + MRISrigidBodyAlignGlobal.cpp + mrisurf.cpp + mrisurf_base.cpp + mrisurf_defect.cpp + mrisurf_deform.cpp + mrisurf_integrate.cpp + mrisurf_io.cpp + mrisurf_metricProperties.cpp + mrisurf_mri.cpp + mrisurf_obsolete.cpp + mrisurf_timeStep.cpp + mrisurf_topology.cpp + mrisurf_vals.cpp + mrisutils.cpp + mriTransform.cpp + mrivoxel.cpp numerics.cpp - offset.c - path.c - pdf.c - pgmstubs.c - prime.c - Progname.c - queue.c - randomfields.c - rbf.c - rbm.c - realm.c - rec.c - region.c - registerio.c - resample.c - rescale.c - retinotopy.c - rfa.c - rforest.c - rfutils.c - romp_support.c - selxavgio.c - sig.c - signa.c - stats.c - stc.c - surfcluster.c - surfgrad.c - svm.c - tags.c - talairachex.c - thread.c - timer.c - transform.c - tritri.c - tukey.c - utils.c - version.c - vertexRotator.c - vlabels.c - volcluster.c - voxlist.c - x3DList.c - xDebug.c - xGLutWindow.c - xGrowableArray.c - xList.c - xSparseVolume.c - xTypes.c - xUndoList.c - xUtilities.c - xVoxel.c - znzlib.c -) - -# add cephes sources -set(SOURCES ${SOURCES} - cephes/bdtr.c - cephes/chdtr.c - cephes/const.c - cephes/fdtr.c - cephes/gamma.c - cephes/igam.c - cephes/igami.c - cephes/incbet.c - cephes/incbi.c - cephes/mtherr.c - cephes/ndtr.c - cephes/ndtri.c - cephes/polevl.c - cephes/stdtr.c -) - -# nrrdio-required definitions -add_definitions(-DTEEM_DIO=0 -DTEEM_QNANHIBIT=1 -DTEEM_ENDIAN=${BYTEORDER}) - -if(CMAKE_SIZEOF_VOID_P EQUAL 8) - add_definitions(-DTEEM_32BIT=0) -elseif(CMAKE_SIZEOF_VOID_P EQUAL 4) - add_definitions(-DTEEM_32BIT=1) -endif() - -# add NrrdIO sources -set(SOURCES ${SOURCES} - NrrdIO/754.c - NrrdIO/formatPNG.c - NrrdIO/accessors.c - NrrdIO/formatPNM.c - NrrdIO/array.c - NrrdIO/formatText.c - NrrdIO/arraysNrrd.c - NrrdIO/formatVTK.c - NrrdIO/axis.c - NrrdIO/gzio.c - NrrdIO/biffbiff.c - NrrdIO/keyvalue.c - NrrdIO/comment.c - NrrdIO/methodsNrrd.c - NrrdIO/defaultsNrrd.c - NrrdIO/miscAir.c - NrrdIO/dio.c - NrrdIO/mop.c - NrrdIO/encodingAscii.c - NrrdIO/parseAir.c - NrrdIO/encodingBzip2.c - NrrdIO/parseNrrd.c - NrrdIO/encoding.c - NrrdIO/encodingGzip.c - NrrdIO/encodingHex.c - NrrdIO/read.c - NrrdIO/encodingRaw.c - NrrdIO/reorder.c - NrrdIO/endianAir.c - NrrdIO/endianNrrd.c - NrrdIO/sane.c - NrrdIO/enum.c - NrrdIO/simple.c - NrrdIO/enumsNrrd.c - NrrdIO/string.c - NrrdIO/format.c - NrrdIO/subset.c - NrrdIO/formatEPS.c - NrrdIO/write.c - NrrdIO/formatNRRD.c + offset.cpp + path.cpp + pdf.cpp + pgmstubs.cpp + pointset.cpp + prime.cpp + Progname.cpp + randomfields.cpp + rbf.cpp + rbm.cpp + realm.cpp + region.cpp + registerio.cpp + resample.cpp + retinotopy.cpp + rfa.cpp + rforest.cpp + rfutils.cpp + rgb.cpp + romp_support.cpp + selxavgio.cpp + sig.cpp + signa.cpp + stats.cpp + surfcluster.cpp + surfgrad.cpp + svm.cpp + tags.cpp + talairachex.cpp + timer.cpp + transform.cpp + tritri.cpp + tukey.cpp + utils.cpp + version.cpp + vertexRotator.cpp + vlabels.cpp + volcluster.cpp + voxlist.cpp + xDebug.cpp + xTypes.cpp + xVoxel.cpp ) -add_library(utils STATIC ${SOURCES}) - target_link_libraries(utils - rgb - hipsstubs - dicom - log jpeg - expat tiff xml2 minc netcdf + nrrdio + dicom + cephes + nifti + gifti + expat ${ZLIB_LIBRARIES} ${ITK_LIBRARIES} ) @@ -319,27 +221,15 @@ endif() # utils binaries -set(GIFTI_SOURCES gifti_io.c gifti_xml.c nifti1_io.c znzlib.c) - -# gifti_tool -add_executable(gifti_tool gifti_tool.c ${GIFTI_SOURCES}) -target_link_libraries(gifti_tool expat ${ZLIB_LIBRARIES}) -install(TARGETS gifti_tool DESTINATION bin) - -# gifti test -add_executable(gifti_test gifti_test.c ${GIFTI_SOURCES}) -target_link_libraries(gifti_test expat ${ZLIB_LIBRARIES}) -install(TARGETS gifti_test DESTINATION bin) - -# xmlToHtml -add_executable(xmlToHtml xmlToHtml.c) -target_link_libraries(xmlToHtml xml2 expat ${ZLIB_LIBRARIES}) -install(TARGETS xmlToHtml DESTINATION bin) +# # xmlToHtml +# add_executable(xmlToHtml xmlToHtml.c) +# target_link_libraries(xmlToHtml xml2 ${ZLIB_LIBRARIES}) +# install(TARGETS xmlToHtml DESTINATION bin) -# fsPrintHelp -add_executable(fsPrintHelp fsPrintHelp.c) -target_compile_definitions(fsPrintHelp PRIVATE BUILD_MAIN) -target_link_libraries(fsPrintHelp xml2 ${ZLIB_LIBRARIES}) -install(TARGETS fsPrintHelp DESTINATION bin) +# # fsPrintHelp +# add_executable(fsPrintHelp fsPrintHelp.c) +# target_compile_definitions(fsPrintHelp PRIVATE BUILD_MAIN) +# target_link_libraries(fsPrintHelp xml2 ${ZLIB_LIBRARIES}) +# install(TARGETS fsPrintHelp DESTINATION bin) -add_subdirectory(test) +# add_subdirectory(test) diff --git a/utils/DICOMRead.c b/utils/DICOMRead.cpp similarity index 99% rename from utils/DICOMRead.c rename to utils/DICOMRead.cpp index ab30e70485a..038d2d94c6c 100644 --- a/utils/DICOMRead.c +++ b/utils/DICOMRead.cpp @@ -1323,7 +1323,7 @@ int AllocElementData(DCM_ELEMENT *e) char *ElementValueString(DCM_ELEMENT *e, int DoBackslash) { char *evstring=NULL; - int n, len; + unsigned int n, len; char tmpstr[2000]; char tmpstr2[2000]; @@ -1541,7 +1541,7 @@ char *SiemensAsciiTagEx(const char *dcmfile, const char *TagString, int cleanup) static int MAX_ASCIILIST = 512; static int INCREMENT = 64; - int i, k; + int k; FILE *fp; char buf[1024]; char command[1024 + 32]; @@ -1567,7 +1567,7 @@ char *SiemensAsciiTagEx(const char *dcmfile, const char *TagString, int cleanup) // cleanup section. Make sure to set cleanup =1 at the final call // don't rely on TagString but the last flag only if (cleanup == 1) { - for (i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) { if (lists[i]) { free(lists[i]); lists[i] = 0; @@ -1593,7 +1593,7 @@ char *SiemensAsciiTagEx(const char *dcmfile, const char *TagString, int cleanup) // backslashes in front of any parens memset(&filename[0], 0, 1024); k = 0; - for (i = 0; i < strlen(dcmfile); i++) { + for (unsigned int i = 0; i < strlen(dcmfile); i++) { if (dcmfile[i] == '(' || dcmfile[i] == ')' || dcmfile[i] == '[' || dcmfile[i] == ']') { filename[k] = 92; // 92 is ascii dec for backslash k++; @@ -1603,7 +1603,7 @@ char *SiemensAsciiTagEx(const char *dcmfile, const char *TagString, int cleanup) } // free allocated list of strings - for (i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) { if (lists[i]) { free(lists[i]); lists[i] = 0; @@ -1652,7 +1652,7 @@ char *SiemensAsciiTagEx(const char *dcmfile, const char *TagString, int cleanup) { lists = newlists; // update the pointer // initialize uninitialized list - for (i = 0; i < INCREMENT; ++i) { + for (int i = 0; i < INCREMENT; ++i) { lists[MAX_ASCIILIST + i] = (char *)0; } MAX_ASCIILIST = newSize; @@ -1672,7 +1672,7 @@ char *SiemensAsciiTagEx(const char *dcmfile, const char *TagString, int cleanup) } // build up string lists available // search the tag - for (i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) { // get the variable name (the first string) VariableName[0] = 0; sscanf(lists[i], "%s %*s %*s", VariableName); @@ -1727,7 +1727,7 @@ char *SiemensAsciiTag(const char *dcmfile, const char *TagString, int flag) FILE *fp; int dumpline, nthchar; char *rt; - char *BeginStr; + const char *BeginStr; int LenBeginStr; char *TestStr; int nTest; @@ -2004,7 +2004,8 @@ int dcmImageDirCos(const char *dcmfile, float *Vcx, float *Vcy, float *Vcz, floa { DCM_ELEMENT *e; char *s; - int n, nbs; + unsigned int n; + int nbs; float rms; /* Load the direction cosines - this is a string of the form: @@ -2067,7 +2068,8 @@ int dcmImagePosition(const char *dcmfile, float *x, float *y, float *z) { DCM_ELEMENT *e; char *s; - int n, nbs; + unsigned int n; + int nbs; /* Load the Image Position: this is a string of the form: x\y\z */ @@ -4370,7 +4372,8 @@ CONDITION GetMultiDoubleFromString(DCM_OBJECT **object, DCM_TAG tag, double *d[] CONDITION cond; char *s, *ss; void *ctx; - int i, j, mult; + unsigned int i; + int j, mult; attribute.tag = tag; cond = DCM_GetElement(object, tag, &attribute); @@ -4406,7 +4409,8 @@ CONDITION GetMultiShortFromString(DCM_OBJECT **object, DCM_TAG tag, short *us[], CONDITION cond; char *s, *ss; void *ctx; - int i, j, mult; + unsigned int i; + int j, mult; attribute.tag = tag; cond = DCM_GetElement(object, tag, &attribute); @@ -6507,7 +6511,8 @@ int DICOMInfo2MRI(DICOMInfo *dcm, void *data, MRI *mri) int DICOMRead(const char *FileName, MRI **mri, int ReadImage) { MRI *pmri = NULL; - char **CleanedFileNames, **FileNames, *c, PathName[256]; + const char *c; + char **CleanedFileNames, **FileNames, PathName[256]; int i, NumberOfFiles, NumberOfDICOMFiles, nStudies, error; int length; DICOMInfo **aDicomInfo; @@ -6886,8 +6891,7 @@ int dcmGetDWIParamsGE(DCM_OBJECT *dcm, double *pbval, double *pxbvec, double *py DCM_ELEMENT *e; CONDITION cond; DCM_TAG tag; - int n; - unsigned int rtnLength; + unsigned int rtnLength, n; void *Ctx = NULL; if (Gdiag_no > 0) printf("Entering dcmGetDWIParamsGE()\n"); @@ -7119,9 +7123,9 @@ int dcmGetDWIParamsSiemensAlt(DCM_OBJECT *dcm, double *pbval, double *pxbvec, do DCM_ELEMENT *e; CONDITION cond; DCM_TAG tag; - unsigned int rtnLength; + unsigned int rtnLength, m; void *Ctx = NULL; - int n, m, k, bval_flag, bvec_flag, Allow; + int k, bval_flag, bvec_flag, Allow; char c, tmpstr[2000], *pc; double val, rms; @@ -7167,7 +7171,7 @@ int dcmGetDWIParamsSiemensAlt(DCM_OBJECT *dcm, double *pbval, double *pxbvec, do // Scroll through the nasty string and find the keywords bval_flag = 0; bvec_flag = 0; - for (n = 0; n < e->length; n++) { + for (unsigned int n = 0; n < e->length; n++) { c = e->d.string[n]; if (c == 'B') { sscanf(&(e->d.string[n]), "%s", tmpstr); @@ -7258,7 +7262,8 @@ int dcmImageDirCosObject(DCM_OBJECT *dcm, double *Vcx, double *Vcy, double *Vcz, DCM_TAG tag; unsigned int rtnLength; void *Ctx = NULL; - int n, nbs; + unsigned int n; + int nbs; char *s; double rms; diff --git a/utils/MARS_DT_Boundary.c b/utils/MARS_DT_Boundary.cpp similarity index 100% rename from utils/MARS_DT_Boundary.c rename to utils/MARS_DT_Boundary.cpp diff --git a/utils/MRISrigidBodyAlignGlobal.c b/utils/MRISrigidBodyAlignGlobal.cpp similarity index 98% rename from utils/MRISrigidBodyAlignGlobal.c rename to utils/MRISrigidBodyAlignGlobal.cpp index 1b5cf60cf1b..aa633db4cc1 100644 --- a/utils/MRISrigidBodyAlignGlobal.c +++ b/utils/MRISrigidBodyAlignGlobal.cpp @@ -83,8 +83,8 @@ void MRISrigidBodyAlignGlobal_findMinSSE( // Project these coordinates to the surface of a sphere of radius mris->radius // This assumes that the vertices are already well away from (0,0,0) // - { int i; - for (i = 0; i < verticesSize; i++) { + { + for (unsigned int i = 0; i < verticesSize; i++) { float invLength = mris->radius/sqrtf(squaref(xv[i])+squaref(yv[i])+squaref(zv[i])); xv[i] *= invLength; yv[i] *= invLength; @@ -278,7 +278,7 @@ void MRISrigidBodyAlignGlobal_findMinSSE( ROMP_PFLB_begin int const viLo = partition*verticesPerPartition; - int const viHi = MIN(verticesSize, viLo + verticesPerPartition); + int const viHi = MIN(verticesSize, (unsigned)viLo + verticesPerPartition); double* const ssesForAlphas = & ssesForAlphasForPartitions[partition*forAlphasCapacity]; MRISPfunctionValResultForAlpha* const fvsForAlphas = & fvsForAlphasForPartitions[partition*forAlphasCapacity]; @@ -310,8 +310,7 @@ void MRISrigidBodyAlignGlobal_findMinSSE( alphasForAlphas, ajsSize, // input requests vertexTrace); - int ajsI; - for (ajsI = 0; ajsI < ajsSize ; ajsI++) { + for (unsigned int ajsI = 0; ajsI < ajsSize ; ajsI++) { int const aj = ajsForAlphas[ajsI]; double const target = fvsForAlphas[ajsI].curr; double const std = fvsForAlphas[ajsI].next; @@ -395,8 +394,7 @@ void MRISrigidBodyAlignGlobal_findMinSSE( // Add to the output centers // - int ajsI; - for (ajsI = 0; ajsI < ajsSize ; ajsI++) { + for (unsigned int ajsI = 0; ajsI < ajsSize ; ajsI++) { int const aj = ajsForAlphas[ajsI]; int const ai = center_ai + gridStride*(aj - nangles/2); diff --git a/utils/MRIio_old.c b/utils/MRIio_old.cpp similarity index 92% rename from utils/MRIio_old.c rename to utils/MRIio_old.cpp index f7afa7a674a..5cdf541459e 100644 --- a/utils/MRIio_old.c +++ b/utils/MRIio_old.cpp @@ -35,9 +35,9 @@ #include "MRIio_old.h" -static void MGHprint_error(char *str); +static void MGHprint_error(const char *str); -static void MGHprint_error(char *str) +static void MGHprint_error(const char *str) { printf("%s", str); exit(0); @@ -47,7 +47,7 @@ char *lmalloc(unsigned long size) { char *p; - p = malloc(size); + p = (char *)malloc(size); if (p == NULL) MGHprint_error("Cannot malloc()\n"); return p; } @@ -56,7 +56,7 @@ char *lcalloc(size_t nmemb, size_t size) { char *p; - p = calloc(nmemb, size); + p = (char *)calloc(nmemb, size); if (p == NULL) MGHprint_error("Cannot calloc()\n"); return p; } diff --git a/utils/Progname.c b/utils/Progname.cpp similarity index 100% rename from utils/Progname.c rename to utils/Progname.cpp diff --git a/utils/afni.c b/utils/afni.cpp similarity index 99% rename from utils/afni.c rename to utils/afni.cpp index 854180416b1..1b98a47dca0 100644 --- a/utils/afni.c +++ b/utils/afni.cpp @@ -48,10 +48,6 @@ #include "AFNI.h" -#ifdef Linux -extern void swab(const void *from, void *to, size_t n); -#endif - /* ----- flags for keeping track of what we've gotten from the header ----- */ #define AFNI_ALL_REQUIRED 0x0000003f @@ -825,7 +821,7 @@ MRI *afniRead(const char *fname, int read_volume) { pmem = (void *)malloc(bytes_per_voxel * mri->width); if (pmem) { - if (fread(pmem, bytes_per_voxel, mri->width, fp) != mri->width) { + if ((int)fread(pmem, bytes_per_voxel, mri->width, fp) != mri->width) { fclose(fp); MRIfree(&header); errno = 0; @@ -835,7 +831,7 @@ MRI *afniRead(const char *fname, int read_volume) if (swap_flag) { if (bytes_per_voxel == 2) // short { - swab(pmem, pmem, mri->width * 2); + swab(pmem, pmem, (size_t)(mri->width * 2)); } else if (bytes_per_voxel == 4) // float { diff --git a/utils/annotation.c b/utils/annotation.cpp similarity index 98% rename from utils/annotation.c rename to utils/annotation.cpp index 7a39fb7bcf7..33792becd5c 100644 --- a/utils/annotation.c +++ b/utils/annotation.cpp @@ -83,7 +83,8 @@ int print_annotation_colortable(FILE *fp) int read_named_annotation_table(char *name) { FILE *fp; - char *cp, fname[STRLEN], line[STRLEN]; + char fname[STRLEN], line[STRLEN]; + const char *cp; int i; if (num_entries) { @@ -137,7 +138,8 @@ int read_named_annotation_table(char *name) int read_annotation_table(void) { FILE *fp; - char *cp, fname[STRLEN], line[STRLEN]; + char fname[STRLEN], line[STRLEN]; + const char *cp; int i; extern char *annotation_table_file; @@ -202,7 +204,7 @@ int annotation_to_index(int annotation) return (-1); } -char *index_to_name(int index) +const char *index_to_name(int index) { int i; @@ -243,7 +245,7 @@ int index_to_annotation(int index) return (-1); } -char *annotation_to_name(int annotation, int *pindex) +const char *annotation_to_name(int annotation, int *pindex) { int i; @@ -625,7 +627,7 @@ int MRISdivideAnnotationUnit(MRI_SURFACE *mris, int annot, int nunits) parcnames[1] = "rostralmiddlefrontal"; MRISmergeAnnotations(surf, 2, parcnames, "frontal"); */ -int MRISmergeAnnotations(MRIS *mris, int nparcs, char **parcnames, char *newparcname) +int MRISmergeAnnotations(MRIS *mris, int nparcs, std::vector parcnames, const char *newparcname) { int err, nthparc, parcid, nnewparcs, nthnewparc, m, match; int vtxno, *annotlist; @@ -642,9 +644,9 @@ int MRISmergeAnnotations(MRIS *mris, int nparcs, char **parcnames, char *newparc // Get the list of annotation numbers too annotlist = (int *)calloc(nparcs, sizeof(int)); for (m = 0; m < nparcs; m++) { - err = CTABfindName(mris->ct, parcnames[m], &parcid); + err = CTABfindName(mris->ct, parcnames[m].c_str(), &parcid); if (err) { - printf("ERROR: cannot find %s in annotation\n", parcnames[m]); + printf("ERROR: cannot find %s in annotation\n", parcnames[m].c_str()); return (1); } CTABannotationAtIndex(mris->ct, parcid, &(annotlist[m])); @@ -659,7 +661,7 @@ int MRISmergeAnnotations(MRIS *mris, int nparcs, char **parcnames, char *newparc // This checks whether the nth parc is in the list to merge match = 0; for (m = 0; m < nparcs; m++) { - if (!strcmp(mris->ct->entries[nthparc]->name, parcnames[m])) { + if (!strcmp(mris->ct->entries[nthparc]->name, parcnames[m].c_str())) { match = 1; break; } @@ -770,7 +772,7 @@ MRI *MRISannot2border(MRIS *surf) int MRISaparc2lobes(MRIS *surf, int a_lobeDivisionType) { int parcCount = 0; - char *parcnames[64]; + std::vector parcnames(64); parcnames[0] = "caudalmiddlefrontal"; parcnames[1] = "superiorfrontal"; diff --git a/utilscpp/argparse.cpp b/utils/argparse.cpp similarity index 91% rename from utilscpp/argparse.cpp rename to utils/argparse.cpp index 5724b09c6ae..a60800981b1 100644 --- a/utilscpp/argparse.cpp +++ b/utils/argparse.cpp @@ -3,11 +3,8 @@ #include #include -#include "argparse.hpp" - -extern "C" { +#include "argparse.h" #include "utils.h" -} /// Makes sure option key is valid (i.e it isn't empty and @@ -15,11 +12,11 @@ extern "C" { static std::string verifyOption(const std::string& name) { if (name.empty()) - fs_fatal(1) << "invalid argument configuration. Argument names must not be empty"; + logFatal(1) << "invalid argument configuration. Argument names must not be empty"; if ((name.size() == 2 && name[0] != '-') || name.size() == 3) - fs_fatal(1) << "invalid argument configuration for '" << name << "'. Short names must begin with '-'"; + logFatal(1) << "invalid argument configuration for '" << name << "'. Short names must begin with '-'"; if (name.size() > 3 && (name[0] != '-' || name[1] != '-')) - fs_fatal(1) << "invalid argument configuration for '" << name << "'. Multi-character names must begin with '--'"; + logFatal(1) << "invalid argument configuration for '" << name << "'. Multi-character names must begin with '--'"; return name; } @@ -103,11 +100,11 @@ ArgumentParser::Argument::Argument(const ArgumentParser::String& _short_name, co // check for illogical option flags if ((min_args == 0) && (argtype != ArgType::Bool)) { - fs_fatal(1) << "invalid argument configuration for '" << canonicalName() << "'. " + logFatal(1) << "invalid argument configuration for '" << canonicalName() << "'. " << "Option flags that accept no input must be of type ArgType::Bool"; } if ((min_args == 0) && required) { - fs_fatal(1) << "invalid argument configuration for '" << canonicalName() << "'. " + logFatal(1) << "invalid argument configuration for '" << canonicalName() << "'. " << "Required flags must accept at least one input"; } } @@ -117,11 +114,11 @@ ArgumentParser::Argument::Argument(const ArgumentParser::String& _short_name, co void ArgumentParser::Argument::validate() { if (positional && consumed < min_args) - fs_fatal(2) << "not enough positional arguments supplied"; + logFatal(2) << "not enough positional arguments supplied"; if (fixed && fixed_nargs != consumed) - fs_fatal(2) << "not enough inputs passed to option '" << canonicalName() << "' (expected " << fixed_nargs << ")"; + logFatal(2) << "not enough inputs passed to option '" << canonicalName() << "' (expected " << fixed_nargs << ")"; if (!fixed && variable_nargs == '+' && consumed < 1) - fs_fatal(2) << "option '" << canonicalName() << "' requires at least one input"; + logFatal(2) << "option '" << canonicalName() << "' requires at least one input"; } @@ -210,7 +207,7 @@ void ArgumentParser::parse(const ArgumentParser::StringVector& argv) for (StringVector::const_iterator in = argv.begin() + 1; in < argv.end(); ++in) { String element = *in; if (element[0] == '-') { - if (index.count(element) == 0) fs_fatal(2) << "unknown flag '" << element << "'"; + if (index.count(element) == 0) logFatal(2) << "unknown flag '" << element << "'"; // count the number of input args following this option unsigned int args_following = 0; for (StringVector::const_iterator fin = in + 1 ; fin < argv.end() ; fin++) { @@ -218,7 +215,7 @@ void ArgumentParser::parse(const ArgumentParser::StringVector& argv) if (future[0] != '-') args_following++; } if (arguments[index[element]].min_args > args_following) { - fs_fatal(2) << "not enough inputs supplied to '" << element << "'"; + logFatal(2) << "not enough inputs supplied to '" << element << "'"; } } } @@ -240,7 +237,7 @@ void ArgumentParser::parse(const ArgumentParser::StringVector& argv) // if so, let's get the next set of positional arguments posidx++; if (posidx >= positionals.size()) { - fs_fatal(2) << "unexpected argument '" << element << "'"; + logFatal(2) << "unexpected argument '" << element << "'"; } else { active = positionals[posidx]; } @@ -286,7 +283,7 @@ void ArgumentParser::parse(const ArgumentParser::StringVector& argv) } } } catch (...) { - fs_fatal(2) << "input '" << element << "' cannot be converted to expected type (" << active.typeName() << ")"; + logFatal(2) << "input '" << element << "' cannot be converted to expected type (" << active.typeName() << ")"; } variables[N].exists = true; active.consumed++; @@ -316,7 +313,7 @@ void ArgumentParser::parse(const ArgumentParser::StringVector& argv) for (ArgumentVector::const_iterator it = arguments.begin(); it != arguments.end(); ++it) { Argument arg = *it; if (arg.required && !exists(arg.canonicalName())) { - fs_fatal(2) << "missing required input '" << arg.canonicalName() << "'"; + logFatal(2) << "missing required input '" << arg.canonicalName() << "'"; } } } @@ -340,7 +337,7 @@ bool ArgumentParser::exists(const String& name) { // first check if name is a valid argument key String unstripped = unstrip(name); - if (index.count(unstripped) == 0) fs_fatal(1) << "'" << unstripped << "' is not a known argument"; + if (index.count(unstripped) == 0) logFatal(1) << "'" << unstripped << "' is not a known argument"; return variables[index[unstripped]].exists; } @@ -358,7 +355,7 @@ void ArgumentParser::insertArgument(const ArgumentParser::Argument& arg) case ArgType::Float : variables.push_back(float(0)); break; case ArgType::Bool : variables.push_back(false); break; case ArgType::String : variables.push_back(String()); break; - default : fs_fatal(1) << "unknown argument type for '" << arg.canonicalName() << "'"; + default : logFatal(1) << "unknown argument type for '" << arg.canonicalName() << "'"; } } else { switch(arg.argtype) { @@ -366,7 +363,7 @@ void ArgumentParser::insertArgument(const ArgumentParser::Argument& arg) case ArgType::Float : variables.push_back(FloatVector()); break; case ArgType::Bool : variables.push_back(std::vector()); break; case ArgType::String : variables.push_back(StringVector()); break; - default : fs_fatal(1) << "unknown argument type for '" << arg.canonicalName() << "'"; + default : logFatal(1) << "unknown argument type for '" << arg.canonicalName() << "'"; } } @@ -374,7 +371,7 @@ void ArgumentParser::insertArgument(const ArgumentParser::Argument& arg) for (IndexMap::iterator it = index.begin(); it != index.end(); it++) { String stripped = strip(it->first); if (stripped == strip(arg.short_name) || stripped == strip(arg.name)) { - fs_fatal(1) << "invalid argument configuration. '" << arg.canonicalName() << "' is used twice"; + logFatal(1) << "invalid argument configuration. '" << arg.canonicalName() << "' is used twice"; } } @@ -382,7 +379,7 @@ void ArgumentParser::insertArgument(const ArgumentParser::Argument& arg) if (!arg.fixed) { if (arg.positional) { if (variable_positional) { - fs_fatal(1) << "invalid argument configuration for '" << arg.canonicalName() << "'. " + logFatal(1) << "invalid argument configuration for '" << arg.canonicalName() << "'. " << "Two positional arguments cannot both have a variable amount of inputs, " << "as this could lead to an undefined boundary between the two"; } @@ -391,7 +388,7 @@ void ArgumentParser::insertArgument(const ArgumentParser::Argument& arg) variable_flag = true; } if (variable_positional && variable_flag) { - fs_fatal(1) << "invalid argument configuration for '" << arg.canonicalName() << "'. " + logFatal(1) << "invalid argument configuration for '" << arg.canonicalName() << "'. " << "A positional argument and flagged argument cannot both have a variable " << "amount of inputs, as this could lead to an undefined boundary between the two"; } diff --git a/utils/art1.c b/utils/art1.c deleted file mode 100644 index 703d6e354b5..00000000000 --- a/utils/art1.c +++ /dev/null @@ -1,457 +0,0 @@ -/** - * @file art1.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:42 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/* - @(#)art1.c 1.1 - 3/28/94 -*/ -/*---------------------------------------------------------------------- - - File Name: art1.c - - Description: - - $Header: /space/repo/1/dev/dev/utils/art1.c,v 1.3 2011/03/02 00:04:42 nicks -Exp $ - $Log: art1.c,v $ - Revision 1.3 2011/03/02 00:04:42 nicks - ENH: new license header mods - - Revision 1.2 2006/12/29 01:49:30 nicks - added license header; ran astyle to set to kr and ansi code styling - - Revision 1.1 1997/03/18 18:26:29 fischl - Initial revision - -----------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - INCLUDE FILES ------------------------------------------------------------------*/ -#include -#include -#include -#include - -#include "art1.h" -#include "diag.h" -#include "error.h" -#include "machine.h" -#include "proto.h" - -#define InsCalloc calloc -#define InsHalloc(a, b) calloc((int)(a), b) -#define InsFree free -#define InsHfree free - -/*----------------------------------------------------------------- - MACROS AND CONSTANTS ------------------------------------------------------------------*/ - -#define BETA .001 -#define DELTA_RHO .0001 /* amount above Tj to set row after mismatch */ -#define ALPHA(art, j) (1.0 / (art->beta + (double)art->ninputs)) - (.00001 * ((double)j + 1.0)) -#ifndef MIN -#define MIN(a, b) (a < b ? a : b) -#endif - -#ifndef MAX -#define MAX(a, b) (a > b ? a : b) -#endif - -/*---------------------------------------------------------------------- - STRUCTURES -----------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - PROTOTYPES ------------------------------------------------------------------*/ - -void artInitWeights(ART1 *art1); -int artFeedBack(ART1 *art1, int class); -int artFeedForward(ART1 *art1); -double artChoice(ART1 *art, int j); -double norm(double huge *a, int len); -void intersect(double huge *a, double huge *b, double huge *c, int len); -void artFastLearn(ART1 *art1, int j); - -/*----------------------------------------------------------------- - MACROS ------------------------------------------------------------------*/ - -#define Mzj(art1, i, j) (art1->zj + (((long)j) * (long)art1->ninputs) + (long)i) - -/*----------------------------------------------------------------- - STATIC DATA ------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - GLOBAL DATA ------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - FUNCTIONS ------------------------------------------------------------------*/ - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -ART1 *Art1Alloc(int ninputs, int max_f2, double rho) -{ - ART1 *art1; - - art1 = (ART1 *)InsCalloc(1, sizeof(ART1)); - - art1->ninputs = ninputs; - art1->noutputs = 0; /* no nodes committed yet */ - art1->max_f2 = max_f2; - art1->beta = BETA; - art1->rho = rho; - art1->scratch = (double *)InsCalloc(ninputs, sizeof(double)); - art1->f0 = (double *)InsCalloc(ninputs, sizeof(double)); - art1->f1 = (double *)InsCalloc(ninputs, sizeof(double)); - art1->f2 = (double *)InsCalloc(max_f2, sizeof(double)); - art1->flags = (int *)InsCalloc(max_f2, sizeof(int)); - art1->zj = (double huge *)InsHalloc((long)ninputs * (long)max_f2, sizeof(double)); - - artInitWeights(art1); - - return (art1); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -ART1 *Art1Read(char *fname) -{ - ART1 *art1; - int ninputs, noutputs, max_f2, i, j; - double zj, rho, beta; - FILE *fp; - - fp = fopen(fname, "r"); - if (!fp) return NULL; - - if (fscanf(fp, "%d %d %d %lf %lf\n", &ninputs, &noutputs, &max_f2, &beta, &rho) != 5) { - fprintf(stderr, "Warning: fscanf did not read expected number of values\n"); - } - - art1 = Art1Alloc(ninputs, max_f2, rho); - art1->noutputs = art1->noutputs; - for (j = 0; j < art1->noutputs; j++) art1->flags[j] |= ART1_COMMITTED; - - for (i = 0; i < art1->ninputs; i++) { - for (j = 0; j < art1->noutputs; j++) { - if (fscanf(fp, "%lf\n", &zj) != 1) { - fprintf(stderr, "Warning: fscanf did not read expected number of values\n"); - } - *Mzj(art1, i, j) = zj; - } - } - - fclose(fp); - return (art1); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int Art1Write(ART1 *art1, char *fname) -{ - FILE *fp; - int i, j; - double zj; - - fp = fopen(fname, "w"); - if (!fp) return (-1); - - fprintf(fp, "%d %d %d %f %f\n", art1->ninputs, art1->noutputs, art1->max_f2, art1->beta, art1->rho); - - for (i = 0; i < art1->ninputs; i++) { - for (j = 0; j < art1->noutputs; j++) { - zj = *Mzj(art1, i, j); - fprintf(fp, "%f\n", zj); - } - } - - fclose(fp); - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int Art1Free(ART1 **art1) -{ - InsFree((*art1)->scratch); - InsFree((*art1)->f0); - InsFree((*art1)->f1); - InsFree((*art1)->f2); - InsFree((*art1)->flags); - InsHfree((*art1)->zj); - InsFree(*art1); - *art1 = NULL; - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int Art1Process(ART1 *art1, double *I) -{ - // int nclass; - int i, class; - - if (Gdiag & DIAG_WRITE) printf("Art1Process()\n"); - - for (i = 0; i < art1->ninputs; i++) art1->f0[i] = art1->f1[i] = I[i]; - - for (i = 0; i < art1->noutputs; i++) art1->flags[i] &= ~ART1_RESET; - - // nclass = 0; - do { - art1->class = class = artFeedForward(art1); - if (class < 0) break; /* no classes left */ - } while (!artFeedBack(art1, class)); - - if (class < 0) /* no prior match was enough to establish resonance */ - { - if (art1->noutputs >= art1->max_f2) /* no more nodes left */ - { - /* find the closest feed-forward match and force it's use */ - for (i = 0; i < art1->noutputs; i++) art1->flags[i] &= ~ART1_RESET; - class = artFeedForward(art1); - } - else /* allocate new f2 node for this category */ - { - class = art1->class = art1->noutputs++; - art1->flags[class] = ART1_COMMITTED; - } - } - - artFastLearn(art1, art1->class); - - if (Gdiag & DIAG_WRITE) printf("Art1Process() --> %d\n", class); - return (class); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -void artInitWeights(ART1 *art1) -{ - int i, j; - double *zj; - - for (i = 0; i < art1->ninputs; i++) { - for (j = 0; j < art1->max_f2; j++) { - zj = Mzj(art1, i, j); - *zj = 1.0; - } - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - feed the active f2 nodes activation back through the top down weights - to f1. Return 1 if resonance is established, 0 if there is a mismatch. - - Resonance is established if: - - rho <= |I ^ zj| - -------- - |I| - - Returns: -----------------------------------------------------------------------*/ -int artFeedBack(ART1 *art1, int class) -{ - int j, ninputs; - double match, norm_I_int_zj, norm_I; - - j = class; - ninputs = art1->ninputs; - intersect(art1->f0, Mzj(art1, 0, j), art1->scratch, ninputs); - norm_I_int_zj = norm(art1->scratch, ninputs); - norm_I = norm(art1->f0, ninputs); - if (!norm_I) - match = 1; - else - match = norm_I_int_zj / norm_I; - - if (Gdiag & DIAG_WRITE) - printf( - "artFeedBack(%d) --> match %2.3f, n(I) %2.3f, " - "n(I^Zj) %2.3f, rho %2.3f %s\n", - class, - match, - norm_I, - norm_I_int_zj, - art1->rho, - match >= art1->rho ? "RESONANCE" : "MISMATCH"); - - if (match < art1->rho) /* mismatch --> do reset */ - { - art1->flags[j] |= ART1_RESET; - return (0); - } - else - return (1); /* resonance */ -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int artFeedForward(ART1 *art1) -{ - int max_j, j; - // double f2; - double max_out; - - max_j = -1; - max_out = -1.0; - - for (j = 0; j < art1->noutputs; j++) { - if (art1->flags[j] & ART1_RESET) continue; /* this node was previous winner */ - - // f2 = - art1->f2[j] = artChoice(art1, j); - if (art1->f2[j] > max_out) { - max_j = j; - max_out = art1->f2[j]; - } - } - - if (Gdiag & DIAG_WRITE) printf("artFeedForward() --> %d (%2.3f)\n", max_j, max_out); - return (max_j); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - calculate the choice function for an f2 node: - - Tj = |I ^ zj| = Zj . I - ------------ - BETA + |zj| - - Returns: -----------------------------------------------------------------------*/ -double artChoice(ART1 *art1, int j) -{ - double Tj, *zj, norm_zj, norm_I_int_zj; - - zj = Mzj(art1, 0, j); /* address of jth nodes weights */ - - /* calculate I ^ zj */ - if (art1->flags[j] & ART1_COMMITTED) { - intersect(art1->f0, zj, art1->scratch, art1->ninputs); - norm_I_int_zj = norm(art1->scratch, art1->ninputs); - norm_zj = norm(zj, art1->ninputs); - - Tj = (double)norm_I_int_zj / (art1->beta + (double)norm_zj); - } - else /* Tj = |I| * ALPHA(j) */ - { - Tj = (double)norm(art1->f0, art1->ninputs); - Tj *= ALPHA(art1, j); - } - return (Tj); -} -/* - take the intersection of vectors a and b, and return it - in vector c. All vectors have length 'len'. -*/ -void intersect(double huge *a, double huge *b, double huge *c, int len) -{ - register int i; - - for (i = 0; i < len; i++, a++, b++, c++) *c = MIN(*a, *b); -} - -/* - take the norm (city block) of vector a of length 'len'. -*/ -double norm(double huge *a, int len) -{ - register int i; - double norm_val; - - for (norm_val = 0.0, i = 0; i < len; i++, a++) norm_val += fabs(*a); - - return (norm_val); -} - -/* - f1->f2 learning: - Zj = (I ^ zj) - ------------ - |I ^ zj| + B - - f2->f1 learning: - zj = I ^ zj -*/ -void artFastLearn(ART1 *art1, int j) -{ - // double norm_I_int_zj; - int i; - - if (j < 0) return; /* not a valid class */ - - intersect(art1->f0, Mzj(art1, 0, j), art1->scratch, art1->ninputs); - // norm_I_int_zj = - norm(art1->scratch, art1->ninputs); - for (i = 0; i < art1->ninputs; i++) { - *Mzj(art1, i, j) = art1->scratch[i]; - } -} -int Art1SetParms(ART1 *art1, double rho) -{ - art1->rho = rho; - return (NO_ERROR); -} diff --git a/utils/artmap.c b/utils/artmap.c deleted file mode 100644 index d64dbffc53a..00000000000 --- a/utils/artmap.c +++ /dev/null @@ -1,578 +0,0 @@ -/** - * @file artmap.c - * @brief Adaptive Resonance Theory map - * - * some kind of vestige of the CNS department - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:42 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/*----------------------------------------------------------------- - INCLUDE FILES ------------------------------------------------------------------*/ -#include -#include -#include -#include - -#include "artmap.h" -#include "diag.h" -#include "error.h" -#include "machine.h" -#include "proto.h" - -/*----------------------------------------------------------------- - MACROS AND CONSTANTS ------------------------------------------------------------------*/ - -#define InsCalloc calloc -#define InsHalloc(a, b) calloc((int)(a), b) -#define InsFree free -#define InsHfree free - -#define BETA .001 -#define DELTA_RHO .0001 /* amount above Tj to set row after mismatch */ -#define ALPHA(art, j) (1.0 / (art->beta + (double)art->ninputs)) - (.00001 * ((double)j + 1.0)) -#ifndef MIN -#define MIN(a, b) (a < b ? a : b) -#endif - -#ifndef MAX -#define MAX(a, b) (a > b ? a : b) -#endif - -/*---------------------------------------------------------------------- - STRUCTURES -----------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - PROTOTYPES ------------------------------------------------------------------*/ - -static void artInitWeights(ARTMAP *artmap); -static int artFeedBack(ARTMAP *artmap, int class); -static int artFeedForward(ARTMAP *artmap); -static double artChoice(ARTMAP *art, int j); -static double norm(double huge *a, int len); -static void intersect(double huge *a, double huge *b, double huge *c, int len); -static void artFastLearn(ARTMAP *artmap, int j); -int artProcess(ARTMAP *artmap, double *I); -int mapFeedForward(ARTMAP *artmap, int class); -void mapLearn(ARTMAP *artmap, int ja, int jb); - -/*----------------------------------------------------------------- - MACROS ------------------------------------------------------------------*/ - -#define Mzj(artmap, i, j) (artmap->zj + (((long)j) * (long)artmap->ninputs) + (long)i) -#define Mwj(artmap, j, k) (artmap->w + (((long)j) * (long)artmap->noutputs) + (long)k) - -/*----------------------------------------------------------------- - STATIC DATA ------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - GLOBAL DATA ------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - FUNCTIONS ------------------------------------------------------------------*/ - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -ARTMAP *ArtmapAlloc(int ninputs, int noutputs, double rho_bar, int max_f2) -{ - ARTMAP *artmap; - - artmap = (ARTMAP *)InsCalloc(1, sizeof(ARTMAP)); - - artmap->ninputs = ninputs; - artmap->noutputs = noutputs; - artmap->max_f2 = max_f2; - artmap->beta = BETA; - artmap->rho = artmap->rho_bar = rho_bar; - artmap->scratch = (double *)InsCalloc(ninputs, sizeof(double)); - artmap->f0 = (double *)InsCalloc(ninputs, sizeof(double)); - artmap->f1 = (double *)InsCalloc(ninputs, sizeof(double)); - artmap->f2 = (double *)InsCalloc(max_f2, sizeof(double)); - artmap->flags = (int *)InsCalloc(max_f2, sizeof(int)); - artmap->zj = (double huge *)InsHalloc((long)ninputs * (long)max_f2, sizeof(double)); - artmap->w = (int huge *)InsHalloc((long)noutputs * (long)max_f2, sizeof(int)); - - artInitWeights(artmap); - - return (artmap); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -ARTMAP *ArtmapRead(char *fname) -{ - ARTMAP *artmap; - int ninputs, noutputs, f2nodes, i, j, k, wj; - double zj; - FILE *fp; - - double beta, rho_bar; - - fp = fopen(fname, "r"); - if (!fp) { - return (NULL); - } - - if (fscanf(fp, "%d %d %d %lf %lf\n", &ninputs, &noutputs, &f2nodes, &beta, &rho_bar) != 5) { - fprintf(stderr, "Warning: fscanf could not read expectenumber of d values"); - } - - artmap = ArtmapAlloc(ninputs, noutputs, rho_bar, f2nodes); - artmap->ncommitted = artmap->f2nodes = f2nodes; - for (j = 0; j < artmap->f2nodes; j++) { - artmap->flags[j] |= ARTMAP_COMMITTED; - for (k = 0; k < artmap->noutputs; k++) { - if (fscanf(fp, "%d\n", &wj) != 1) { - fprintf(stderr, "Warning: fscanf could not read expectenumber of d values"); - } - *Mwj(artmap, j, k) = wj; - } - } - - for (i = 0; i < artmap->ninputs; i++) { - for (j = 0; j < artmap->f2nodes; j++) { - if (fscanf(fp, "%lf\n", &zj) != 1) { - fprintf(stderr, "Warning: fscanf could not read expectenumber of d values"); - } - *Mzj(artmap, i, j) = zj; - } - } - - fclose(fp); - return (artmap); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int ArtmapWrite(ARTMAP *artmap, char *fname) -{ - FILE *fp; - int i, j, k, wj; - double zj; - - fp = fopen(fname, "w"); - if (!fp) return (-1); - - fprintf(fp, "%d %d %d %f %f\n", artmap->ninputs, artmap->noutputs, artmap->f2nodes, artmap->beta, artmap->rho_bar); - - for (j = 0; j < artmap->f2nodes; j++) { - for (k = 0; k < artmap->noutputs; k++) { - wj = *Mwj(artmap, j, k); - fprintf(fp, "%d\n", wj); - } - } - - for (i = 0; i < artmap->ninputs; i++) { - for (j = 0; j < artmap->f2nodes; j++) { - zj = *Mzj(artmap, i, j); - fprintf(fp, "%f\n", zj); - } - } - - fclose(fp); - return (0); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int ArtmapFree(ARTMAP **artmap) -{ - InsFree((*artmap)->scratch); - InsFree((*artmap)->f0); - InsFree((*artmap)->f1); - InsFree((*artmap)->f2); - InsFree((*artmap)->flags); - InsHfree((*artmap)->zj); - InsHfree((*artmap)->w); - InsFree(*artmap); - *artmap = NULL; - return (0); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int ArtmapProcess(ARTMAP *artmap, double *I) -{ - int class; - - if (Gdiag & DIAG_WRITE) printf("ArtmapProcess()\n"); - class = artProcess(artmap, I); - - if (class == 4) { - int k; - - if (Gdiag & DIAG_WRITE) - for (k = 0; k < artmap->noutputs; k++) printf("Mwj(4, %d) = %d\n", k, *Mwj(artmap, 4, k)); - } - return (mapFeedForward(artmap, class)); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int artProcess(ARTMAP *artmap, double *I) -{ - int nclass, i, class = 0; - - for (i = 0; i < artmap->ninputs; i++) artmap->f0[i] = artmap->f1[i] = I[i]; - - for (i = 0; i < artmap->f2nodes; i++) artmap->flags[i] &= ~ARTMAP_RESET; - - nclass = 0; - do { - /* - in test mode, if the first neither of the 1st two classes - survive feedback, give it up. -*/ - if (!artmap->learn && ++nclass > 2) { - artmap->match = 0.0; - break; - } - artmap->class = class = artFeedForward(artmap); - if (class < 0) break; /* no classes left */ - } while (!artFeedBack(artmap, class)); - - if (Gdiag & DIAG_WRITE) printf("artProcess() --> %d\n", class); - return (class); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int ArtmapLearn(ARTMAP *artmap, double *I, int class) -{ - int artClass; - - if (Gdiag & DIAG_WRITE) printf("ArtmapLearn(%d)\n", class); - - artmap->learn = 1; /* will allow committment of new nodes */ - - artmap->match = artmap->rho_bar - DELTA_RHO; - do { - artmap->rho = artmap->match + DELTA_RHO; /* match tracking */ - /* artmap->f2nodes = artmap->max_f2 ;*/ - artClass = ArtmapProcess(artmap, I); - /* artmap->f2nodes = artmap->ncommitted ;*/ - if (artClass < 0) /* commit new node */ - { - if (artmap->f2nodes < artmap->max_f2) { - if (Gdiag & DIAG_WRITE) printf("committing new f2 node %d to class %d\n", artmap->f2nodes, class); - artmap->class = artmap->f2nodes++; - artmap->flags[artmap->class] |= ARTMAP_COMMITTED; - artmap->ncommitted++; - break; - } - else - return (-1); /* out of memory */ - } - if (artClass != class) { - if (Gdiag & DIAG_WRITE) printf("artClass %d != class %d --> match tracking\n", artClass, class); - } - } while (artClass != class); - - artFastLearn(artmap, artmap->class); - mapLearn(artmap, artmap->class, class); - - artmap->rho = artmap->rho_bar; /* relax to baseline vigilance */ - return (artClass); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void artInitWeights(ARTMAP *artmap) -{ - int i, j, k; - double *zj; - - for (i = 0; i < artmap->ninputs; i++) { - for (j = 0; j < artmap->max_f2; j++) { - zj = Mzj(artmap, i, j); - *zj = 1.0; - } - } - for (j = 0; j < artmap->max_f2; j++) { - for (k = 0; k < artmap->noutputs; k++) { - *Mwj(artmap, j, k) = 1; - } - } -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - feed the active f2 nodes activation back through the top down weights - to f1. Return 1 if resonance is established, 0 if there is a mismatch. - - Resonance is established if: - - rho <= |I ^ zj| - -------- - |I| - - Returns: -----------------------------------------------------------------------*/ -static int artFeedBack(ARTMAP *artmap, int class) -{ - int j, ninputs; - double match, norm_I_int_zj, norm_I; - - j = class; - ninputs = artmap->ninputs; - intersect(artmap->f0, Mzj(artmap, 0, j), artmap->scratch, ninputs); - norm_I_int_zj = norm(artmap->scratch, ninputs); - norm_I = norm(artmap->f0, ninputs); - if (!norm_I) - match = 1; - else - match = norm_I_int_zj / norm_I; - artmap->match = match; /* for use in match tracking */ - - if (Gdiag & DIAG_WRITE) - printf( - "artFeedBack(%d) --> match %2.3f, n(I) %2.3f, n(I^Zj) %2.3f, " - "rho %2.3f %s\n", - class, - match, - norm_I, - norm_I_int_zj, - artmap->rho, - match >= artmap->rho ? "RESONANCE" : "MISMATCH"); - - if (match < artmap->rho) /* mismatch --> do reset */ - { - artmap->flags[j] |= ARTMAP_RESET; - return (0); - } - else - return (1); /* resonance */ -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static int artFeedForward(ARTMAP *artmap) -{ - int max_j, j; - // double f2, - double max_out; - - max_j = -1; - max_out = -1.0; - - for (j = 0; j < artmap->f2nodes; j++) { - if (artmap->flags[j] & ARTMAP_RESET) continue; /* this node was previous winner */ - - // f2 = - artmap->f2[j] = artChoice(artmap, j); - if (artmap->f2[j] > max_out) { - max_j = j; - max_out = artmap->f2[j]; - } - } - - if (Gdiag & DIAG_WRITE) printf("artFeedForward() --> %d (%2.3f)\n", max_j, max_out); - return (max_j); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - calculate the choice function for an f2 node: - - Tj = |I ^ zj| = Zj . I - ------------ - BETA + |zj| - - Returns: -----------------------------------------------------------------------*/ -static double artChoice(ARTMAP *artmap, int j) -{ - double Tj, *zj, norm_zj, norm_I_int_zj; - - zj = Mzj(artmap, 0, j); /* address of jth nodes weights */ - - /* calculate I ^ zj */ - if (artmap->flags[j] & ARTMAP_COMMITTED) { - intersect(artmap->f0, zj, artmap->scratch, artmap->ninputs); - norm_I_int_zj = norm(artmap->scratch, artmap->ninputs); - norm_zj = norm(zj, artmap->ninputs); - - Tj = (double)norm_I_int_zj / (artmap->beta + (double)norm_zj); - } - else /* Tj = |I| * ALPHA(j) */ - { - Tj = (double)norm(artmap->f0, artmap->ninputs); - Tj *= ALPHA(artmap, j); - } - return (Tj); -} - -/* - take the intersection of vectors a and b, and return it - in vector c. All vectors have length 'len'. -*/ -static void intersect(double huge *a, double huge *b, double huge *c, int len) -{ - register int i; - - for (i = 0; i < len; i++, a++, b++, c++) *c = MIN(*a, *b); -} - -/* - take the norm (city block) of vector a of length 'len'. -*/ -static double norm(double huge *a, int len) -{ - register int i; - double norm_val; - - for (norm_val = 0.0, i = 0; i < len; i++, a++) norm_val += fabs(*a); - - return (norm_val); -} - -/* - f1->f2 learning: - Zj = (I ^ zj) - ------------ - |I ^ zj| + B - - f2->f1 learning: - zj = I ^ zj -*/ -static void artFastLearn(ARTMAP *artmap, int j) -{ - // double norm_I_int_zj; - int i; - - if (j < 0) return; /* not a valid class */ - - intersect(artmap->f0, Mzj(artmap, 0, j), artmap->scratch, artmap->ninputs); - // norm_I_int_zj = - norm(artmap->scratch, artmap->ninputs); - for (i = 0; i < artmap->ninputs; i++) { - *Mzj(artmap, i, j) = artmap->scratch[i]; - } -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - calculate map field activation x = Yb ^ wj - - where Yb is b field activation, and wj are adaptive weights - between F2a and the map field. - - Returns: -----------------------------------------------------------------------*/ -int mapFeedForward(ARTMAP *artmap, int class) -{ - int k, apredict; - - if (class < 0) return (-1); /* ARTa did not make a choice */ - - apredict = -1; - for (k = 0; k < artmap->noutputs; k++) { - if ((apredict < 0) && *Mwj(artmap, class, k)) /* 1st node */ - { - apredict = k; - break; - } - } - if (Gdiag & DIAG_WRITE) printf("mapFeedForward(%d) --> %d\n", class, apredict); - return (apredict); -} - -/*---------------------------------------------------------------------- - Parameters: - - Description: - learn weights at the map field. The weights obey - - Wjk = 1 for j and k active. All other weights are 0. - - Returns: -----------------------------------------------------------------------*/ -void mapLearn(ARTMAP *artmap, int aclass, int mapclass) -{ - register int k, *wj; - - if (Gdiag & DIAG_WRITE) printf("mapLearn(%d-->%d)\n", aclass, mapclass); - - for (k = 0; k < artmap->noutputs; k++) { - wj = Mwj(artmap, aclass, k); - if (k != mapclass) { - if (Gdiag & DIAG_WRITE) printf("deleting map connection %d --> %d\n", aclass, k); - *wj = 0; - } - } -} diff --git a/utils/aseg_edit_svm.c b/utils/aseg_edit_svm.c deleted file mode 100644 index c4e53ffdfe9..00000000000 --- a/utils/aseg_edit_svm.c +++ /dev/null @@ -1,143 +0,0 @@ -/** - * @file aseg_edit_svm.c - * @brief utilities for using SVMs to reclassify aseg voxels - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: zkaufman $ - * $Date: 2015/03/12 20:22:55 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -extern const char *Progname; - -/*----------------------------------------------------- - INCLUDE FILES - -------------------------------------------------------*/ -#include -#include -#include - -#include "diag.h" -#include "error.h" -#include "mri.h" -#include "utils.h" -#include "voxlist.h" - -#include "aseg_edit_svm.h" - -/*#define NINPUTS(wsize, nscales) \ - (4 + \ - (wsize * wsize * wsize) * nscales * \ - (1 + 1)) // 3+1 = 3 grad components plus image intensity*/ -float **build_svm_training_data(VOXEL_LIST *vl_total, - int target_label, - float *svm_classes, - MRI **mri_smooth, - MRI **mri_grad, - MRI **mri_laplacian, - MRI *mri_dtrans, - int wsize, - int nscales) -{ - float **svm_inputs; - int i, ninputs; - MRI *mri_dtrans_grad; - - svm_inputs = (float **)calloc(vl_total->nvox, sizeof(float *)); - if (svm_inputs == NULL) - ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %d SVM input vector", Progname, vl_total->nvox); - - ninputs = NINPUTS(wsize, nscales); - mri_dtrans_grad = MRIsobel(mri_dtrans, NULL, NULL); - for (i = 0; i < vl_total->nvox; i++) { - if (svm_classes) svm_classes[i] = ((int)vl_total->vdst[i] == target_label) ? 1 : -1; - - svm_inputs[i] = build_svm_inputs_at_voxel(vl_total, - i, - target_label, - mri_smooth, - mri_grad, - mri_laplacian, - mri_dtrans, - mri_dtrans_grad, - wsize, - nscales, - NULL); - if (svm_inputs[i] == NULL) - ErrorExit( - ERROR_NOMEMORY, "%s: could not allocate %dth SVM input vector size %d", Progname, vl_total->nvox, ninputs); - } - MRIfree(&mri_dtrans_grad); - return (svm_inputs); -} -float *build_svm_inputs_at_voxel(VOXEL_LIST *vl, - int i, - int target_label, - MRI **mri_smooth, - MRI **mri_grad, - MRI **mri_laplacian, - MRI *mri_dtrans, - MRI *mri_dtrans_grad, - int wsize, - int nscales, - float *svm_inputs) -{ - int s, xk, yk, zk, xi, yi, zi, x, y, z, ninputs, whalf, input; - - whalf = (wsize - 1) / 2; - ninputs = NINPUTS(wsize, nscales); - if (svm_inputs == NULL) { - svm_inputs = (float *)calloc(ninputs, sizeof(float)); - if (svm_inputs == NULL) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %d SVM input vector", Progname, ninputs); - } - - x = vl->xi[i]; - y = vl->yi[i]; - z = vl->zi[i]; - - input = 0; - svm_inputs[input++] = MRIgetVoxVal(mri_dtrans, x, y, z, 0); - if (!isfinite(svm_inputs[input - 1])) DiagBreak(); - svm_inputs[input++] = MRIgetVoxVal(mri_dtrans_grad, x, y, z, 0); - if (!isfinite(svm_inputs[input - 1])) DiagBreak(); - svm_inputs[input++] = MRIgetVoxVal(mri_dtrans_grad, x, y, z, 1); - if (!isfinite(svm_inputs[input - 1])) DiagBreak(); - svm_inputs[input++] = MRIgetVoxVal(mri_dtrans_grad, x, y, z, 2); - if (!isfinite(svm_inputs[input - 1])) DiagBreak(); - for (xk = -whalf; xk <= whalf; xk++) - for (yk = -whalf; yk <= whalf; yk++) - for (zk = -whalf; zk <= whalf; zk++) { - for (s = 0; s < nscales; s++) { - xi = mri_smooth[s]->xi[x + xk]; - yi = mri_smooth[s]->yi[y + yk]; - zi = mri_smooth[s]->zi[z + zk]; - svm_inputs[input++] = MRIgetVoxVal(mri_smooth[s], xi, yi, zi, 0); - if (!isfinite(svm_inputs[input - 1])) DiagBreak(); -#if 0 - svm_inputs[input++] = MRIgetVoxVal(mri_grad[s], xi, yi, zi, 0) ; - svm_inputs[input++] = MRIgetVoxVal(mri_grad[s], xi, yi, zi, 1) ; - svm_inputs[input++] = MRIgetVoxVal(mri_grad[s], xi, yi, zi, 2) ; -#endif - svm_inputs[input++] = MRIgetVoxVal(mri_laplacian[s], xi, yi, zi, 0); - if (!isfinite(svm_inputs[input - 1])) DiagBreak(); - } - } - - for (input = 0; input < ninputs; input++) - if (!isfinite(svm_inputs[input])) DiagBreak(); - return (svm_inputs); -} diff --git a/utils/autoencoder.c b/utils/autoencoder.cpp similarity index 100% rename from utils/autoencoder.c rename to utils/autoencoder.cpp diff --git a/utils/backprop.c b/utils/backprop.c deleted file mode 100644 index 69f367c965a..00000000000 --- a/utils/backprop.c +++ /dev/null @@ -1,1379 +0,0 @@ -/** - * @file backprop.c - * @brief back-propagation neural net - * - * backprop files can store multiple networks of varying size. In order to - * accomodate this, I mimic the tiff file structure with a header indicating - * the # of networks, and a pointer to the 1st one. Each one then starts with - * a pointer to the next network, or NULL for the last network in the file. - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:42 $ - * $Revision: 1.13 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/*----------------------------------------------------------------- - INCLUDE FILES ------------------------------------------------------------------*/ -#include "backprop.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include "diag.h" -#include "error.h" -#include "machine.h" -#include "macros.h" -#include "proto.h" -#include "timer.h" -#include "utils.h" - -/*----------------------------------------------------------------- - MACROS AND CONSTANTS ------------------------------------------------------------------*/ - -#define InsFree free -#define InsCalloc calloc -#define InsHalloc(a, b) calloc((int)a, (int)b) -#define InsHfree free -#define far -#define huge - -/* - can use either sigmoid or hyperbolic tangent activation function. -*/ -#define SIGMOID 0 - -#if SIGMOID - -#define f(net) (1.0f / (1.0f + (float)exp((double)-net))) -#define fprime(o) (o * (1.0f - o)) - -#define SIG_MAX 0.75f -#define SIG_MIN 0.25f - -#else - -/* use hyperbolic tangent */ - -#define T_A 1.0f /*1.716f*/ /* push limits of sigmoid away from +-1 */ -#define T_B 0.666f /* stretch sigmoid out a bit */ - -#define f(net) (T_A * tanh(T_B * (net))) -#define fprime(o) (T_A * T_B * (1.0f - o * o)) - -#define SIG_MAX 0.5f -#define SIG_MIN -0.5f - -#endif - -#define SIG_RANGE (SIG_MAX - SIG_MIN) -#define MIN_TRATE 0.01f - -/*---------------------------------------------------------------------- - STRUCTURES -----------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - PROTOTYPES ------------------------------------------------------------------*/ - -static void bpInitLayerWeights(LAYER *layer); -static void bpInitLayer(LAYER *backprop, int ninputs, int nunits); -static void bpFreeLayer(LAYER *layer); -static void bpWriteLayer(FILE *fp, LAYER *layer); -static void bpReadLayer(FILE *fp, LAYER *layer); -static void bpLayerFeedForward(float *I, LAYER *layer, int nlin); -static void bpCalculateOutputDeltas(BACKPROP *backprop, float *targets); -static void bpCalculateHiddenDeltas(BACKPROP *backprop); -static void bpUpdateLayerWeights(LAYER *layer, float *I, float trate, float momentum); -static void bpUnnormalizeOutputs(BACKPROP *backprop); -static void bpNormalizeTargets(BACKPROP *backprop, float *targets); -static void bpUnnormalizeTargets(BACKPROP *backprop, float *targets); -static void bpCopyLayer(LAYER *lsrc, LAYER *ldst); - -/* file maintainance stuff */ -static long bpFileNewEnd(FILE *fp, BPFILE_HEADER *hd, int swapped); -static long bpFileSeekEndPtr(FILE *fp, BPFILE_HEADER *hd, int swapped); -static long bpFileSeekNet(FILE *fp, BPFILE_HEADER *hd, int netno, int swapped); -static int bpChangeNumberOfNets(FILE *fp, int nnets); - -/*----------------------------------------------------------------- - MACROS ------------------------------------------------------------------*/ - -/* from i to j */ -#define Wij(l, i, j) (*((l)->w + (((long)j) * (l)->ninputs) + (long)i)) -#define DWij(l, i, j) (*((l)->dw + (((long)j) * (l)->ninputs) + (long)i)) - -/*----------------------------------------------------------------- - STATIC DATA ------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - GLOBAL DATA ------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - FUNCTIONS ------------------------------------------------------------------*/ - -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int coef = -1; - -BACKPROP *BackpropAlloc( - int ninputs, int noutputs, int nhidden, float trate, float momentum, float *mean_out, float *std_out) -{ - BACKPROP *backprop; - - backprop = (BACKPROP *)InsCalloc(1, sizeof(BACKPROP)); - - backprop->ninputs = ninputs; - backprop->noutputs = noutputs; - backprop->nhidden = nhidden; - backprop->old_momentum = backprop->momentum = momentum; - backprop->mean_out = (float *)calloc(noutputs, sizeof(float)); - backprop->error_ratio = BP_ERROR_RATIO; - backprop->trate_up = BP_TRATE_INCREASE; - backprop->trate_down = BP_TRATE_DECREASE; - if (!backprop->mean_out) ErrorExit(ERROR_BAD_FILE, "BackpropAlloc: could not output range vector\n"); - backprop->std_out = (float *)calloc(noutputs, sizeof(float)); - if (!backprop->std_out) ErrorExit(ERROR_BAD_FILE, "BackpropAlloc: could not output range vector\n"); - memmove(backprop->mean_out, mean_out, noutputs * sizeof(float)); - memmove(backprop->std_out, std_out, noutputs * sizeof(float)); - backprop->errors = (float *)calloc(noutputs, sizeof(float)); - if (!backprop->errors) ErrorExit(ERROR_BAD_FILE, "BackpropAlloc: could not allocate error vector\n"); - - backprop->trate = trate; - bpInitLayer(&backprop->hidden, ninputs, nhidden); - bpInitLayer(&backprop->output, nhidden, noutputs); - - return (backprop); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int BackpropFileNumberOfNets(char *fname) -{ - BPFILE_HEADER hd; - FILE *fp; - - if (strcmp(fname, "-")) { - fp = fopen(fname, "r"); - if (!fp) return (-1); - fclose(fp); - fp = fopen(fname, "r+"); - } - else - fp = stdin; - - if (fread(&hd, sizeof(hd), 1, fp) != 1) - ErrorExit(ERROR_BAD_FILE, "BackpropNumberOfNets(%s): could not read header from file\n", fname); - - DiagPrintf(DIAG_WRITE, "BackpropNumberOfNets(%s): %d nets, 1st at %ld\n", fname, hd.nnets, hd.first); - if (hd.magic != BP_MAGIC) /* try changing byte order */ - { - hd.magic = swapLong32(hd.magic); - hd.nnets = swapLong32(hd.nnets); - hd.first = swapLong32(hd.first); - } - - if (hd.magic != BP_MAGIC) - ErrorReturn(ERROR_BAD_FILE, (ERROR_BAD_FILE, "BackpropFileNumberOfNets(%s): bad magic #\n", fname)); - - return ((int)hd.nnets); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -BACKPROP *BackpropRead(char *fname, int netno) -{ - BACKPROP *backprop; - int ninputs, noutputs, nhidden, ubytes, swapped = 0; - FILE *fp; - float momentum, trate, *min_out, *max_out; - BPFILE_HEADER hd; - - if (strcmp(fname, "-")) { - fp = fopen(fname, "r"); - if (!fp) return (NULL); - fclose(fp); - fp = fopen(fname, "r+"); - } - else - fp = stdin; - - if (fread(&hd, sizeof(hd), 1, fp) != 1) - ErrorReturn(NULL, (ERROR_BAD_FILE, "BackpropRead(%s): could not read header from file\n", fname)); - - if (hd.magic != BP_MAGIC) /* try changing byte order */ - { - hd.magic = swapLong32(hd.magic); - hd.nnets = swapLong32(hd.nnets); - hd.first = swapLong32(hd.first); - swapped = 1; - } - if (hd.magic != BP_MAGIC) ErrorReturn(NULL, (ERROR_BAD_FILE, "BackpropRead(%s): bad magic #\n", fname)); - - if (netno < 0) /* read last net in file */ - netno = (int)hd.nnets; - - DiagPrintf(DIAG_WRITE, "BackpropRead(%s, %d): %d nets, 1st at %ld\n", fname, netno, hd.nnets, hd.first); - if (netno >= hd.nnets) { - fclose(fp); - return (NULL); - } - - bpFileSeekNet(fp, &hd, netno, swapped); - DiagPrintf(DIAG_WRITE, "after bpFileSeekNet: fpos @ %ld\n", ftell(fp)); - - if (fscanf(fp, "%d %d %d %f %f %d\n", &ninputs, &noutputs, &nhidden, &trate, &momentum, &ubytes) != 6) { - if (fp != stdin) fclose(fp); - ErrorReturn(NULL, (ERROR_BAD_FILE, "could not scan parameters from bp file %s\n", fname)); - } - min_out = (float *)calloc(noutputs, sizeof(float)); - if (!min_out) { - if (fp != stdin) fclose(fp); - ErrorExit(ERROR_BAD_FILE, "BackpropRead(%s): could not allocate min_out\n", fname); - } - max_out = (float *)calloc(noutputs, sizeof(float)); - if (!max_out) { - if (fp != stdin) fclose(fp); - ErrorExit(ERROR_BAD_FILE, "BackpropRead(%s): could not allocate max_out\n", fname); - } - if (fread(min_out, sizeof(float), noutputs, fp) != (size_t)noutputs) { - if (fp != stdin) fclose(fp); - ErrorExit(ERROR_BAD_FILE, "BackpropRead(%s): could not read min_out\n", fname); - } - if (fread(max_out, sizeof(float), noutputs, fp) != (size_t)noutputs) { - if (fp != stdin) fclose(fp); - ErrorExit(ERROR_BAD_FILE, "BackpropRead(%s): could not read max_out\n", fname); - } - if (swapped) { - *min_out = swapFloat(*min_out); - *max_out = swapFloat(*max_out); - } - backprop = BackpropAlloc(ninputs, noutputs, nhidden, momentum, trate, min_out, max_out); - - free(min_out); - free(max_out); - if (ubytes > 0) { - backprop->user = (char *)calloc(ubytes, sizeof(char)); - backprop->user_bytes = ubytes; - if (fread(backprop->user, sizeof(char), ubytes, fp) != (size_t)ubytes) { - if (fp != stdin) fclose(fp); - ErrorReturn(NULL, (ERROR_BAD_FILE, "BackpropRead: could not read %d user bytes\n", ubytes)); - } - } - bpReadLayer(fp, &backprop->hidden); - bpReadLayer(fp, &backprop->output); - - if (fp != stdin) fclose(fp); - - return (backprop); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -BACKPROP *BackpropCopy(BACKPROP *bp_src, BACKPROP *bp_dst) -{ - if (bp_dst && ((bp_dst->ninputs != bp_src->ninputs) || (bp_dst->noutputs != bp_src->noutputs) || - (bp_dst->nhidden != bp_src->nhidden))) - BackpropFree(&bp_dst); - - if (!bp_dst) - bp_dst = BackpropAlloc(bp_src->ninputs, - bp_src->noutputs, - bp_src->nhidden, - bp_src->trate, - bp_src->momentum, - bp_src->mean_out, - bp_src->std_out); - - bp_dst->momentum = bp_src->momentum; /* momentum coefficient */ - bp_dst->trate = bp_src->trate; /* learning rate */ - bp_dst->trate_up = bp_src->trate_up; /* adaptive step size increase */ - bp_dst->trate_down = bp_src->trate_down; /* adaptive step size decrease */ - - /* ratio of new/old sse for step size modification */ - bp_dst->error_ratio = bp_src->error_ratio; - bp_dst->nepochs = bp_src->nepochs; /* # of epochs of training */ - bp_dst->ntrials = bp_src->ntrials; - bp_dst->old_momentum = bp_src->old_momentum; - bp_dst->sse = bp_src->sse; - - memmove(bp_dst->mean_out, bp_src->mean_out, bp_src->noutputs * sizeof(float)); - memmove(bp_dst->std_out, bp_src->std_out, bp_src->noutputs * sizeof(float)); - memmove(bp_dst->errors, bp_src->errors, bp_src->noutputs * sizeof(float)); - if ((bp_dst->user_bytes = bp_src->user_bytes) != 0) { - bp_dst->user = (void *)calloc(bp_src->user_bytes, sizeof(char)); - memmove(bp_dst->user, bp_src->user, bp_src->user_bytes); - } - - bpCopyLayer(&bp_src->hidden, &bp_dst->hidden); - bpCopyLayer(&bp_src->output, &bp_dst->output); - return (bp_dst); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpCopyLayer(LAYER *lsrc, LAYER *ldst) -{ - int nweights; - - nweights = lsrc->nunits * lsrc->ninputs; - memmove(ldst->w, lsrc->w, nweights * sizeof(*(lsrc->w))); - memmove(ldst->dw, lsrc->dw, nweights * sizeof(*(lsrc->dw))); - memmove(ldst->biases, lsrc->biases, lsrc->nunits * sizeof(*(lsrc->biases))); - memmove(ldst->db, lsrc->db, lsrc->nunits * sizeof(*(lsrc->db))); - if (lsrc->deltas) { - if (!ldst->deltas) ldst->deltas = (float *)calloc(lsrc->nunits, sizeof(float)); - memmove(ldst->deltas, lsrc->deltas, lsrc->nunits * sizeof(*(lsrc->deltas))); - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int BackpropWrite(BACKPROP *backprop, char *fname, int argc, char *argv[], char *comments, int mode) -{ - FILE *fp = NULL; - int i; - char *user; - BPFILE_HEADER hd; - long fpos; - - DiagPrintf(DIAG_WRITE, "BackpropWrite(%s): mode = %s\n", fname, mode == BP_WRITE ? "write" : "append"); - - switch (mode) { - case BP_WRITE: /* create a new file */ - fp = fopen(fname, "w"); - if (!fp) ErrorExit(ERROR_BAD_FILE, "BackpropWrite(%s): could not create file\n", fname); - hd.nnets = 1; - hd.magic = BP_MAGIC; - hd.first = 0L; /* will be filled in with ptr to 1st network */ - if (fwrite(&hd, sizeof(hd), 1, fp) != 1) - ErrorExit(ERROR_BAD_FILE, "BackpropWrite(%s): could not write header\n", fname); - fclose(fp); - fp = fopen(fname, "r+"); - if (!fp) ErrorExit(ERROR_BAD_FILE, "BackpropWrite(%s): could not create file for appending\n", fname); - break; - case BP_APPEND: - fp = fopen(fname, "r+"); - if (!fp) ErrorReturn(-3, (ERROR_BAD_FILE, "BackpropWrite(%s): could not create file for appending\n", fname)); - - if (fread(&hd, sizeof(hd), 1, fp) != 1) - ErrorReturn(-3, (ERROR_BAD_FILE, "BackpropWrite(%s): could not read header from file\n", fname)); - - if (hd.magic != BP_MAGIC) ErrorReturn(-4, (ERROR_BAD_FILE, "BackpropWrite(%s): bad magic #\n", fname)); - break; - } - - fpos = bpFileNewEnd(fp, &hd, 0); /* seek to the last net in the file */ - DiagPrintf(DIAG_WRITE, "after bpFileNewEnd, fpos @ %ld\n", fpos); - - /* put NULL pointer to indicate the end of the ptr chain */ - if (fseek(fp, 0L, SEEK_END)) ErrorExit(ERROR_BAD_FILE, "BackpropWrite(%s): could not seek to end of file\n", fname); - - fpos = 0L; - if (fwrite(&fpos, sizeof(fpos), 1, fp) != 1) - ErrorExit(ERROR_BAD_FILE, "BackpropWrite(%s): could not write null\n", fname); - - DiagPrintf(DIAG_WRITE, "nulls written in file, fpos @ %ld\n", ftell(fp)); - fprintf(fp, - "%d %d %d %f %f %d\n", - backprop->ninputs, - backprop->noutputs, - backprop->nhidden, - backprop->trate, - backprop->momentum, - backprop->user_bytes); - - if (fwrite(backprop->mean_out, sizeof(float), backprop->noutputs, fp) != (size_t)backprop->noutputs) - ErrorExit(ERROR_BAD_FILE, "BackpropWrite(%s): could not write min output vector\n", fname); - - if (fwrite(backprop->std_out, sizeof(float), backprop->noutputs, fp) != (size_t)backprop->noutputs) - ErrorExit(ERROR_BAD_FILE, "BackpropWrite(%s): could not write max output vector\n", fname); - - if (backprop->user_bytes > 0) { - if (fwrite(backprop->user, sizeof(char), backprop->user_bytes, fp) != (size_t)backprop->user_bytes) - ErrorReturn(ERROR_BAD_FILE, - (ERROR_BAD_FILE, "BackpropWrite: could not write %d user bytes\n", backprop->user_bytes)); - } - - bpWriteLayer(fp, &backprop->hidden); - bpWriteLayer(fp, &backprop->output); - - user = getenv("USER"); - if (!user) user = getenv("LOGNAME"); - if (!user) user = "UNKNOWN"; - - fprintf(fp, "\ncreated by %s on %s\n", user, current_date_time()); - for (i = 0; i < argc; i++) fprintf(fp, "%s ", argv[i]); - fprintf(fp, "\n"); - if (comments) fprintf(fp, "%s\n", comments); - - if (mode == BP_APPEND) bpChangeNumberOfNets(fp, 1); - - if (fp != stdout) fclose(fp); - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int BackpropProcess(BACKPROP *backprop, float *I) -{ - int i, class = -1; - LAYER *hidden, *output; - float maxX; - - if (Gdiag & DIAG_BACKPROP) { - if (!backprop->learn) printf("\n"); - printf("BackpropProcess("); - for (i = 0; i < backprop->ninputs; i++) printf("%2.3f ", I[i]); - printf(")\n"); - } - - hidden = &backprop->hidden; - output = &backprop->output; - bpLayerFeedForward(I, hidden, 1); - bpLayerFeedForward(hidden->x, output, 0); - - for (maxX = 0.0f, i = 0; i < backprop->noutputs; i++) { - if (output->x[i] > maxX) { - maxX = output->x[i]; - class = i; - } - } - /* scale outputs to desired range */ - if (!backprop->learn) bpUnnormalizeOutputs(backprop); - - if (Gdiag & DIAG_BACKPROP) { - printf("BackpropProcess returning: "); - for (i = 0; i < backprop->noutputs; i++) printf("%2.5f ", backprop->output.x[i]); - printf("\n"); - } - return (class); -} -#if 1 -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: - convert the output range to unnormalized format -----------------------------------------------------------------------*/ -#define NO_CONVERT 0 -static void bpUnnormalizeOutputs(BACKPROP *backprop) -{ - float mean, std; - int i; - LAYER *output; - - /* scale outputs to desired range */ - output = &backprop->output; - for (i = 0; i < backprop->noutputs; i++) { - mean = backprop->mean_out[i]; - std = backprop->std_out[i]; - output->x[i] = output->x[i] * std + mean; - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: - scale targets to desired range -----------------------------------------------------------------------*/ -static void bpNormalizeTargets(BACKPROP *backprop, float *targets) -{ - float mean, std; - int i; - - /* scale targets to desired range */ - for (i = 0; i < backprop->noutputs; i++) { - mean = backprop->mean_out[i]; - std = backprop->std_out[i]; - targets[i] = (targets[i] - mean) / std; - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: - convert targets back to original unnormalized range -----------------------------------------------------------------------*/ -static void bpUnnormalizeTargets(BACKPROP *backprop, float *targets) -{ - float mean, std; - int i; - - /* scale targets to desired range */ - for (i = 0; i < backprop->noutputs; i++) { - mean = backprop->mean_out[i]; - std = backprop->std_out[i]; - targets[i] = (targets[i] * std) + mean; - } -} -#else -/*---------------------------------------------------------------------- -Parameters: - -Description: - -Returns: -scale outputs to desired range -----------------------------------------------------------------------*/ -#define NO_CONVERT 0 -static void bpUnnormalizeOutputs(BACKPROP *backprop) -{ - float scale, min_out; - int i; - LAYER *output; - -#if NO_CONVERT - return; -#endif - - /* scale outputs to desired range */ - output = &backprop->output; - for (i = 0; i < backprop->noutputs; i++) { - min_out = backprop->min_out[i]; - scale = (backprop->max_out[i] - min_out) / SIG_RANGE; - output->x[i] = (output->x[i] - SIG_MIN) * scale + min_out; - } -} -/*---------------------------------------------------------------------- -Parameters: - -Description: - -Returns: -scale outputs to desired range -----------------------------------------------------------------------*/ -static void bpNormalizeTargets(BACKPROP *backprop, float *targets) -{ - float scale, min_out; - int i; - -#if NO_CONVERT - return; -#endif - - /* scale outputs to desired range */ - for (i = 0; i < backprop->noutputs; i++) { - min_out = backprop->min_out[i]; - scale = (backprop->max_out[i] - min_out) / SIG_RANGE; - targets[i] = (targets[i] - min_out) / scale + SIG_MIN; - } -} -/*---------------------------------------------------------------------- -Parameters: - -Description: - -Returns: -scale outputs to desired range -----------------------------------------------------------------------*/ -static void bpUnnormalizeTargets(BACKPROP *backprop, float *targets) -{ - float scale, min_out; - int i; - -#if NO_CONVERT - return; -#endif - - /* scale outputs to desired range */ - for (i = 0; i < backprop->noutputs; i++) { - min_out = backprop->min_out[i]; - scale = (backprop->max_out[i] - min_out) / SIG_RANGE; - targets[i] = (targets[i] - SIG_MIN) * scale + min_out; - } -} -#endif -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpLayerFeedForward(float *I, LAYER *layer, int nlin) -{ - int i, j, nunits, ninputs; - float *pbias, *px; - register float net, *Ii, *wij; - - if (Gdiag & DIAG_BACKPROP) printf("bpLayerFeedForward()\n"); - - nunits = layer->nunits; - ninputs = layer->ninputs; - pbias = &layer->biases[0]; - px = &layer->x[0]; - for (j = 0; j < nunits; j++) { - net = *pbias++; - if (Gdiag & DIAG_BACKPROP) printf("unit %d: %2.5f\n", j, net); - - Ii = &I[0]; - wij = &Wij(layer, 0, j); - for (i = 0; i < ninputs; i++) { - net += *wij++ * *Ii++; -#if 0 - if (Gdiag & DIAG_BACKPROP) - printf("net += %2.5f * %2.3f --> %2.5f\n", - Wij(layer, i, j), I[i], net) ; -#endif - } - - if (nlin) - *px++ = (float)f(net); - else - *px++ = net; -#if 0 - if (Gdiag & DIAG_BACKPROP) - printf("unit %d output f(%2.5f) = %2.5f\n", j, net, f(net)) ; -#endif - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - train the network for one entire epoch, randomizing the training - order. - - Returns: -----------------------------------------------------------------------*/ -extern FILE *logfp; -float BackpropTrainEpoch( - BACKPROP *bp, - int ntrials, - int (*io_func)(float *inputs, float *targets, int index, int ninputs, int noutputs, void *user), - void *user) -{ - char *input_tested; - float *inputs, *targets; - int tested, index, min_trial, max_trial, i; - BACKPROP *new_bp = NULL; - - new_bp = BackpropCopy(bp, NULL); - input_tested = (char *)calloc(ntrials, sizeof(char)); - inputs = (float *)calloc(bp->ninputs, sizeof(float)); - targets = (float *)calloc(bp->noutputs, sizeof(float)); - if (!input_tested | !inputs | !targets) - ErrorExit(ERROR_BAD_FILE, "BackpropTrainEpoch(%d): could not allocated arrays\n", ntrials); - - /* reset training parameters */ - for (i = 0; i < bp->noutputs; i++) new_bp->errors[i] = 0.0f; - - new_bp->ntrials = 0; - min_trial = 0; - max_trial = ntrials - 1; - new_bp->sse = 0.0f; - - for (tested = 0; tested < ntrials;) /* go through training set once */ - { - index = nint(randomNumber(0.0, (double)(max_trial))); - if (index == max_trial) - while (input_tested[--max_trial] && (max_trial > min_trial)) { - } - if (index == min_trial) - while (input_tested[++min_trial] && (max_trial > min_trial)) { - } - - if (input_tested[index]) continue; - tested++; - if (!(*io_func)(inputs, targets, index, bp->ninputs, bp->noutputs, user)) continue; - input_tested[index] = 1; - - BackpropLearn(new_bp, inputs, targets); /* train candidate network */ - } - -#if 1 - new_bp->sse /= (float)ntrials; -#endif - - if (!bp->nepochs) bp->sse = new_bp->sse; /* nothing to compare it to */ - -/* - for adaptive learning rate: If sse increases by more than ERROR_RATIO, - then update the step size according to: - -for adaptive learning rate: If sse increases by more than ERROR_RATIO, -then update the step size according to: - -learning_rate = learning_rate * TRATE_DECREASE - -otherwise, if the sse decresed, the increase the step size by: - -learning_rate = learning_rate * TRATE_INCREASE. -*/ - -#if 0 - /* only use new weights if error didn't increase too much */ - if (new_bp->sse < bp->sse * bp->error_ratio) - BackpropCopy(new_bp, bp) ; - - if (error_ratio >= 1.0f) /* error decreased */ - { - bp->momentum = bp->old_momentum ; /* restore original momentum */ - } - else /* error increased */ - { - bp->momentum = 0.0f ; - error_ratio *= 2.0f ; /* decrease more than increase */ - } - bp->trate = bp->trate * error_ratio ; - -#else - if (new_bp->sse > bp->sse * bp->error_ratio) /* don't accept change */ - { - bp->trate = bp->trate * bp->trate_down; - bp->momentum = 0.0f; - } - else /* new error is acceptable, use new network */ - { - if (new_bp->sse < bp->sse) /* error decreased, increase trate */ - { - new_bp->trate = new_bp->trate * new_bp->trate_up; - } - else /* error increased by a little NEW!!!! */ - { - new_bp->trate = new_bp->trate * new_bp->trate_down; - /* new_bp->momentum = 0.0f ;*/ - } - /* only use new weights if error didn't increase too much */ - BackpropCopy(new_bp, bp); - - bp->momentum = bp->old_momentum; /* restore original momentum */ - } - if (bp->trate < MIN_TRATE) bp->trate = MIN_TRATE; -#endif - - bp->nepochs++; - - BackpropFree(&new_bp); - free(input_tested); - free(inputs); - free(targets); - return (bp->sse); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -float BackpropLearn(BACKPROP *backprop, float *inputs, float *targets) -{ - // int bpClass; - int i; - LAYER *hidden, *output; - float bpError; - - if (Gdiag & DIAG_BACKPROP) { - printf("\nBackpropLearn "); - for (i = 0; i < backprop->ninputs; i++) printf("%2.3f ", inputs[i]); - printf("--> "); - for (i = 0; i < backprop->noutputs; i++) printf("%2.3f ", targets[i]); - printf("\n"); - } - - if (!backprop->hidden.deltas) { - backprop->hidden.deltas = (float *)InsCalloc(backprop->nhidden, sizeof(float)); - backprop->output.deltas = (float *)InsCalloc(backprop->noutputs, sizeof(float)); - } - - backprop->learn = 1; - - // bpClass = - BackpropProcess(backprop, inputs); - - hidden = &backprop->hidden; - output = &backprop->output; - - bpNormalizeTargets(backprop, targets); /* convert targets to -1 --> 1 */ - bpCalculateOutputDeltas(backprop, targets); - bpCalculateHiddenDeltas(backprop); - bpUpdateLayerWeights(hidden, inputs, backprop->trate, backprop->momentum); - bpUpdateLayerWeights(output, hidden->x, backprop->trate, backprop->momentum); - - bpError = BackpropError(backprop, targets); - - /* - moved the next 2 lines to after the error call. - */ - bpUnnormalizeOutputs(backprop); - bpUnnormalizeTargets(backprop, targets); - - backprop->learn = 0; - backprop->ntrials++; - - return (bpError); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpCalculateOutputDeltas(BACKPROP *backprop, float *targets) -{ - LAYER *output; - float *ptarget, *px, *pdelta, target; - int j, nunits; - register float out; - - /* put in deltas */ - output = &backprop->output; - ptarget = &targets[0]; - px = &output->x[0]; - pdelta = &output->deltas[0]; - nunits = output->nunits; - for (j = 0; j < nunits; j++) { - target = *ptarget++; - out = *px++; - *pdelta++ = (target - out) /* * fprime(out) */; - -#if 0 - if (Gdiag & DIAG_BACKPROP) - printf("Output Delta %d: (%2.3f - %2.5f) * %2.5f = %2.5f\n", - j, target, out, fprime(out), output->deltas[j]) ; -#endif - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpCalculateHiddenDeltas(BACKPROP *backprop) -{ - LAYER *output, *hidden; - int i, j, hnunits, onunits; - register float *pdeli, *pdelj; - - /* put in deltas */ - hidden = &backprop->hidden; - output = &backprop->output; - - hnunits = hidden->nunits; - onunits = output->nunits; - pdeli = &hidden->deltas[0]; - for (i = 0; i < hnunits; i++) { - *pdeli = 0.0f; - -#if 0 - if (Gdiag & DIAG_BACKPROP) - printf("HiddenDelta %d: (", j) ; -#endif - - pdelj = &output->deltas[0]; - for (j = 0; j < onunits; j++) { - *pdeli += *pdelj++ * Wij(output, i, j); -#if 0 - if (Gdiag & DIAG_BACKPROP) - { - printf("%2.5f * %2.5f", output->deltas[j], Wij(output,i,j)) ; - if (j < output->nunits-1) - printf(" + ") ; - } -#endif - } - - *pdeli++ *= fprime(hidden->x[i]); -#if 0 - if (Gdiag & DIAG_BACKPROP) - printf(") * %2.5f = %2.5f\n", - fprime(hidden->x[i]), hidden->deltas[i]) ; -#endif - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpInitLayer(LAYER *layer, int ninputs, int nunits) -{ - long nweights; - - layer->ninputs = ninputs; - layer->nunits = nunits; - layer->x = (float *)InsCalloc(nunits, sizeof(*(layer->x))); - - nweights = (long)ninputs * (long)nunits; - layer->w = (float huge *)InsHalloc(nweights, sizeof(*(layer->w))); - layer->dw = (float huge *)InsHalloc(nweights, sizeof(*(layer->dw))); - layer->biases = (float *)InsCalloc(nunits, sizeof(*(layer->biases))); - layer->db = (float *)InsCalloc(nunits, sizeof(*(layer->db))); - bpInitLayerWeights(layer); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpUpdateLayerWeights(LAYER *layer, float *I, float trate, float momentum) -{ - int i, j, nunits, ninputs; - float delta, one_minus_momentum, db, *Ii; - register float dw, *dwij, *wij; - - one_minus_momentum = trate * (1.0f - momentum); - nunits = layer->nunits; - ninputs = layer->ninputs; - - for (j = 0; j < nunits; j++) { - delta = layer->deltas[j]; - db = delta * one_minus_momentum + momentum * layer->db[j]; - if (Gdiag & DIAG_BACKPROP) - printf("update bias %d: %2.5f + (%2.3f * %2.5f) = %2.5f\n", - j, - layer->biases[j], - trate, - delta, - layer->biases[j] + trate * delta); - - layer->db[j] = db; - layer->biases[j] += db; - - dwij = &DWij(layer, 0, j); - wij = &Wij(layer, 0, j); - Ii = &I[0]; - for (i = 0; i < ninputs; i++, wij++, dwij++) { - dw = one_minus_momentum * delta * *Ii++ + momentum * *dwij; -#if 0 - if (Gdiag & DIAG_BACKPROP) - printf("update weight %d-->%d: %2.5f + (%2.3f * %2.5f * %2.3f)" - "= %2.5f\n", - i,j, Wij(layer,i,j), trate, delta, I[i], - Wij(layer,i,j)+dw) ; -#endif - *wij += dw; - *dwij = dw; - } - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpInitLayerWeights(LAYER *layer) -{ - int i, j; - double rlim; - - /* Haykin rule-of-thumb for good initial weight range */ - rlim = 2.4 / (double)(layer->ninputs); - - /* initialize weights and biases to random values between -1 and 1 */ - for (j = 0; j < layer->nunits; j++) layer->biases[j] = (float)randomNumber(-rlim, rlim); - - for (j = 0; j < layer->nunits; j++) { - for (i = 0; i < layer->ninputs; i++) Wij(layer, i, j) = (float)randomNumber(-rlim, rlim); - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpReadLayer(FILE *fp, LAYER *layer) -{ - int i, j, scanned; - - scanned = fscanf(fp, "%d %d\n", &layer->ninputs, &layer->nunits); - if (scanned != 2) { - fprintf(stderr, "Warning: scanned %d elements, expected 2\n", scanned); - } - bpInitLayer(layer, layer->ninputs, layer->nunits); - - scanned = fscanf(fp, "\n"); - if (scanned != 1) { - fprintf(stderr, "Warning: scanned %d elements, expected 1\n", scanned); - } - /* now read in weights */ - for (j = 0; j < layer->nunits; j++) { - scanned = fscanf(fp, "%f\n", &layer->biases[j]); - if (scanned != 1) { - fprintf(stderr, "Warning: scanned %d elements, expected 1\n", scanned); - } - - for (i = 0; i < layer->ninputs; i++) { - scanned = fscanf(fp, "%f ", &Wij(layer, i, j)); - if (scanned != 1) { - fprintf(stderr, "Warning: scanned %d elements, expected 1\n", scanned); - } - } - - scanned = fscanf(fp, "\n"); - if (scanned != 0) { - fprintf(stderr, "Warning: expected to read newline\n"); - } - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpWriteLayer(FILE *fp, LAYER *layer) -{ - int i, j; - - fprintf(fp, "%d %d\n", layer->ninputs, layer->nunits); - - for (j = 0; j < layer->nunits; j++) { - fprintf(fp, "%f\n", layer->biases[j]); - for (i = 0; i < layer->ninputs; i++) fprintf(fp, "%f ", Wij(layer, i, j)); - - fprintf(fp, "\n"); - } -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int BackpropFree(BACKPROP **pbackprop) -{ - BACKPROP *backprop; - - backprop = *pbackprop; - bpFreeLayer(&backprop->hidden); - bpFreeLayer(&backprop->output); - if (backprop->user) free(backprop->user); - InsFree(backprop); - *pbackprop = NULL; - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static void bpFreeLayer(LAYER *layer) -{ - InsFree(layer->x); - InsHfree(layer->w); - InsHfree(layer->dw); - InsFree(layer->biases); - InsFree(layer->db); - if (layer->deltas) InsFree(layer->deltas); - layer->biases = NULL; - layer->deltas = NULL; - layer->x = NULL; - layer->w = NULL; -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ - -#ifndef TINY -#define TINY 0.000001f -#endif - -float BackpropError(BACKPROP *bp, float *targets) -{ - float bpError, error; - // float total; - int i, nunits; - LAYER *output; - - output = &bp->output; - nunits = output->nunits; -#if 0 - for (i = 0, total = bpError = 0.0f ; i < nunits ; i++) - { - error = fabs(targets[i] - output->x[i]) ; - - bpError += error ; - if (FZERO(targets[i])) - target = TINY ; - else - target = fabs(targets[i]) ; - - bp->errors[i] += error / target ; - ; - total += target ; - } - - bpError /= total ; -#else - // for (i = 0, total = bpError = 0.0f; i < nunits; i++) { - for (i = 0, bpError = 0.0f; i < nunits; i++) { - error = targets[i] - output->x[i]; - error *= error; - - bpError += error; - bp->errors[i] += error; - } - -#endif - - bp->sse += bpError; - - return (bpError); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int BackpropErrorReset(BACKPROP *bp) -{ - memset(bp->errors, 0, bp->noutputs * sizeof(float)); - - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -int BackpropSetParms(BACKPROP *bp, float trate_up, float trate_down, float error_ratio) -{ - bp->trate_up = trate_up; - bp->trate_down = trate_down; - bp->error_ratio = error_ratio; - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -#if 0 -int -BackpropEpochComplete(BACKPROP *bp) -{ - int ntrials ; - - ntrials = bp->ntrials ; - - bp->ntrials = 0 ; - if (bp->nepochs++) /* nothing to compare 0th epoch to */ - { - /* - for adaptive learning rate: If sse increases by more than ERROR_RATIO, - then update the step size according to: - - learning_rate = learning_rate * TRATE_DECREASE - - otherwise, if the sse decresed, the increase the step size by: - - learning_rate = learning_rate * TRATE_INCREASE. - */ - - bp->momentum = bp->old_momentum ; - if (new_bp->sse > bp->sse * bp->error_ratio) - { - bp->trate = bp->trate * bp->trate_down ; - bp->momentum = 0.0f ; - } - else if (new_bp->sse < bp->sse) - bp->trate = bp->trate * bp->trate_up ; - } - bp->old_sse = bp->sse ; - bp->sse = 0.0f ; - - return(0) ; -} -#endif -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static long bpFileNewEnd(FILE *fp, BPFILE_HEADER *hd, int swapped) -{ - long end; - int err; - - if (fseek(fp, 0L, SEEK_END)) ErrorExit(ERROR_BAD_FILE, "bpFileNewEnd: could not seek to end\n"); - - end = ftell(fp); - - bpFileSeekEndPtr(fp, hd, swapped); - DiagPrintf(DIAG_WRITE, "bpFileNewEnd: putting end %ld at %ld\n", end, ftell(fp)); - fseek(fp, 0L, SEEK_CUR); - if ((err = fwrite(&end, sizeof(end), 1, fp)) != 1) - ErrorExit(ERROR_BAD_FILE, "bpFileNewEnd: %d, could not write new end location %ld @ %ld\n", err, end, ftell(fp)); - - return (ftell(fp)); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static long bpFileSeekEndPtr(FILE *fp, BPFILE_HEADER *hd, int swapped) -{ - long next; - - /* - now follow pointer chain to find position of null pointer that we need - to update with the location of the new net. - */ - next = (char *)&(hd->first) - (char *)hd; - DiagPrintf(DIAG_WRITE, "bpFileSeekEnd: starting search at %ld\n", next); - while (next) { - if (fseek(fp, next, SEEK_SET)) ErrorExit(ERROR_BAD_FILE, "bpFileSeekEndPtr: could not seek to %ld\n", next); - if (fread(&next, sizeof(next), 1, fp) != 1) - ErrorExit(ERROR_BAD_FILE, "bpFileNewEnd: could not read pointer @%ld\n", ftell(fp)); - - if (swapped) next = swapLong32(next); - DiagPrintf(DIAG_WRITE, "bpFileSeekEnd: next %ld @ %ld\n", next, ftell(fp) - sizeof(long)); - } - - /* file ptr should be at location of end of pointer chain, not beyond it */ - if (fseek(fp, -(long)sizeof(long), SEEK_CUR)) - ErrorExit(ERROR_BAD_FILE, "bpFileSeekEndPtr: could not seek back sizeof(long)\n"); - - return (ftell(fp)); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static long bpFileSeekNet(FILE *fp, BPFILE_HEADER *hd, int netno, int swapped) -{ - int index; - long next; - - /* - now follow pointer chain to find position of null pointer that we need - to update with the location of the new net. - */ - next = (char *)&(hd->first) - (char *)hd; - DiagPrintf(DIAG_WRITE, "bpFileSeekNet(%d): starting search at %ld\n", netno, next); - for (index = 0; index <= netno; index++) { - if (fseek(fp, next, SEEK_SET)) ErrorExit(ERROR_BAD_FILE, "bpFileSeekNet: could not seek to %ld\n", next); - if (fread(&next, sizeof(next), 1, fp) != 1) - ErrorExit(ERROR_BAD_FILE, "bpFileSeekNet: could not seek to next pointer\n"); - - if (swapped) next = swapLong32(next); - DiagPrintf(DIAG_WRITE, "bpFileSeekNet: %d at %ld\n", index, next); - } - if (fseek(fp, next + sizeof(long), SEEK_SET)) - ErrorExit(ERROR_BAD_FILE, "bpFileSeekNet: could not seek forward sizeof(long)\n"); - - return (next + sizeof(long)); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: - - Returns: -----------------------------------------------------------------------*/ -static int bpChangeNumberOfNets(FILE *fp, int nnets) -{ - BPFILE_HEADER hd; - - DiagPrintf(DIAG_WRITE, "bpChangeNumberOfNets(%d)\n", nnets); - - if (fseek(fp, 0L, SEEK_SET)) - ErrorExit(ERROR_BAD_FILE, "bpChangeNumberOfNets(%d): could not seek to start of file\n", nnets); - - if (fread(&hd, sizeof(hd), 1, fp) != 1) - ErrorExit(ERROR_BAD_FILE, "bpChangeNumberOfNets(%d): could not read header\n", nnets); - - hd.nnets += nnets; - if (fseek(fp, 0L, SEEK_SET)) - ErrorExit(ERROR_BAD_FILE, "bpChangeNumberOfNets(%d): could not seek to start of file\n", nnets); - - if (fwrite(&hd, sizeof(hd), 1, fp) != 1) - ErrorExit(ERROR_BAD_FILE, "bpChangeNumberOfNets(%d): could not write header\n", nnets); - - return (0); -} diff --git a/utils/bfileio.c b/utils/bfileio.cpp similarity index 96% rename from utils/bfileio.c rename to utils/bfileio.cpp index d582df52bfe..78280a0cf94 100644 --- a/utils/bfileio.c +++ b/utils/bfileio.cpp @@ -38,6 +38,8 @@ */ #define BFILEIO_SRC + +#include #include #include #include @@ -155,7 +157,7 @@ char *bf_getstemfromname(char *bfname) } stemlen = len - 7; - stem = calloc(stemlen + 1, sizeof(char)); + stem = (char *)calloc(stemlen + 1, sizeof(char)); if (stem == NULL) { sprintf(bfmsg, "bf_getstemfromname() could not calloc\n"); bferr = 1; @@ -279,8 +281,8 @@ float *bf_ldbfile(char *bfname, int *nrows, int *ncols, int *nfrms) short *sdata = NULL; float *fdata = NULL; FILE *fp; - int err, nread, type, endian, archendian, n; - size_t ntot; + int err, type, endian, archendian; + size_t ntot, nread; bferr = 0; /* get endianness of current architecture */ @@ -304,7 +306,7 @@ float *bf_ldbfile(char *bfname, int *nrows, int *ncols, int *nfrms) } /* create a buffer to hold the data */ - fdata = calloc(ntot, sizeof(float)); + fdata = (float *)calloc(ntot, sizeof(float)); if (fdata == NULL) { sprintf(bfmsg, "bf_ldbfile(): could not alloc float %d", (int)(ntot * sizeof(float))); bferr = 1; @@ -323,7 +325,7 @@ float *bf_ldbfile(char *bfname, int *nrows, int *ncols, int *nfrms) sprintf(bfmsg, "bf_ldbfile(): error reading %s", bfname); bferr = 1; fprintf(stderr, "%s \n", bfmsg); - fprintf(stderr, " ntoberead = %d, nread = %d\n", (int)ntot, nread); + fprintf(stderr, " ntoberead = %d, nread = %d\n", (int)ntot, (int)nread); free(fdata); return (NULL); } @@ -334,7 +336,7 @@ float *bf_ldbfile(char *bfname, int *nrows, int *ncols, int *nfrms) /* --------------------- bshort ---------------------------*/ if (type == BF_SHORT) { /* create a temp short buf */ - sdata = calloc(ntot, sizeof(short)); + sdata = (short *)calloc(ntot, sizeof(short)); if (sdata == NULL) { sprintf(bfmsg, "bf_ldbfile(): could not alloc %d", (int)(ntot * sizeof(short))); bferr = 1; @@ -350,7 +352,7 @@ float *bf_ldbfile(char *bfname, int *nrows, int *ncols, int *nfrms) sprintf(bfmsg, "bf_ldbfile(): error reading %s", bfname); bferr = 1; fprintf(stderr, "%s \n", bfmsg); - fprintf(stderr, " ntoberead = %d, nread = %d\n", (int)ntot, nread); + fprintf(stderr, " ntoberead = %d, nread = %d\n", (int)ntot, (int)nread); free(fdata); free(sdata); return (NULL); @@ -358,7 +360,7 @@ float *bf_ldbfile(char *bfname, int *nrows, int *ncols, int *nfrms) if (endian != archendian) /* swap bytes if necessary */ byteswapbufshort(sdata, ntot * sizeof(short)); /* convert data from short to float */ - for (n = 0; n < ntot; n++) fdata[n] = (float)sdata[n]; + for (unsigned int n = 0; n < ntot; n++) fdata[n] = (float)sdata[n]; free(sdata); } @@ -374,9 +376,9 @@ int bf_svbfile(float *bfdata, char *bfname, int nrows, int ncols, int nfrms, int float *fdata = NULL; char hdrfile[1000]; FILE *fp; - int type, nwrote, archendian, n, err; + int type, archendian, err; int fdatadealloc = 0; - size_t ntot; + size_t ntot, nwrote; bferr = 0; /* get endianness of current architecture */ @@ -436,7 +438,7 @@ int bf_svbfile(float *bfdata, char *bfname, int nrows, int ncols, int nfrms, int sprintf(bfmsg, "bf_svbfile(): error writing to %s", bfname); bferr = 1; fprintf(stderr, "%s \n", bfmsg); - fprintf(stderr, " ntobewritten = %d, nwritten = %d\n", (int)ntot, nwrote); + fprintf(stderr, " ntobewritten = %d, nwritten = %d\n", (int)ntot, (int)nwrote); return (1); } } @@ -451,7 +453,7 @@ int bf_svbfile(float *bfdata, char *bfname, int nrows, int ncols, int nfrms, int fprintf(stderr, "%s \n", bfmsg); return (1); } - for (n = 0; n < ntot; n++) sdata[n] = (short)rint(bfdata[n]); + for (unsigned int n = 0; n < ntot; n++) sdata[n] = (short)rint(bfdata[n]); /* swap bytes if necessary */ if (svendian != archendian) byteswapbufshort(sdata, ntot * sizeof(short)); @@ -466,7 +468,7 @@ int bf_svbfile(float *bfdata, char *bfname, int nrows, int ncols, int nfrms, int sprintf(bfmsg, "bf_svbfile(): error writing to %s", bfname); bferr = 1; fprintf(stderr, "%s \n", bfmsg); - fprintf(stderr, " ntobewritten = %d, nwritten = %d\n", (int)ntot, nwrote); + fprintf(stderr, " ntobewritten = %d, nwritten = %d\n", (int)ntot, (int)nwrote); return (1); } } @@ -510,20 +512,18 @@ int bf_getnslices(char *stem) int bf_getvoltype(char *stem) { FILE *fp; - char bfile[1000], *ext; + char bfile[1000]; memset(bfile, '\0', 1000); - ext = "bshort"; - sprintf(bfile, "%s_000.%s", stem, ext); + sprintf(bfile, "%s_000.%s", stem, "bshort"); fp = fopen(bfile, "r"); if (fp != NULL) { fclose(fp); return (BF_SHORT); } - ext = "bfloat"; - sprintf(bfile, "%s_000.%s", stem, ext); + sprintf(bfile, "%s_000.%s", stem, "bfloat"); fp = fopen(bfile, "r"); if (fp != NULL) { fclose(fp); @@ -653,7 +653,7 @@ int bf_delete_volume(char *stem) char fname[1000]; int nrows, ncols, nslcs, nfrms, endian, type; int err, slice; - char *ext = NULL; + std::string ext; if (!bf_volume_exists(stem)) { fprintf(stderr, "bf_delete_volume(): volume %s does not exist\n", stem); @@ -669,7 +669,7 @@ int bf_delete_volume(char *stem) for (slice = 0; slice < nslcs; slice++) { sprintf(fname, "%s_%03d.hdr", stem, slice); err = unlink(fname); - sprintf(fname, "%s_%03d.%s", stem, slice, ext); + sprintf(fname, "%s_%03d.%s", stem, slice, ext.c_str()); err = unlink(fname); } return (0); @@ -704,7 +704,8 @@ BF_DATA *bf_ldvolume(char *stem) BF_DATA *bfd; int nrows, ncols, nslcs, nfrms, endian, type; int err, slice; - char bfname[1000], *ext; + char bfname[1000]; + std::string ext; float *fdata; err = bf_getvoldim(stem, &nrows, &ncols, &nslcs, &nfrms, &endian, &type); @@ -720,7 +721,7 @@ BF_DATA *bf_ldvolume(char *stem) for (slice = 0; slice < nslcs; slice++) { memset(bfname, '\0', 1000); - sprintf(bfname, "%s_%03d.%s", stem, slice, ext); + sprintf(bfname, "%s_%03d.%s", stem, slice, ext.c_str()); fdata = bf_ldbfile(bfname, &nrows, &ncols, &nfrms); if (fdata == NULL) { bf_freebfd(&bfd); @@ -737,7 +738,8 @@ BF_DATA *bf_ldslice(char *stem, int slice) BF_DATA *bfd; int nrows, ncols, nfrms, endian, type; int err; - char bfname[1000], *ext; + char bfname[1000]; + std::string ext; float *fdata; memset(bfname, '\0', 1000); @@ -748,7 +750,7 @@ BF_DATA *bf_ldslice(char *stem, int slice) else ext = "bfloat"; - sprintf(bfname, "%s_%03d.%s", stem, slice, ext); + sprintf(bfname, "%s_%03d.%s", stem, slice, ext.c_str()); err = bf_getbfiledim(bfname, &nrows, &ncols, &nfrms, &endian, &type); if (err) return (NULL); @@ -769,7 +771,8 @@ BF_DATA *bf_ldslice(char *stem, int slice) int bf_svvolume(BF_DATA *bfd, char *stem, int svendian, int svtype) { int err, slice; - char bfname[1000], *ext; + char bfname[1000]; + std::string ext; float *fdata; memset(bfname, '\0', 1000); @@ -785,7 +788,7 @@ int bf_svvolume(BF_DATA *bfd, char *stem, int svendian, int svtype) ext = "bfloat"; for (slice = 0; slice < bfd->nslcs; slice++) { - sprintf(bfname, "%s_%03d.%s", stem, slice, ext); + sprintf(bfname, "%s_%03d.%s", stem, slice, ext.c_str()); fdata = bfd->slcdata[slice]; err = bf_svbfile(fdata, bfname, bfd->nrows, bfd->ncols, bfd->nfrms, svendian); if (err) return (1); @@ -797,7 +800,8 @@ int bf_svvolume(BF_DATA *bfd, char *stem, int svendian, int svtype) int bf_svslice(BF_DATA *bfd, char *stem, int slice, int svendian, int svtype) { int err; - char bfname[1000], *ext; + char bfname[1000]; + std::string ext; float *fdata; memset(bfname, '\0', 1000); @@ -812,7 +816,7 @@ int bf_svslice(BF_DATA *bfd, char *stem, int slice, int svendian, int svtype) } fdata = bfd->slcdata[0]; - sprintf(bfname, "%s_%03d.%s", stem, slice, ext); + sprintf(bfname, "%s_%03d.%s", stem, slice, ext.c_str()); err = bf_svbfile(fdata, bfname, bfd->nrows, bfd->ncols, bfd->nfrms, svendian); if (err) return (1); diff --git a/utils/box.c b/utils/box.cpp similarity index 100% rename from utils/box.c rename to utils/box.cpp diff --git a/utils/chklc.c b/utils/chklc.cpp similarity index 99% rename from utils/chklc.c rename to utils/chklc.cpp index 9ea54821df4..99360299ab8 100644 --- a/utils/chklc.c +++ b/utils/chklc.cpp @@ -387,7 +387,7 @@ int chklc2(char *msg) void cmp_glib_version(void) { int i; - char *GNU_LIBC_VERSION_MAX = "2.15"; + const char *GNU_LIBC_VERSION_MAX = "2.15"; int glibc_max[2], glibc_current[2]; static const char *new_license_msg = "--------------------------------------------------------------------------\n" diff --git a/utils/chronometer.c b/utils/chronometer.cpp similarity index 100% rename from utils/chronometer.c rename to utils/chronometer.cpp diff --git a/utils/class_array.c b/utils/class_array.cpp similarity index 100% rename from utils/class_array.c rename to utils/class_array.cpp index 141e00bf8c6..2ad787a21d7 100644 --- a/utils/class_array.c +++ b/utils/class_array.cpp @@ -22,8 +22,6 @@ * */ -extern const char *Progname; - /*----------------------------------------------------- INCLUDE FILES -------------------------------------------------------*/ @@ -39,6 +37,8 @@ extern const char *Progname; #include "mrinorm.h" #include "voxlist.h" +extern const char *Progname; + static MATRIX *compute_ras_basis_vectors( MRI *mri_aseg_orig, MRI *mri_aseg_edit, int target_label, int width, int height, int depth, int pad); static int clUpdateStatistics(CA *ca, CLASSIFIER *cl, float *inputs, int output); diff --git a/utils/cluster.c b/utils/cluster.cpp similarity index 100% rename from utils/cluster.c rename to utils/cluster.cpp diff --git a/utils/cma.c b/utils/cma.cpp similarity index 99% rename from utils/cma.c rename to utils/cma.cpp index 75dd6adcd93..932eced5c84 100644 --- a/utils/cma.c +++ b/utils/cma.cpp @@ -954,7 +954,7 @@ surface-based analysis. It also computes the same values based on volume-based analysis to check against the surface-based results. \param subject */ -double *ComputeBrainVolumeStats(char *subject, char *suffix, char *sdir) +double *ComputeBrainVolumeStats(char *subject, char *suff, char *sdir) { char tmpstr[2000]; char *SUBJECTS_DIR; @@ -972,7 +972,12 @@ double *ComputeBrainVolumeStats(char *subject, char *suffix, char *sdir) double OptChiasmVol, CSFVol; double *stats = NULL; - if (suffix == NULL) suffix = ""; + const char *suffix; + if (suff == NULL) { + suffix = ""; + } else { + suffix = suff; + } if (sdir) SUBJECTS_DIR = sdir; diff --git a/utils/cmat.c b/utils/cmat.cpp similarity index 100% rename from utils/cmat.c rename to utils/cmat.cpp diff --git a/utils/cmdargs.c b/utils/cmdargs.cpp similarity index 100% rename from utils/cmdargs.c rename to utils/cmdargs.cpp diff --git a/utils/colortab.c b/utils/colortab.cpp similarity index 99% rename from utils/colortab.c rename to utils/colortab.cpp index 876e7d21ce2..16978f1fa3a 100644 --- a/utils/colortab.c +++ b/utils/colortab.cpp @@ -593,7 +593,7 @@ COLOR_TABLE *CTABreadFromBinaryV1(FILE *fp, int nentries) len)); } name = (char *)malloc(len + 1); - if (fread(name, sizeof(char), len, fp) != len) { + if (fread(name, sizeof(char), len, fp) != (unsigned)len) { ErrorPrintf(ERROR_BADFILE, "CTABreadFromBinaryV1: could not read parameter(s)"); } strncpy(ct->fname, name, sizeof(ct->fname)); @@ -624,7 +624,7 @@ COLOR_TABLE *CTABreadFromBinaryV1(FILE *fp, int nentries) len)); } name = (char *)malloc(len + 1); - if (fread(name, sizeof(char), len, fp) != len) { + if (fread(name, sizeof(char), len, fp) != (unsigned)len) { ErrorPrintf(ERROR_BADFILE, "CTABreadFromBinaryV1: could not read parameter(s)"); } strncpy(ct->entries[structure]->name, name, sizeof(ct->entries[structure]->name)); @@ -728,7 +728,7 @@ COLOR_TABLE *CTABreadFromBinaryV2(FILE *fp) "was %d", len)); name = (char *)malloc(len + 1); - if (fread(name, sizeof(char), len, fp) != len) { + if (fread(name, sizeof(char), len, fp) != (unsigned)len) { ErrorPrintf(ERROR_BADFILE, "CTABreadFromBinaryV1: could not read parameter(s)"); } strncpy(ct->fname, name, sizeof(ct->fname)); @@ -778,7 +778,7 @@ COLOR_TABLE *CTABreadFromBinaryV2(FILE *fp) len)); } name = (char *)malloc(len + 1); - if (fread(name, sizeof(char), len, fp) != len) { + if (fread(name, sizeof(char), len, fp) != (unsigned)len) { ErrorPrintf(ERROR_BADFILE, "CTABreadFromBinaryV1: could not read parameter(s)"); } strncpy(ct->entries[structure]->name, name, sizeof(ct->entries[structure]->name)); @@ -1371,7 +1371,7 @@ int CTABrgb2Annotation(int r, int g, int b) CTABentryNameToIndex(char *EntryName, COLOR_TABLE *ct) Return the color table index given the name of the entry. ----------------------------------------------------------------*/ -int CTABentryNameToIndex(char *EntryName, COLOR_TABLE *ct) +int CTABentryNameToIndex(const char *EntryName, COLOR_TABLE *ct) { CTE *cte; int i; @@ -1389,7 +1389,7 @@ int CTABentryNameToIndex(char *EntryName, COLOR_TABLE *ct) CTABentryNameToIndex(char *EntryName, COLOR_TABLE *ct) Return the color table annotation given the name of the entry. ----------------------------------------------------------------*/ -int CTABentryNameToAnnotation(char *EntryName, COLOR_TABLE *ct) +int CTABentryNameToAnnotation(const char *EntryName, COLOR_TABLE *ct) { CTE *cte; int index, annotation; @@ -1715,7 +1715,7 @@ describes the tissue classes, and (3) the schema name. \param ct - color table with tissue type info (may or may not be null depending upon the schema) */ -COLOR_TABLE *TissueTypeSchema(COLOR_TABLE *ct, char *schema) +COLOR_TABLE *TissueTypeSchema(COLOR_TABLE *ct, const char *schema) { if (strcmp(schema, "default-jan-2014") == 0) { ct = TissueTypeSchemaDefault(ct); diff --git a/utils/connectcomp.c b/utils/connectcomp.cpp similarity index 99% rename from utils/connectcomp.c rename to utils/connectcomp.cpp index d8a28c07c3a..49776b99a7b 100644 --- a/utils/connectcomp.c +++ b/utils/connectcomp.cpp @@ -927,7 +927,7 @@ void myListAddInt(MYlist list, int element) size = myListSize(list); capacity = myListCapacity(list); elementSize = myListElementSize(list); - data = myListData(list); + data = (int *)myListData(list); if (size >= capacity) { capacityIncrement = myListCapacityIncrement(list); @@ -1341,7 +1341,7 @@ void *myRealloc(void *ptr, int size) } /* Prints error message */ -void myError(char error_text[]) +void myError(const char error_text[]) { fprintf(stderr, "Utility run-time error:\n"); fprintf(stderr, "%s\n", error_text); diff --git a/utils/corio.c b/utils/corio.cpp similarity index 100% rename from utils/corio.c rename to utils/corio.cpp diff --git a/utils/cpputils.cpp b/utils/cpputils.cpp index 3db5dbb5ea5..9bf6d7b98e1 100644 --- a/utils/cpputils.cpp +++ b/utils/cpputils.cpp @@ -22,15 +22,12 @@ * */ -const char *CPPUTILS_VERSION = "$Revision: 1.4 $"; - -extern "C" { #include "cma.h" #include "diag.h" #include "macros.h" #include "mri.h" #include "mrisurf.h" -} + #include #include #include @@ -47,7 +44,7 @@ using namespace std; /* This function finds the closest distance of voxels with the distance d of volume mri_dist to the surface mris. */ -extern "C" MRI *MRISsignedFixedDistanceTransform(MRI_SURFACE *mris, MRI *mri_dist, double distance) +MRI *MRISsignedFixedDistanceTransform(MRI_SURFACE *mris, MRI *mri_dist, double distance) { // this volume is used to track visited voxels MRI* mri_visited = MRIcloneDifferentType(mri_dist, MRI_INT); @@ -166,7 +163,7 @@ extern "C" MRI *MRISsignedFixedDistanceTransform(MRI_SURFACE *mris, MRI *mri_dis * around 4 to 5 minutes ) but it's very accurate. returned MRI structure (mri_out) is an MRI_INT MRI volume with voxels * inside having the value 1 and voxels outside with value 0. */ -extern "C" MRI *MRISfillInterior2(MRI_SURFACE *mris, MRI *mri_interior) +MRI *MRISfillInterior2(MRI_SURFACE *mris, MRI *mri_interior) { MRI *_mridist, *mri_out; diff --git a/utils/ctrpoints.c b/utils/ctrpoints.cpp similarity index 99% rename from utils/ctrpoints.c rename to utils/ctrpoints.cpp index 15d0398114c..b88f10ace5b 100644 --- a/utils/ctrpoints.c +++ b/utils/ctrpoints.cpp @@ -172,7 +172,7 @@ int MRIwriteControlPoints(const MPoint *pointArray, int count, int useRealRAS, c } else { strcpy(user, "unknown user"); } - res = fprintf(fp, "written by %s on %s\n", user, current_date_time()); + res = fprintf(fp, "written by %s on %s\n", user, currentDateTime().c_str()); res = fclose(fp); return (NO_ERROR); diff --git a/utils/cvector.c b/utils/cvector.cpp similarity index 99% rename from utils/cvector.c rename to utils/cvector.cpp index 0a9398576e8..a98056fb3ea 100644 --- a/utils/cvector.c +++ b/utils/cvector.cpp @@ -409,8 +409,8 @@ int compare_sort_elts(const void *vse1, const void *vse2) { const SORT_ELT *se1, *se2; - se1 = vse1; - se2 = vse2; + se1 = (const SORT_ELT *)vse1; + se2 = (const SORT_ELT *)vse2; return (se2->snr > se1->snr); } diff --git a/utils/dcdflib.c b/utils/dcdflib.c deleted file mode 100644 index d17e66ec64a..00000000000 --- a/utils/dcdflib.c +++ /dev/null @@ -1,9166 +0,0 @@ -/** - * @file dcdflib.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:42 $ - * $Revision: 1.8 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include "cdflib.h" -#include "proto.h" - -static void E0000(int, - int *, - double *, - double *, - unsigned long *, - unsigned long *, - double *, - double *, - double *, - double *, - double *, - double *, - double *); -static void E0001(int, - int *, - double *, - double *, - double *, - double *, - unsigned long *, - unsigned long *, - double *, - double *, - double *, - double *); -/* - * A comment about ints and longs - whether ints or longs are used should - * make no difference, but where double r-values are assigned to ints the - * r-value is cast converted to a long, which is then assigned to the int - * to be compatible with the operation of fifidint. - */ -/* ------------------------------------------------------------------------ - - COMPUTATION OF LN(GAMMA(B)/GAMMA(A+B)) WHEN B .GE. 8 - - -------- - - IN THIS ALGORITHM, DEL(X) IS THE FUNCTION DEFINED BY - LN(GAMMA(X)) = (X - 0.5)*LN(X) - X + 0.5*LN(2*PI) + DEL(X). - ------------------------------------------------------------------------ -*/ -double algdiv(double *a, double *b) -{ - static double c0 = .833333333333333e-01; - static double c1 = -.277777777760991e-02; - static double c2 = .793650666825390e-03; - static double c3 = -.595202931351870e-03; - static double c4 = .837308034031215e-03; - static double c5 = -.165322962780713e-02; - static double algdiv, c, d, h, s11, s3, s5, s7, s9, t, u, v, w, x, x2, T1; - /* - .. - .. Executable Statements .. - */ - if (*a <= *b) goto S10; - h = *b / *a; - c = 1.0e0 / (1.0e0 + h); - x = h / (1.0e0 + h); - d = *a + (*b - 0.5e0); - goto S20; -S10: - h = *a / *b; - c = h / (1.0e0 + h); - x = 1.0e0 / (1.0e0 + h); - d = *b + (*a - 0.5e0); -S20: - /* - SET SN = (1 - X**N)/(1 - X) - */ - x2 = x * x; - s3 = 1.0e0 + (x + x2); - s5 = 1.0e0 + (x + x2 * s3); - s7 = 1.0e0 + (x + x2 * s5); - s9 = 1.0e0 + (x + x2 * s7); - s11 = 1.0e0 + (x + x2 * s9); - /* - SET W = DEL(B) - DEL(A + B) - */ - t = pow(1.0e0 / *b, 2.0); - w = ((((c5 * s11 * t + c4 * s9) * t + c3 * s7) * t + c2 * s5) * t + c1 * s3) * t + c0; - w *= (c / *b); - /* - COMBINE THE RESULTS - */ - T1 = *a / *b; - u = d * alnrel(&T1); - v = *a * (log(*b) - 1.0e0); - if (u <= v) goto S30; - algdiv = w - v - u; - return algdiv; -S30: - algdiv = w - u - v; - return algdiv; -} -double alngam(double *x) -/* -********************************************************************** - - double alngam(double *x) - double precision LN of the GAMma function - - - Function - - - Returns the natural logarithm of GAMMA(X). - - - Arguments - - - X --> value at which scaled log gamma is to be returned - X is DOUBLE PRECISION - - - Method - - - If X .le. 6.0, then use recursion to get X below 3 - then apply rational approximation number 5236 of - Hart et al, Computer Approximations, John Wiley and - Sons, NY, 1968. - - If X .gt. 6.0, then use recursion to get X to at least 12 and - then use formula 5423 of the same source. - -********************************************************************** -*/ -{ -#define hln2pi 0.91893853320467274178e0 - static double coef[5] = { - 0.83333333333333023564e-1, -0.27777777768818808e-2, 0.79365006754279e-3, -0.594997310889e-3, 0.8065880899e-3}; - static double scoefd[4] = { - 0.62003838007126989331e2, 0.9822521104713994894e1, -0.8906016659497461257e1, 0.1000000000000000000e1}; - static double scoefn[9] = {0.62003838007127258804e2, - 0.36036772530024836321e2, - 0.20782472531792126786e2, - 0.6338067999387272343e1, - 0.215994312846059073e1, - 0.3980671310203570498e0, - 0.1093115956710439502e0, - 0.92381945590275995e-2, - 0.29737866448101651e-2}; - static int K1 = 9; - static int K3 = 4; - static int K5 = 5; - static double alngam, offset, prod, xx; - static int i, n; - static double T2, T4, T6; - /* - .. - .. Executable Statements .. - */ - if (!(*x <= 6.0e0)) goto S70; - prod = 1.0e0; - xx = *x; - if (!(*x > 3.0e0)) goto S30; -S10: - if (!(xx > 3.0e0)) goto S20; - xx -= 1.0e0; - prod *= xx; - goto S10; -S30: -S20: - if (!(*x < 2.0e0)) goto S60; -S40: - if (!(xx < 2.0e0)) goto S50; - prod /= xx; - xx += 1.0e0; - goto S40; -S60: -S50: - T2 = xx - 2.0e0; - T4 = xx - 2.0e0; - alngam = devlpl(scoefn, &K1, &T2) / devlpl(scoefd, &K3, &T4); - /* - COMPUTE RATIONAL APPROXIMATION TO GAMMA(X) - */ - alngam *= prod; - alngam = log(alngam); - goto S110; -S70: - offset = hln2pi; - /* - IF NECESSARY MAKE X AT LEAST 12 AND CARRY CORRECTION IN OFFSET - */ - n = fifidint(12.0e0 - *x); - if (!(n > 0)) goto S90; - prod = 1.0e0; - for (i = 1; i <= n; i++) prod *= (*x + (double)(i - 1)); - offset -= log(prod); - xx = *x + (double)n; - goto S100; -S90: - xx = *x; -S100: - /* - COMPUTE POWER SERIES - */ - T6 = 1.0e0 / pow(xx, 2.0); - alngam = devlpl(coef, &K5, &T6) / xx; - alngam += (offset + (xx - 0.5e0) * log(xx) - xx); -S110: - return alngam; -#undef hln2pi -} -double alnrel(double *a) -/* ------------------------------------------------------------------------ - EVALUATION OF THE FUNCTION LN(1 + A) ------------------------------------------------------------------------ -*/ -{ - static double p1 = -.129418923021993e+01; - static double p2 = .405303492862024e+00; - static double p3 = -.178874546012214e-01; - static double q1 = -.162752256355323e+01; - static double q2 = .747811014037616e+00; - static double q3 = -.845104217945565e-01; - static double alnrel, t, t2, w, x; - /* - .. - .. Executable Statements .. - */ - if (fabs(*a) > 0.375e0) goto S10; - t = *a / (*a + 2.0e0); - t2 = t * t; - w = (((p3 * t2 + p2) * t2 + p1) * t2 + 1.0e0) / (((q3 * t2 + q2) * t2 + q1) * t2 + 1.0e0); - alnrel = 2.0e0 * t * w; - return alnrel; -S10: - x = 1.e0 + *a; - alnrel = log(x); - return alnrel; -} -double apser(double *a, double *b, double *x, double *eps) -/* ------------------------------------------------------------------------ - APSER YIELDS THE INCOMPLETE BETA RATIO I(SUB(1-X))(B,A) FOR - A .LE. MIN(EPS,EPS*B), B*X .LE. 1, AND X .LE. 0.5. USED WHEN - A IS VERY SMALL. USE ONLY IF ABOVE INEQUALITIES ARE SATISFIED. ------------------------------------------------------------------------ -*/ -{ - static double g = .577215664901533e0; - static double apser, aj, bx, c, j, s, t, tol; - /* - .. - .. Executable Statements .. - */ - bx = *b * *x; - t = *x - bx; - if (*b * *eps > 2.e-2) goto S10; - c = log(*x) + psi(b) + g + t; - goto S20; -S10: - c = log(bx) + g + t; -S20: - tol = 5.0e0 * *eps * fabs(c); - j = 1.0e0; - s = 0.0e0; -S30: - j += 1.0e0; - t *= (*x - bx / j); - aj = t / j; - s += aj; - if (fabs(aj) > tol) goto S30; - apser = -(*a * (c + s)); - return apser; -} -double basym(double *a, double *b, double *lambda, double *eps) -/* ------------------------------------------------------------------------ - ASYMPTOTIC EXPANSION FOR IX(A,B) FOR LARGE A AND B. - LAMBDA = (A + B)*Y - B AND EPS IS THE TOLERANCE USED. - IT IS ASSUMED THAT LAMBDA IS NONNEGATIVE AND THAT - A AND B ARE GREATER THAN OR EQUAL TO 15. ------------------------------------------------------------------------ -*/ -{ - static double e0 = 1.12837916709551e0; - static double e1 = .353553390593274e0; - static int num = 20; - /* - ------------------------ - ****** NUM IS THE MAXIMUM VALUE THAT N CAN TAKE IN THE DO LOOP - ENDING AT STATEMENT 50. IT IS REQUIRED THAT NUM BE EVEN. - THE ARRAYS A0, B0, C, D HAVE DIMENSION NUM + 1. - ------------------------ - E0 = 2/SQRT(PI) - E1 = 2**(-3/2) - ------------------------ - */ - static int K3 = 1; - static double basym, bsum, dsum, f, h, h2, hn, j0, j1, r, r0, r1, s, sum, t, t0, t1, u, w, w0, z, z0, z2, zn, znm1; - static int i, im1, imj, j, m, mm1, mmj, n, np1; - static double a0[21], b0[21], c[21], d[21], T1, T2; - /* - .. - .. Executable Statements .. - */ - basym = 0.0e0; - if (*a >= *b) goto S10; - h = *a / *b; - r0 = 1.0e0 / (1.0e0 + h); - r1 = (*b - *a) / *b; - w0 = 1.0e0 / sqrt(*a * (1.0e0 + h)); - goto S20; -S10: - h = *b / *a; - r0 = 1.0e0 / (1.0e0 + h); - r1 = (*b - *a) / *a; - w0 = 1.0e0 / sqrt(*b * (1.0e0 + h)); -S20: - T1 = -(*lambda / *a); - T2 = *lambda / *b; - f = *a * rlog1(&T1) + *b * rlog1(&T2); - t = exp(-f); - if (t == 0.0e0) return basym; - z0 = sqrt(f); - z = 0.5e0 * (z0 / e1); - z2 = f + f; - a0[0] = 2.0e0 / 3.0e0 * r1; - c[0] = -(0.5e0 * a0[0]); - d[0] = -c[0]; - j0 = 0.5e0 / e0 * erfc1(&K3, &z0); - j1 = e1; - sum = j0 + d[0] * w0 * j1; - s = 1.0e0; - h2 = h * h; - hn = 1.0e0; - w = w0; - znm1 = z; - zn = z2; - for (n = 2; n <= num; n += 2) { - hn = h2 * hn; - a0[n - 1] = 2.0e0 * r0 * (1.0e0 + h * hn) / ((double)n + 2.0e0); - np1 = n + 1; - s += hn; - a0[np1 - 1] = 2.0e0 * r1 * s / ((double)n + 3.0e0); - for (i = n; i <= np1; i++) { - r = -(0.5e0 * ((double)i + 1.0e0)); - b0[0] = r * a0[0]; - for (m = 2; m <= i; m++) { - bsum = 0.0e0; - mm1 = m - 1; - for (j = 1; j <= mm1; j++) { - mmj = m - j; - bsum += (((double)j * r - (double)mmj) * a0[j - 1] * b0[mmj - 1]); - } - b0[m - 1] = r * a0[m - 1] + bsum / (double)m; - } - c[i - 1] = b0[i - 1] / ((double)i + 1.0e0); - dsum = 0.0e0; - im1 = i - 1; - for (j = 1; j <= im1; j++) { - imj = i - j; - dsum += (d[imj - 1] * c[j - 1]); - } - d[i - 1] = -(dsum + c[i - 1]); - } - j0 = e1 * znm1 + ((double)n - 1.0e0) * j0; - j1 = e1 * zn + (double)n * j1; - znm1 = z2 * znm1; - zn = z2 * zn; - w = w0 * w; - t0 = d[n - 1] * w * j0; - w = w0 * w; - t1 = d[np1 - 1] * w * j1; - sum += (t0 + t1); - if (fabs(t0) + fabs(t1) <= *eps * sum) goto S80; - } -S80: - u = exp(-bcorr(a, b)); - basym = e0 * t * u * sum; - return basym; -} -double bcorr(double *a0, double *b0) -/* ------------------------------------------------------------------------ - - EVALUATION OF DEL(A0) + DEL(B0) - DEL(A0 + B0) WHERE - LN(GAMMA(A)) = (A - 0.5)*LN(A) - A + 0.5*LN(2*PI) + DEL(A). - IT IS ASSUMED THAT A0 .GE. 8 AND B0 .GE. 8. - ------------------------------------------------------------------------ -*/ -{ - static double c0 = .833333333333333e-01; - static double c1 = -.277777777760991e-02; - static double c2 = .793650666825390e-03; - static double c3 = -.595202931351870e-03; - static double c4 = .837308034031215e-03; - static double c5 = -.165322962780713e-02; - static double bcorr, a, b, c, h, s11, s3, s5, s7, s9, t, w, x, x2; - /* - .. - .. Executable Statements .. - */ - a = fifdmin1(*a0, *b0); - b = fifdmax1(*a0, *b0); - h = a / b; - c = h / (1.0e0 + h); - x = 1.0e0 / (1.0e0 + h); - x2 = x * x; - /* - SET SN = (1 - X**N)/(1 - X) - */ - s3 = 1.0e0 + (x + x2); - s5 = 1.0e0 + (x + x2 * s3); - s7 = 1.0e0 + (x + x2 * s5); - s9 = 1.0e0 + (x + x2 * s7); - s11 = 1.0e0 + (x + x2 * s9); - /* - SET W = DEL(B) - DEL(A + B) - */ - t = pow(1.0e0 / b, 2.0); - w = ((((c5 * s11 * t + c4 * s9) * t + c3 * s7) * t + c2 * s5) * t + c1 * s3) * t + c0; - w *= (c / b); - /* - COMPUTE DEL(A) + W - */ - t = pow(1.0e0 / a, 2.0); - bcorr = (((((c5 * t + c4) * t + c3) * t + c2) * t + c1) * t + c0) / a + w; - return bcorr; -} -double betaln(double *a0, double *b0) -/* ------------------------------------------------------------------------ - EVALUATION OF THE LOGARITHM OF THE BETA FUNCTION ------------------------------------------------------------------------ - E = 0.5*LN(2*PI) --------------------------- -*/ -{ - static double e = .918938533204673e0; - static double betaln, a, b, c, h, u, v, w, z; - static int i, n; - static double T1; - /* - .. - .. Executable Statements .. - */ - a = fifdmin1(*a0, *b0); - b = fifdmax1(*a0, *b0); - if (a >= 8.0e0) goto S100; - if (a >= 1.0e0) goto S20; - /* - ----------------------------------------------------------------------- - PROCEDURE WHEN A .LT. 1 - ----------------------------------------------------------------------- - */ - if (b >= 8.0e0) goto S10; - T1 = a + b; - betaln = gamln(&a) + (gamln(&b) - gamln(&T1)); - return betaln; -S10: - betaln = gamln(&a) + algdiv(&a, &b); - return betaln; -S20: - /* - ----------------------------------------------------------------------- - PROCEDURE WHEN 1 .LE. A .LT. 8 - ----------------------------------------------------------------------- - */ - if (a > 2.0e0) goto S40; - if (b > 2.0e0) goto S30; - betaln = gamln(&a) + gamln(&b) - gsumln(&a, &b); - return betaln; -S30: - w = 0.0e0; - if (b < 8.0e0) goto S60; - betaln = gamln(&a) + algdiv(&a, &b); - return betaln; -S40: - /* - REDUCTION OF A WHEN B .LE. 1000 - */ - if (b > 1000.0e0) goto S80; - n = (long)(a - 1.0e0); - w = 1.0e0; - for (i = 1; i <= n; i++) { - a -= 1.0e0; - h = a / b; - w *= (h / (1.0e0 + h)); - } - w = log(w); - if (b < 8.0e0) goto S60; - betaln = w + gamln(&a) + algdiv(&a, &b); - return betaln; -S60: - /* - REDUCTION OF B WHEN B .LT. 8 - */ - n = (long)(b - 1.0e0); - z = 1.0e0; - for (i = 1; i <= n; i++) { - b -= 1.0e0; - z *= (b / (a + b)); - } - betaln = w + log(z) + (gamln(&a) + (gamln(&b) - gsumln(&a, &b))); - return betaln; -S80: - /* - REDUCTION OF A WHEN B .GT. 1000 - */ - n = (long)(a - 1.0e0); - w = 1.0e0; - for (i = 1; i <= n; i++) { - a -= 1.0e0; - w *= (a / (1.0e0 + a / b)); - } - betaln = log(w) - (double)n * log(b) + (gamln(&a) + algdiv(&a, &b)); - return betaln; -S100: - /* - ----------------------------------------------------------------------- - PROCEDURE WHEN A .GE. 8 - ----------------------------------------------------------------------- - */ - w = bcorr(&a, &b); - h = a / b; - c = h / (1.0e0 + h); - u = -((a - 0.5e0) * log(c)); - v = b * alnrel(&h); - if (u <= v) goto S110; - betaln = -(0.5e0 * log(b)) + e + w - v - u; - return betaln; -S110: - betaln = -(0.5e0 * log(b)) + e + w - u - v; - return betaln; -} -double bfrac(double *a, double *b, double *x, double *y, double *lambda, double *eps) -/* ------------------------------------------------------------------------ - CONTINUED FRACTION EXPANSION FOR IX(A,B) WHEN A,B .GT. 1. - IT IS ASSUMED THAT LAMBDA = (A + B)*Y - B. ------------------------------------------------------------------------ -*/ -{ - static double bfrac, alpha, an, anp1, beta, bn, bnp1, c, c0, c1, e, n, p, r, r0, s, t, w, yp1; - /* - .. - .. Executable Statements .. - */ - bfrac = brcomp(a, b, x, y); - if (bfrac == 0.0e0) return bfrac; - c = 1.0e0 + *lambda; - c0 = *b / *a; - c1 = 1.0e0 + 1.0e0 / *a; - yp1 = *y + 1.0e0; - n = 0.0e0; - p = 1.0e0; - s = *a + 1.0e0; - an = 0.0e0; - bn = anp1 = 1.0e0; - bnp1 = c / c1; - r = c1 / c; -S10: - /* - CONTINUED FRACTION CALCULATION - */ - n += 1.0e0; - t = n / *a; - w = n * (*b - n) * *x; - e = *a / s; - alpha = p * (p + c0) * e * e * (w * *x); - e = (1.0e0 + t) / (c1 + t + t); - beta = n + w / s + e * (c + n * yp1); - p = 1.0e0 + t; - s += 2.0e0; - /* - UPDATE AN, BN, ANP1, AND BNP1 - */ - t = alpha * an + beta * anp1; - an = anp1; - anp1 = t; - t = alpha * bn + beta * bnp1; - bn = bnp1; - bnp1 = t; - r0 = r; - r = anp1 / bnp1; - if (fabs(r - r0) <= *eps * r) goto S20; - /* - RESCALE AN, BN, ANP1, AND BNP1 - */ - an /= bnp1; - bn /= bnp1; - anp1 = r; - bnp1 = 1.0e0; - goto S10; -S20: - /* - TERMINATION - */ - bfrac *= r; - return bfrac; -} -void bgrat(double *a, double *b, double *x, double *y, double *w, double *eps, int *ierr) -/* ------------------------------------------------------------------------ - ASYMPTOTIC EXPANSION FOR IX(A,B) WHEN A IS LARGER THAN B. - THE RESULT OF THE EXPANSION IS ADDED TO W. IT IS ASSUMED - THAT A .GE. 15 AND B .LE. 1. EPS IS THE TOLERANCE USED. - IERR IS A VARIABLE THAT REPORTS THE STATUS OF THE RESULTS. ------------------------------------------------------------------------ -*/ -{ - static double bm1, bp2n, cn, coef, dj, j, l, lnx, n2, nu, p, q, r, s, sum, t, t2, u, v, z; - static int i, n, nm1; - static double c[30], d[30], T1; - /* - .. - .. Executable Statements .. - */ - bm1 = *b - 0.5e0 - 0.5e0; - nu = *a + 0.5e0 * bm1; - if (*y > 0.375e0) goto S10; - T1 = -*y; - lnx = alnrel(&T1); - goto S20; -S10: - lnx = log(*x); -S20: - z = -(nu * lnx); - if (*b * z == 0.0e0) goto S70; - /* - COMPUTATION OF THE EXPANSION - SET R = EXP(-Z)*Z**B/GAMMA(B) - */ - r = *b * (1.0e0 + gam1(b)) * exp(*b * log(z)); - r *= (exp(*a * lnx) * exp(0.5e0 * bm1 * lnx)); - u = algdiv(b, a) + *b * log(nu); - u = r * exp(-u); - if (u == 0.0e0) goto S70; - grat1(b, &z, &r, &p, &q, eps); - v = 0.25e0 * pow(1.0e0 / nu, 2.0); - t2 = 0.25e0 * lnx * lnx; - l = *w / u; - j = q / r; - sum = j; - t = cn = 1.0e0; - n2 = 0.0e0; - for (n = 1; n <= 30; n++) { - bp2n = *b + n2; - j = (bp2n * (bp2n + 1.0e0) * j + (z + bp2n + 1.0e0) * t) * v; - n2 += 2.0e0; - t *= t2; - cn /= (n2 * (n2 + 1.0e0)); - c[n - 1] = cn; - s = 0.0e0; - if (n == 1) goto S40; - nm1 = n - 1; - coef = *b - (double)n; - for (i = 1; i <= nm1; i++) { - s += (coef * c[i - 1] * d[n - i - 1]); - coef += *b; - } - S40: - d[n - 1] = bm1 * cn + s / (double)n; - dj = d[n - 1] * j; - sum += dj; - if (sum <= 0.0e0) goto S70; - if (fabs(dj) <= *eps * (sum + l)) goto S60; - } -S60: - /* - ADD THE RESULTS TO W - */ - *ierr = 0; - *w += (u * sum); - return; -S70: - /* - THE EXPANSION CANNOT BE COMPUTED - */ - *ierr = 1; - return; -} -double bpser(double *a, double *b, double *x, double *eps) -/* ------------------------------------------------------------------------ - POWER SERIES EXPANSION FOR EVALUATING IX(A,B) WHEN B .LE. 1 - OR B*X .LE. 0.7. EPS IS THE TOLERANCE USED. ------------------------------------------------------------------------ -*/ -{ - static double bpser, a0, apb, b0, c, n, sum, t, tol, u, w, z; - static int i, m; - /* - .. - .. Executable Statements .. - */ - bpser = 0.0e0; - if (*x == 0.0e0) return bpser; - /* - ----------------------------------------------------------------------- - COMPUTE THE FACTOR X**A/(A*BETA(A,B)) - ----------------------------------------------------------------------- - */ - a0 = fifdmin1(*a, *b); - if (a0 < 1.0e0) goto S10; - z = *a * log(*x) - betaln(a, b); - bpser = exp(z) / *a; - goto S100; -S10: - b0 = fifdmax1(*a, *b); - if (b0 >= 8.0e0) goto S90; - if (b0 > 1.0e0) goto S40; - /* - PROCEDURE FOR A0 .LT. 1 AND B0 .LE. 1 - */ - bpser = pow(*x, *a); - if (bpser == 0.0e0) return bpser; - apb = *a + *b; - if (apb > 1.0e0) goto S20; - z = 1.0e0 + gam1(&apb); - goto S30; -S20: - u = *a + *b - 1.e0; - z = (1.0e0 + gam1(&u)) / apb; -S30: - c = (1.0e0 + gam1(a)) * (1.0e0 + gam1(b)) / z; - bpser *= (c * (*b / apb)); - goto S100; -S40: - /* - PROCEDURE FOR A0 .LT. 1 AND 1 .LT. B0 .LT. 8 - */ - u = gamln1(&a0); - m = (long)(b0 - 1.0e0); - if (m < 1) goto S60; - c = 1.0e0; - for (i = 1; i <= m; i++) { - b0 -= 1.0e0; - c *= (b0 / (a0 + b0)); - } - u = log(c) + u; -S60: - z = *a * log(*x) - u; - b0 -= 1.0e0; - apb = a0 + b0; - if (apb > 1.0e0) goto S70; - t = 1.0e0 + gam1(&apb); - goto S80; -S70: - u = a0 + b0 - 1.e0; - t = (1.0e0 + gam1(&u)) / apb; -S80: - bpser = exp(z) * (a0 / *a) * (1.0e0 + gam1(&b0)) / t; - goto S100; -S90: - /* - PROCEDURE FOR A0 .LT. 1 AND B0 .GE. 8 - */ - u = gamln1(&a0) + algdiv(&a0, &b0); - z = *a * log(*x) - u; - bpser = a0 / *a * exp(z); -S100: - if (bpser == 0.0e0 || *a <= 0.1e0 * *eps) return bpser; - /* - ----------------------------------------------------------------------- - COMPUTE THE SERIES - ----------------------------------------------------------------------- - */ - sum = n = 0.0e0; - c = 1.0e0; - tol = *eps / *a; -S110: - n += 1.0e0; - c *= ((0.5e0 + (0.5e0 - *b / n)) * *x); - w = c / (*a + n); - sum += w; - if (fabs(w) > tol) goto S110; - bpser *= (1.0e0 + *a * sum); - return bpser; -} -void bratio(double *a, double *b, double *x, double *y, double *w, double *w1, int *ierr) -/* ------------------------------------------------------------------------ - - EVALUATION OF THE INCOMPLETE BETA FUNCTION IX(A,B) - - -------------------- - - IT IS ASSUMED THAT A AND B ARE NONNEGATIVE, AND THAT X .LE. 1 - AND Y = 1 - X. BRATIO ASSIGNS W AND W1 THE VALUES - - W = IX(A,B) - W1 = 1 - IX(A,B) - - IERR IS A VARIABLE THAT REPORTS THE STATUS OF THE RESULTS. - IF NO INPUT ERRORS ARE DETECTED THEN IERR IS SET TO 0 AND - W AND W1 ARE COMPUTED. OTHERWISE, IF AN ERROR IS DETECTED, - THEN W AND W1 ARE ASSIGNED THE VALUE 0 AND IERR IS SET TO - ONE OF THE FOLLOWING VALUES ... - - IERR = 1 IF A OR B IS NEGATIVE - IERR = 2 IF A = B = 0 - IERR = 3 IF X .LT. 0 OR X .GT. 1 - IERR = 4 IF Y .LT. 0 OR Y .GT. 1 - IERR = 5 IF X + Y .NE. 1 - IERR = 6 IF X = A = 0 - IERR = 7 IF Y = B = 0 - --------------------- - WRITTEN BY ALFRED H. MORRIS, JR. - NAVAL SURFACE WARFARE CENTER - DAHLGREN, VIRGINIA - REVISED ... NOV 1991 ------------------------------------------------------------------------ -*/ -{ - static int K1 = 1; - static double a0, b0, eps, lambda, t, x0, y0, z; - static int ierr1, ind, n; - static double T2, T3, T4, T5; - /* - .. - .. Executable Statements .. - */ - /* - ****** EPS IS A MACHINE DEPENDENT CONSTANT. EPS IS THE SMALLEST - FLOATING POINT NUMBER FOR WHICH 1.0 + EPS .GT. 1.0 - */ - eps = spmpar(&K1); - *w = *w1 = 0.0e0; - if (*a < 0.0e0 || *b < 0.0e0) goto S270; - if (*a == 0.0e0 && *b == 0.0e0) goto S280; - if (*x < 0.0e0 || *x > 1.0e0) goto S290; - if (*y < 0.0e0 || *y > 1.0e0) goto S300; - z = *x + *y - 0.5e0 - 0.5e0; - if (fabs(z) > 3.0e0 * eps) goto S310; - *ierr = 0; - if (*x == 0.0e0) goto S210; - if (*y == 0.0e0) goto S230; - if (*a == 0.0e0) goto S240; - if (*b == 0.0e0) goto S220; - eps = fifdmax1(eps, 1.e-15); - if (fifdmax1(*a, *b) < 1.e-3 * eps) goto S260; - ind = 0; - a0 = *a; - b0 = *b; - x0 = *x; - y0 = *y; - if (fifdmin1(a0, b0) > 1.0e0) goto S40; - /* - PROCEDURE FOR A0 .LE. 1 OR B0 .LE. 1 - */ - if (*x <= 0.5e0) goto S10; - ind = 1; - a0 = *b; - b0 = *a; - x0 = *y; - y0 = *x; -S10: - if (b0 < fifdmin1(eps, eps * a0)) goto S90; - if (a0 < fifdmin1(eps, eps * b0) && b0 * x0 <= 1.0e0) goto S100; - if (fifdmax1(a0, b0) > 1.0e0) goto S20; - if (a0 >= fifdmin1(0.2e0, b0)) goto S110; - if (pow(x0, a0) <= 0.9e0) goto S110; - if (x0 >= 0.3e0) goto S120; - n = 20; - goto S140; -S20: - if (b0 <= 1.0e0) goto S110; - if (x0 >= 0.3e0) goto S120; - if (x0 >= 0.1e0) goto S30; - if (pow(x0 * b0, a0) <= 0.7e0) goto S110; -S30: - if (b0 > 15.0e0) goto S150; - n = 20; - goto S140; -S40: - /* - PROCEDURE FOR A0 .GT. 1 AND B0 .GT. 1 - */ - if (*a > *b) goto S50; - lambda = *a - (*a + *b) * *x; - goto S60; -S50: - lambda = (*a + *b) * *y - *b; -S60: - if (lambda >= 0.0e0) goto S70; - ind = 1; - a0 = *b; - b0 = *a; - x0 = *y; - y0 = *x; - lambda = fabs(lambda); -S70: - if (b0 < 40.0e0 && b0 * x0 <= 0.7e0) goto S110; - if (b0 < 40.0e0) goto S160; - if (a0 > b0) goto S80; - if (a0 <= 100.0e0) goto S130; - if (lambda > 0.03e0 * a0) goto S130; - goto S200; -S80: - if (b0 <= 100.0e0) goto S130; - if (lambda > 0.03e0 * b0) goto S130; - goto S200; -S90: - /* - EVALUATION OF THE APPROPRIATE ALGORITHM - */ - *w = fpser(&a0, &b0, &x0, &eps); - *w1 = 0.5e0 + (0.5e0 - *w); - goto S250; -S100: - *w1 = apser(&a0, &b0, &x0, &eps); - *w = 0.5e0 + (0.5e0 - *w1); - goto S250; -S110: - *w = bpser(&a0, &b0, &x0, &eps); - *w1 = 0.5e0 + (0.5e0 - *w); - goto S250; -S120: - *w1 = bpser(&b0, &a0, &y0, &eps); - *w = 0.5e0 + (0.5e0 - *w1); - goto S250; -S130: - T2 = 15.0e0 * eps; - *w = bfrac(&a0, &b0, &x0, &y0, &lambda, &T2); - *w1 = 0.5e0 + (0.5e0 - *w); - goto S250; -S140: - *w1 = bup(&b0, &a0, &y0, &x0, &n, &eps); - b0 += (double)n; -S150: - T3 = 15.0e0 * eps; - bgrat(&b0, &a0, &y0, &x0, w1, &T3, &ierr1); - *w = 0.5e0 + (0.5e0 - *w1); - goto S250; -S160: - n = (long)(b0); - b0 -= (double)n; - if (b0 != 0.0e0) goto S170; - n -= 1; - b0 = 1.0e0; -S170: - *w = bup(&b0, &a0, &y0, &x0, &n, &eps); - if (x0 > 0.7e0) goto S180; - *w += bpser(&a0, &b0, &x0, &eps); - *w1 = 0.5e0 + (0.5e0 - *w); - goto S250; -S180: - if (a0 > 15.0e0) goto S190; - n = 20; - *w += bup(&a0, &b0, &x0, &y0, &n, &eps); - a0 += (double)n; -S190: - T4 = 15.0e0 * eps; - bgrat(&a0, &b0, &x0, &y0, w, &T4, &ierr1); - *w1 = 0.5e0 + (0.5e0 - *w); - goto S250; -S200: - T5 = 100.0e0 * eps; - *w = basym(&a0, &b0, &lambda, &T5); - *w1 = 0.5e0 + (0.5e0 - *w); - goto S250; -S210: - /* - TERMINATION OF THE PROCEDURE - */ - if (*a == 0.0e0) goto S320; -S220: - *w = 0.0e0; - *w1 = 1.0e0; - return; -S230: - if (*b == 0.0e0) goto S330; -S240: - *w = 1.0e0; - *w1 = 0.0e0; - return; -S250: - if (ind == 0) return; - t = *w; - *w = *w1; - *w1 = t; - return; -S260: - /* - PROCEDURE FOR A AND B .LT. 1.E-3*EPS - */ - *w = *b / (*a + *b); - *w1 = *a / (*a + *b); - return; -S270: - /* - ERROR RETURN - */ - *ierr = 1; - return; -S280: - *ierr = 2; - return; -S290: - *ierr = 3; - return; -S300: - *ierr = 4; - return; -S310: - *ierr = 5; - return; -S320: - *ierr = 6; - return; -S330: - *ierr = 7; - return; -} -double brcmp1(int *mu, double *a, double *b, double *x, double *y) -/* ------------------------------------------------------------------------ - EVALUATION OF EXP(MU) * (X**A*Y**B/BETA(A,B)) ------------------------------------------------------------------------ -*/ -{ - static double Const = .398942280401433e0; - static double brcmp1, a0, apb, b0, c, e, h, lambda, lnx, lny, t, u, v, x0, y0, z; - static int i, n; - /* - ----------------- - CONST = 1/SQRT(2*PI) - ----------------- - */ - static double T1, T2, T3, T4; - /* - .. - .. Executable Statements .. - */ - a0 = fifdmin1(*a, *b); - if (a0 >= 8.0e0) goto S130; - if (*x > 0.375e0) goto S10; - lnx = log(*x); - T1 = -*x; - lny = alnrel(&T1); - goto S30; -S10: - if (*y > 0.375e0) goto S20; - T2 = -*y; - lnx = alnrel(&T2); - lny = log(*y); - goto S30; -S20: - lnx = log(*x); - lny = log(*y); -S30: - z = *a * lnx + *b * lny; - if (a0 < 1.0e0) goto S40; - z -= betaln(a, b); - brcmp1 = esum(mu, &z); - return brcmp1; -S40: - /* - ----------------------------------------------------------------------- - PROCEDURE FOR A .LT. 1 OR B .LT. 1 - ----------------------------------------------------------------------- - */ - b0 = fifdmax1(*a, *b); - if (b0 >= 8.0e0) goto S120; - if (b0 > 1.0e0) goto S70; - /* - ALGORITHM FOR B0 .LE. 1 - */ - brcmp1 = esum(mu, &z); - if (brcmp1 == 0.0e0) return brcmp1; - apb = *a + *b; - if (apb > 1.0e0) goto S50; - z = 1.0e0 + gam1(&apb); - goto S60; -S50: - u = *a + *b - 1.e0; - z = (1.0e0 + gam1(&u)) / apb; -S60: - c = (1.0e0 + gam1(a)) * (1.0e0 + gam1(b)) / z; - brcmp1 = brcmp1 * (a0 * c) / (1.0e0 + a0 / b0); - return brcmp1; -S70: - /* - ALGORITHM FOR 1 .LT. B0 .LT. 8 - */ - u = gamln1(&a0); - n = (long)(b0 - 1.0e0); - if (n < 1) goto S90; - c = 1.0e0; - for (i = 1; i <= n; i++) { - b0 -= 1.0e0; - c *= (b0 / (a0 + b0)); - } - u = log(c) + u; -S90: - z -= u; - b0 -= 1.0e0; - apb = a0 + b0; - if (apb > 1.0e0) goto S100; - t = 1.0e0 + gam1(&apb); - goto S110; -S100: - u = a0 + b0 - 1.e0; - t = (1.0e0 + gam1(&u)) / apb; -S110: - brcmp1 = a0 * esum(mu, &z) * (1.0e0 + gam1(&b0)) / t; - return brcmp1; -S120: - /* - ALGORITHM FOR B0 .GE. 8 - */ - u = gamln1(&a0) + algdiv(&a0, &b0); - T3 = z - u; - brcmp1 = a0 * esum(mu, &T3); - return brcmp1; -S130: - /* - ----------------------------------------------------------------------- - PROCEDURE FOR A .GE. 8 AND B .GE. 8 - ----------------------------------------------------------------------- - */ - if (*a > *b) goto S140; - h = *a / *b; - x0 = h / (1.0e0 + h); - y0 = 1.0e0 / (1.0e0 + h); - lambda = *a - (*a + *b) * *x; - goto S150; -S140: - h = *b / *a; - x0 = 1.0e0 / (1.0e0 + h); - y0 = h / (1.0e0 + h); - lambda = (*a + *b) * *y - *b; -S150: - e = -(lambda / *a); - if (fabs(e) > 0.6e0) goto S160; - u = rlog1(&e); - goto S170; -S160: - u = e - log(*x / x0); -S170: - e = lambda / *b; - if (fabs(e) > 0.6e0) goto S180; - v = rlog1(&e); - goto S190; -S180: - v = e - log(*y / y0); -S190: - T4 = -(*a * u + *b * v); - z = esum(mu, &T4); - brcmp1 = Const * sqrt(*b * x0) * z * exp(-bcorr(a, b)); - return brcmp1; -} -double brcomp(double *a, double *b, double *x, double *y) -/* ------------------------------------------------------------------------ - EVALUATION OF X**A*Y**B/BETA(A,B) ------------------------------------------------------------------------ -*/ -{ - static double Const = .398942280401433e0; - static double brcomp, a0, apb, b0, c, e, h, lambda, lnx, lny, t, u, v, x0, y0, z; - static int i, n; - /* - ----------------- - CONST = 1/SQRT(2*PI) - ----------------- - */ - static double T1, T2; - /* - .. - .. Executable Statements .. - */ - brcomp = 0.0e0; - if (*x == 0.0e0 || *y == 0.0e0) return brcomp; - a0 = fifdmin1(*a, *b); - if (a0 >= 8.0e0) goto S130; - if (*x > 0.375e0) goto S10; - lnx = log(*x); - T1 = -*x; - lny = alnrel(&T1); - goto S30; -S10: - if (*y > 0.375e0) goto S20; - T2 = -*y; - lnx = alnrel(&T2); - lny = log(*y); - goto S30; -S20: - lnx = log(*x); - lny = log(*y); -S30: - z = *a * lnx + *b * lny; - if (a0 < 1.0e0) goto S40; - z -= betaln(a, b); - brcomp = exp(z); - return brcomp; -S40: - /* - ----------------------------------------------------------------------- - PROCEDURE FOR A .LT. 1 OR B .LT. 1 - ----------------------------------------------------------------------- - */ - b0 = fifdmax1(*a, *b); - if (b0 >= 8.0e0) goto S120; - if (b0 > 1.0e0) goto S70; - /* - ALGORITHM FOR B0 .LE. 1 - */ - brcomp = exp(z); - if (brcomp == 0.0e0) return brcomp; - apb = *a + *b; - if (apb > 1.0e0) goto S50; - z = 1.0e0 + gam1(&apb); - goto S60; -S50: - u = *a + *b - 1.e0; - z = (1.0e0 + gam1(&u)) / apb; -S60: - c = (1.0e0 + gam1(a)) * (1.0e0 + gam1(b)) / z; - brcomp = brcomp * (a0 * c) / (1.0e0 + a0 / b0); - return brcomp; -S70: - /* - ALGORITHM FOR 1 .LT. B0 .LT. 8 - */ - u = gamln1(&a0); - n = (long)(b0 - 1.0e0); - if (n < 1) goto S90; - c = 1.0e0; - for (i = 1; i <= n; i++) { - b0 -= 1.0e0; - c *= (b0 / (a0 + b0)); - } - u = log(c) + u; -S90: - z -= u; - b0 -= 1.0e0; - apb = a0 + b0; - if (apb > 1.0e0) goto S100; - t = 1.0e0 + gam1(&apb); - goto S110; -S100: - u = a0 + b0 - 1.e0; - t = (1.0e0 + gam1(&u)) / apb; -S110: - brcomp = a0 * exp(z) * (1.0e0 + gam1(&b0)) / t; - return brcomp; -S120: - /* - ALGORITHM FOR B0 .GE. 8 - */ - u = gamln1(&a0) + algdiv(&a0, &b0); - brcomp = a0 * exp(z - u); - return brcomp; -S130: - /* - ----------------------------------------------------------------------- - PROCEDURE FOR A .GE. 8 AND B .GE. 8 - ----------------------------------------------------------------------- - */ - if (*a > *b) goto S140; - h = *a / *b; - x0 = h / (1.0e0 + h); - y0 = 1.0e0 / (1.0e0 + h); - lambda = *a - (*a + *b) * *x; - goto S150; -S140: - h = *b / *a; - x0 = 1.0e0 / (1.0e0 + h); - y0 = h / (1.0e0 + h); - lambda = (*a + *b) * *y - *b; -S150: - e = -(lambda / *a); - if (fabs(e) > 0.6e0) goto S160; - u = rlog1(&e); - goto S170; -S160: - u = e - log(*x / x0); -S170: - e = lambda / *b; - if (fabs(e) > 0.6e0) goto S180; - v = rlog1(&e); - goto S190; -S180: - v = e - log(*y / y0); -S190: - z = exp(-(*a * u + *b * v)); - brcomp = Const * sqrt(*b * x0) * z * exp(-bcorr(a, b)); - return brcomp; -} -double bup(double *a, double *b, double *x, double *y, int *n, double *eps) -/* ------------------------------------------------------------------------ - EVALUATION OF IX(A,B) - IX(A+N,B) WHERE N IS A POSITIVE INTEGER. - EPS IS THE TOLERANCE USED. ------------------------------------------------------------------------ -*/ -{ - static int K1 = 1; - static int K2 = 0; - static double bup, ap1, apb, d, l, r, t, w; - static int i, k, kp1, mu, nm1; - /* - .. - .. Executable Statements .. - */ - /* - OBTAIN THE SCALING FACTOR EXP(-MU) AND - EXP(MU)*(X**A*Y**B/BETA(A,B))/A - */ - apb = *a + *b; - ap1 = *a + 1.0e0; - mu = 0; - d = 1.0e0; - if (*n == 1 || *a < 1.0e0) goto S10; - if (apb < 1.1e0 * ap1) goto S10; - mu = (long)(fabs(exparg(&K1))); - k = (long)(exparg(&K2)); - if (k < mu) mu = k; - t = mu; - d = exp(-t); -S10: - bup = brcmp1(&mu, a, b, x, y) / *a; - if (*n == 1 || bup == 0.0e0) return bup; - nm1 = *n - 1; - w = d; - /* - LET K BE THE INDEX OF THE MAXIMUM TERM - */ - k = 0; - if (*b <= 1.0e0) goto S50; - if (*y > 1.e-4) goto S20; - k = nm1; - goto S30; -S20: - r = (*b - 1.0e0) * *x / *y - *a; - if (r < 1.0e0) goto S50; - t = nm1; - k = (long)(t); - if (r < t) k = (long)(r); -S30: - /* - ADD THE INCREASING TERMS OF THE SERIES - */ - for (i = 1; i <= k; i++) { - l = i - 1; - d = (apb + l) / (ap1 + l) * *x * d; - w += d; - } - if (k == nm1) goto S70; -S50: - /* - ADD THE REMAINING TERMS OF THE SERIES - */ - kp1 = k + 1; - for (i = kp1; i <= nm1; i++) { - l = i - 1; - d = (apb + l) / (ap1 + l) * *x * d; - w += d; - if (d <= *eps * w) goto S70; - } -S70: - /* - TERMINATE THE PROCEDURE - */ - bup *= w; - return bup; -} -void cdfbet(int *which, double *p, double *q, double *x, double *y, double *a, double *b, int *status, double *bound) -/********************************************************************** - - void cdfbet(int *which,double *p,double *q,double *x,double *y, - double *a,double *b,int *status,double *bound) - - Cumulative Distribution Function - BETa Distribution - - - Function - - - Calculates any one parameter of the beta distribution given - values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next four argument - values is to be calculated from the others. - Legal range: 1..4 - iwhich = 1 : Calculate P and Q from X,Y,A and B - iwhich = 2 : Calculate X and Y from P,Q,A and B - iwhich = 3 : Calculate A from P,Q,X,Y and B - iwhich = 4 : Calculate B from P,Q,X,Y and A - - P <--> The integral from 0 to X of the chi-square - distribution. - Input range: [0, 1]. - - Q <--> 1-P. - Input range: [0, 1]. - P + Q = 1.0. - - X <--> Upper limit of integration of beta density. - Input range: [0,1]. - Search range: [0,1] - - Y <--> 1-X. - Input range: [0,1]. - Search range: [0,1] - X + Y = 1.0. - - A <--> The first parameter of the beta density. - Input range: (0, +infinity). - Search range: [1D-100,1D100] - - B <--> The second parameter of the beta density. - Input range: (0, +infinity). - Search range: [1D-100,1D100] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - 4 if X + Y .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Cumulative distribution function (P) is calculated directly by - code associated with the following reference. - - DiDinato, A. R. and Morris, A. H. Algorithm 708: Significant - Digit Computation of the Incomplete Beta Function Ratios. ACM - Trans. Math. Softw. 18 (1993), 360-373. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - - - Note - - - The beta density is proportional to - t^(A-1) * (1-t)^(B-1) - -**********************************************************************/ -{ -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define inf 1.0e100 -#define one 1.0e0 - static int K1 = 1; - static double K2 = 0.0e0; - static double K3 = 1.0e0; - static double K8 = 0.5e0; - static double K9 = 5.0e0; - static double fx, xhi, xlo, cum, ccum, xy, pq; - static unsigned long qhi, qleft, qporq; - static double T4, T5, T6, T7, T10, T11, T12, T13, T14, T15; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 4.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q < 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q < 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 2) goto S150; - /* - X - */ - if (!(*x < 0.0e0 || *x > 1.0e0)) goto S140; - if (!(*x < 0.0e0)) goto S120; - *bound = 0.0e0; - goto S130; -S120: - *bound = 1.0e0; -S130: - *status = -4; - return; -S150: -S140: - if (*which == 2) goto S190; - /* - Y - */ - if (!(*y < 0.0e0 || *y > 1.0e0)) goto S180; - if (!(*y < 0.0e0)) goto S160; - *bound = 0.0e0; - goto S170; -S160: - *bound = 1.0e0; -S170: - *status = -5; - return; -S190: -S180: - if (*which == 3) goto S210; - /* - A - */ - if (!(*a <= 0.0e0)) goto S200; - *bound = 0.0e0; - *status = -6; - return; -S210: -S200: - if (*which == 4) goto S230; - /* - B - */ - if (!(*b <= 0.0e0)) goto S220; - *bound = 0.0e0; - *status = -7; - return; -S230: -S220: - if (*which == 1) goto S270; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S260; - if (!(pq < 0.0e0)) goto S240; - *bound = 0.0e0; - goto S250; -S240: - *bound = 1.0e0; -S250: - *status = 3; - return; -S270: -S260: - if (*which == 2) goto S310; - /* - X + Y - */ - xy = *x + *y; - if (!(fabs(xy - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S300; - if (!(xy < 0.0e0)) goto S280; - *bound = 0.0e0; - goto S290; -S280: - *bound = 1.0e0; -S290: - *status = 4; - return; -S310: -S300: - if (!(*which == 1)) qporq = *p <= *q; - /* - Select the minimum of P or Q - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P and Q - */ - cumbet(x, y, a, b, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Calculating X and Y - */ - T4 = atol; - T5 = tol; - dstzr(&K2, &K3, &T4, &T5); - if (!qporq) goto S340; - *status = 0; - dzror(status, x, &fx, &xlo, &xhi, &qleft, &qhi); - *y = one - *x; - S320: - if (!(*status == 1)) goto S330; - cumbet(x, y, a, b, &cum, &ccum); - fx = cum - *p; - dzror(status, x, &fx, &xlo, &xhi, &qleft, &qhi); - *y = one - *x; - goto S320; - S330: - goto S370; - S340: - *status = 0; - dzror(status, y, &fx, &xlo, &xhi, &qleft, &qhi); - *x = one - *y; - S350: - if (!(*status == 1)) goto S360; - cumbet(x, y, a, b, &cum, &ccum); - fx = ccum - *q; - dzror(status, y, &fx, &xlo, &xhi, &qleft, &qhi); - *x = one - *y; - goto S350; - S370: - S360: - if (!(*status == -1)) goto S400; - if (!qleft) goto S380; - *status = 1; - *bound = 0.0e0; - goto S390; - S380: - *status = 2; - *bound = 1.0e0; - S400: - S390:; - } - else if (3 == *which) { - /* - Computing A - */ - *a = 5.0e0; - T6 = zero; - T7 = inf; - T10 = atol; - T11 = tol; - dstinv(&T6, &T7, &K8, &K8, &K9, &T10, &T11); - *status = 0; - dinvr(status, a, &fx, &qleft, &qhi); - S410: - if (!(*status == 1)) goto S440; - cumbet(x, y, a, b, &cum, &ccum); - if (!qporq) goto S420; - fx = cum - *p; - goto S430; - S420: - fx = ccum - *q; - S430: - dinvr(status, a, &fx, &qleft, &qhi); - goto S410; - S440: - if (!(*status == -1)) goto S470; - if (!qleft) goto S450; - *status = 1; - *bound = zero; - goto S460; - S450: - *status = 2; - *bound = inf; - S470: - S460:; - } - else if (4 == *which) { - /* - Computing B - */ - *b = 5.0e0; - T12 = zero; - T13 = inf; - T14 = atol; - T15 = tol; - dstinv(&T12, &T13, &K8, &K8, &K9, &T14, &T15); - *status = 0; - dinvr(status, b, &fx, &qleft, &qhi); - S480: - if (!(*status == 1)) goto S510; - cumbet(x, y, a, b, &cum, &ccum); - if (!qporq) goto S490; - fx = cum - *p; - goto S500; - S490: - fx = ccum - *q; - S500: - dinvr(status, b, &fx, &qleft, &qhi); - goto S480; - S510: - if (!(*status == -1)) goto S540; - if (!qleft) goto S520; - *status = 1; - *bound = zero; - goto S530; - S520: - *status = 2; - *bound = inf; - S530:; - } -S540: - return; -#undef tol -#undef atol -#undef zero -#undef inf -#undef one -} -void cdfbin( - int *which, double *p, double *q, double *s, double *xn, double *pr, double *ompr, int *status, double *bound) -/********************************************************************** - - void cdfbin(int *which,double *p,double *q,double *s,double *xn, - double *pr,double *ompr,int *status,double *bound) - - Cumulative Distribution Function - BINomial distribution - - - Function - - - Calculates any one parameter of the binomial - distribution given values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next four argument - values is to be calculated from the others. - Legal range: 1..4 - iwhich = 1 : Calculate P and Q from S,XN,PR and OMPR - iwhich = 2 : Calculate S from P,Q,XN,PR and OMPR - iwhich = 3 : Calculate XN from P,Q,S,PR and OMPR - iwhich = 4 : Calculate PR and OMPR from P,Q,S and XN - - P <--> The cumulation from 0 to S of the binomial distribution. - (Probablility of S or fewer successes in XN trials each - with probability of success PR.) - Input range: [0,1]. - - Q <--> 1-P. - Input range: [0, 1]. - P + Q = 1.0. - - S <--> The number of successes observed. - Input range: [0, XN] - Search range: [0, XN] - - XN <--> The number of binomial trials. - Input range: (0, +infinity). - Search range: [1E-100, 1E100] - - PR <--> The probability of success in each binomial trial. - Input range: [0,1]. - Search range: [0,1] - - OMPR <--> 1-PR - Input range: [0,1]. - Search range: [0,1] - PR + OMPR = 1.0 - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - 4 if PR + OMPR .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.5.24 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce the binomial - distribution to the cumulative incomplete beta distribution. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - - -**********************************************************************/ -{ -#define atol 1.0e-50 -#define tol 1.0e-8 -#define zero 1.0e-100 -#define inf 1.0e100 -#define one 1.0e0 - static int K1 = 1; - static double K2 = 0.0e0; - static double K3 = 0.5e0; - static double K4 = 5.0e0; - static double K11 = 1.0e0; - static double fx, xhi, xlo, cum, ccum, pq, prompr; - static unsigned long qhi, qleft, qporq; - static double T5, T6, T7, T8, T9, T10, T12, T13; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 && *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 4.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q < 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q < 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 3) goto S130; - /* - XN - */ - if (!(*xn <= 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -5; - return; -S130: -S120: - if (*which == 2) goto S170; - /* - S - */ - if (!(*s < 0.0e0 || (*which != 3 && *s > *xn))) goto S160; - if (!(*s < 0.0e0)) goto S140; - *bound = 0.0e0; - goto S150; -S140: - *bound = *xn; -S150: - *status = -4; - return; -S170: -S160: - if (*which == 4) goto S210; - /* - PR - */ - if (!(*pr < 0.0e0 || *pr > 1.0e0)) goto S200; - if (!(*pr < 0.0e0)) goto S180; - *bound = 0.0e0; - goto S190; -S180: - *bound = 1.0e0; -S190: - *status = -6; - return; -S210: -S200: - if (*which == 4) goto S250; - /* - OMPR - */ - if (!(*ompr < 0.0e0 || *ompr > 1.0e0)) goto S240; - if (!(*ompr < 0.0e0)) goto S220; - *bound = 0.0e0; - goto S230; -S220: - *bound = 1.0e0; -S230: - *status = -7; - return; -S250: -S240: - if (*which == 1) goto S290; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S280; - if (!(pq < 0.0e0)) goto S260; - *bound = 0.0e0; - goto S270; -S260: - *bound = 1.0e0; -S270: - *status = 3; - return; -S290: -S280: - if (*which == 4) goto S330; - /* - PR + OMPR - */ - prompr = *pr + *ompr; - if (!(fabs(prompr - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S320; - if (!(prompr < 0.0e0)) goto S300; - *bound = 0.0e0; - goto S310; -S300: - *bound = 1.0e0; -S310: - *status = 4; - return; -S330: -S320: - if (!(*which == 1)) qporq = *p <= *q; - /* - Select the minimum of P or Q - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P - */ - cumbin(s, xn, pr, ompr, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Calculating S - */ - *s = 5.0e0; - T5 = atol; - T6 = tol; - dstinv(&K2, xn, &K3, &K3, &K4, &T5, &T6); - *status = 0; - dinvr(status, s, &fx, &qleft, &qhi); - S340: - if (!(*status == 1)) goto S370; - cumbin(s, xn, pr, ompr, &cum, &ccum); - if (!qporq) goto S350; - fx = cum - *p; - goto S360; - S350: - fx = ccum - *q; - S360: - dinvr(status, s, &fx, &qleft, &qhi); - goto S340; - S370: - if (!(*status == -1)) goto S400; - if (!qleft) goto S380; - *status = 1; - *bound = 0.0e0; - goto S390; - S380: - *status = 2; - *bound = *xn; - S400: - S390:; - } - else if (3 == *which) { - /* - Calculating XN - */ - *xn = 5.0e0; - T7 = zero; - T8 = inf; - T9 = atol; - T10 = tol; - dstinv(&T7, &T8, &K3, &K3, &K4, &T9, &T10); - *status = 0; - dinvr(status, xn, &fx, &qleft, &qhi); - S410: - if (!(*status == 1)) goto S440; - cumbin(s, xn, pr, ompr, &cum, &ccum); - if (!qporq) goto S420; - fx = cum - *p; - goto S430; - S420: - fx = ccum - *q; - S430: - dinvr(status, xn, &fx, &qleft, &qhi); - goto S410; - S440: - if (!(*status == -1)) goto S470; - if (!qleft) goto S450; - *status = 1; - *bound = zero; - goto S460; - S450: - *status = 2; - *bound = inf; - S470: - S460:; - } - else if (4 == *which) { - /* - Calculating PR and OMPR - */ - T12 = atol; - T13 = tol; - dstzr(&K2, &K11, &T12, &T13); - if (!qporq) goto S500; - *status = 0; - dzror(status, pr, &fx, &xlo, &xhi, &qleft, &qhi); - *ompr = one - *pr; - S480: - if (!(*status == 1)) goto S490; - cumbin(s, xn, pr, ompr, &cum, &ccum); - fx = cum - *p; - dzror(status, pr, &fx, &xlo, &xhi, &qleft, &qhi); - *ompr = one - *pr; - goto S480; - S490: - goto S530; - S500: - *status = 0; - dzror(status, ompr, &fx, &xlo, &xhi, &qleft, &qhi); - *pr = one - *ompr; - S510: - if (!(*status == 1)) goto S520; - cumbin(s, xn, pr, ompr, &cum, &ccum); - fx = ccum - *q; - dzror(status, ompr, &fx, &xlo, &xhi, &qleft, &qhi); - *pr = one - *ompr; - goto S510; - S530: - S520: - if (!(*status == -1)) goto S560; - if (!qleft) goto S540; - *status = 1; - *bound = 0.0e0; - goto S550; - S540: - *status = 2; - *bound = 1.0e0; - S550:; - } -S560: - return; -#undef atol -#undef tol -#undef zero -#undef inf -#undef one -} -void cdfchi(int *which, double *p, double *q, double *x, double *df, int *status, double *bound) -/********************************************************************** - - void cdfchi(int *which,double *p,double *q,double *x,double *df, - int *status,double *bound) - - Cumulative Distribution Function - CHI-Square distribution - - - Function - - - Calculates any one parameter of the chi-square - distribution given values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next three argument - values is to be calculated from the others. - Legal range: 1..3 - iwhich = 1 : Calculate P and Q from X and DF - iwhich = 2 : Calculate X from P,Q and DF - iwhich = 3 : Calculate DF from P,Q and X - - P <--> The integral from 0 to X of the chi-square - distribution. - Input range: [0, 1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - X <--> Upper limit of integration of the non-central - chi-square distribution. - Input range: [0, +infinity). - Search range: [0,1E100] - - DF <--> Degrees of freedom of the - chi-square distribution. - Input range: (0, +infinity). - Search range: [ 1E-100, 1E100] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - 10 indicates error returned from cumgam. See - references in cdfgam - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.4.19 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce the chisqure - distribution to the incomplete distribution. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - -**********************************************************************/ -{ -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define inf 1.0e100 - static int K1 = 1; - static double K2 = 0.0e0; - static double K4 = 0.5e0; - static double K5 = 5.0e0; - static double fx, cum, ccum, pq, porq; - static unsigned long qhi, qleft, qporq; - static double T3, T6, T7, T8, T9, T10, T11; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 3)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 3.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q <= 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q <= 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 2) goto S130; - /* - X - */ - if (!(*x < 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -4; - return; -S130: -S120: - if (*which == 3) goto S150; - /* - DF - */ - if (!(*df <= 0.0e0)) goto S140; - *bound = 0.0e0; - *status = -5; - return; -S150: -S140: - if (*which == 1) goto S190; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S180; - if (!(pq < 0.0e0)) goto S160; - *bound = 0.0e0; - goto S170; -S160: - *bound = 1.0e0; -S170: - *status = 3; - return; -S190: -S180: - if (*which == 1) goto S220; - /* - Select the minimum of P or Q - */ - qporq = *p <= *q; - if (!qporq) goto S200; - porq = *p; - goto S210; -S200: - porq = *q; -S220: -S210: - /* - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P and Q - */ - *status = 0; - cumchi(x, df, p, q); - if (porq > 1.5e0) { - *status = 10; - return; - } - } - else if (2 == *which) { - /* - Calculating X - */ - *x = 5.0e0; - T3 = inf; - T6 = atol; - T7 = tol; - dstinv(&K2, &T3, &K4, &K4, &K5, &T6, &T7); - *status = 0; - dinvr(status, x, &fx, &qleft, &qhi); - S230: - if (!(*status == 1)) goto S270; - cumchi(x, df, &cum, &ccum); - if (!qporq) goto S240; - fx = cum - *p; - goto S250; - S240: - fx = ccum - *q; - S250: - if (!(fx + porq > 1.5e0)) goto S260; - *status = 10; - return; - S260: - dinvr(status, x, &fx, &qleft, &qhi); - goto S230; - S270: - if (!(*status == -1)) goto S300; - if (!qleft) goto S280; - *status = 1; - *bound = 0.0e0; - goto S290; - S280: - *status = 2; - *bound = inf; - S300: - S290:; - } - else if (3 == *which) { - /* - Calculating DF - */ - *df = 5.0e0; - T8 = zero; - T9 = inf; - T10 = atol; - T11 = tol; - dstinv(&T8, &T9, &K4, &K4, &K5, &T10, &T11); - *status = 0; - dinvr(status, df, &fx, &qleft, &qhi); - S310: - if (!(*status == 1)) goto S350; - cumchi(x, df, &cum, &ccum); - if (!qporq) goto S320; - fx = cum - *p; - goto S330; - S320: - fx = ccum - *q; - S330: - if (!(fx + porq > 1.5e0)) goto S340; - *status = 10; - return; - S340: - dinvr(status, df, &fx, &qleft, &qhi); - goto S310; - S350: - if (!(*status == -1)) goto S380; - if (!qleft) goto S360; - *status = 1; - *bound = zero; - goto S370; - S360: - *status = 2; - *bound = inf; - S370:; - } -S380: - return; -#undef tol -#undef atol -#undef zero -#undef inf -} -void cdfchn(int *which, double *p, double *q, double *x, double *df, double *pnonc, int *status, double *bound) -/********************************************************************** - - void cdfchn(int *which,double *p,double *q,double *x,double *df, - double *pnonc,int *status,double *bound) - - Cumulative Distribution Function - Non-central Chi-Square - - - Function - - - Calculates any one parameter of the non-central chi-square - distribution given values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next three argument - values is to be calculated from the others. - Input range: 1..4 - iwhich = 1 : Calculate P and Q from X and DF - iwhich = 2 : Calculate X from P,DF and PNONC - iwhich = 3 : Calculate DF from P,X and PNONC - iwhich = 3 : Calculate PNONC from P,X and DF - - P <--> The integral from 0 to X of the non-central chi-square - distribution. - Input range: [0, 1-1E-16). - - Q <--> 1-P. - Q is not used by this subroutine and is only included - for similarity with other cdf* routines. - - X <--> Upper limit of integration of the non-central - chi-square distribution. - Input range: [0, +infinity). - Search range: [0,1E100] - - DF <--> Degrees of freedom of the non-central - chi-square distribution. - Input range: (0, +infinity). - Search range: [ 1E-100, 1E100] - - PNONC <--> Non-centrality parameter of the non-central - chi-square distribution. - Input range: [0, +infinity). - Search range: [0,1E4] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.4.25 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to compute the cumulative - distribution function. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - - - WARNING - - The computation time required for this routine is proportional - to the noncentrality parameter (PNONC). Very large values of - this parameter can consume immense computer resources. This is - why the search range is bounded by 10,000. - -**********************************************************************/ -{ -#define tent4 1.0e4 -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define one (1.0e0 - 1.0e-16) -#define inf 1.0e100 - static double K1 = 0.0e0; - static double K3 = 0.5e0; - static double K4 = 5.0e0; - static double fx, cum, ccum; - static unsigned long qhi, qleft; - static double T2, T5, T6, T7, T8, T9, T10, T11, T12, T13; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 4.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > one)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = one; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 2) goto S90; - /* - X - */ - if (!(*x < 0.0e0)) goto S80; - *bound = 0.0e0; - *status = -4; - return; -S90: -S80: - if (*which == 3) goto S110; - /* - DF - */ - if (!(*df <= 0.0e0)) goto S100; - *bound = 0.0e0; - *status = -5; - return; -S110: -S100: - if (*which == 4) goto S130; - /* - PNONC - */ - if (!(*pnonc < 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -6; - return; -S130: -S120: - /* - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P and Q - */ - cumchn(x, df, pnonc, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Calculating X - */ - *x = 5.0e0; - T2 = inf; - T5 = atol; - T6 = tol; - dstinv(&K1, &T2, &K3, &K3, &K4, &T5, &T6); - *status = 0; - dinvr(status, x, &fx, &qleft, &qhi); - S140: - if (!(*status == 1)) goto S150; - cumchn(x, df, pnonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, x, &fx, &qleft, &qhi); - goto S140; - S150: - if (!(*status == -1)) goto S180; - if (!qleft) goto S160; - *status = 1; - *bound = 0.0e0; - goto S170; - S160: - *status = 2; - *bound = inf; - S180: - S170:; - } - else if (3 == *which) { - /* - Calculating DF - */ - *df = 5.0e0; - T7 = zero; - T8 = inf; - T9 = atol; - T10 = tol; - dstinv(&T7, &T8, &K3, &K3, &K4, &T9, &T10); - *status = 0; - dinvr(status, df, &fx, &qleft, &qhi); - S190: - if (!(*status == 1)) goto S200; - cumchn(x, df, pnonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, df, &fx, &qleft, &qhi); - goto S190; - S200: - if (!(*status == -1)) goto S230; - if (!qleft) goto S210; - *status = 1; - *bound = zero; - goto S220; - S210: - *status = 2; - *bound = inf; - S230: - S220:; - } - else if (4 == *which) { - /* - Calculating PNONC - */ - *pnonc = 5.0e0; - T11 = tent4; - T12 = atol; - T13 = tol; - dstinv(&K1, &T11, &K3, &K3, &K4, &T12, &T13); - *status = 0; - dinvr(status, pnonc, &fx, &qleft, &qhi); - S240: - if (!(*status == 1)) goto S250; - cumchn(x, df, pnonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, pnonc, &fx, &qleft, &qhi); - goto S240; - S250: - if (!(*status == -1)) goto S280; - if (!qleft) goto S260; - *status = 1; - *bound = zero; - goto S270; - S260: - *status = 2; - *bound = tent4; - S270:; - } -S280: - return; -#undef tent4 -#undef tol -#undef atol -#undef zero -#undef one -#undef inf -} -void cdff(int *which, double *p, double *q, double *f, double *dfn, double *dfd, int *status, double *bound) -/********************************************************************** - - void cdff(int *which,double *p,double *q,double *f,double *dfn, - double *dfd,int *status,double *bound) - - Cumulative Distribution Function - F distribution - - - Function - - - Calculates any one parameter of the F distribution - given values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next four argument - values is to be calculated from the others. - Legal range: 1..4 - iwhich = 1 : Calculate P and Q from F,DFN and DFD - iwhich = 2 : Calculate F from P,Q,DFN and DFD - iwhich = 3 : Calculate DFN from P,Q,F and DFD - iwhich = 4 : Calculate DFD from P,Q,F and DFN - - P <--> The integral from 0 to F of the f-density. - Input range: [0,1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - F <--> Upper limit of integration of the f-density. - Input range: [0, +infinity). - Search range: [0,1E100] - - DFN < --> Degrees of freedom of the numerator sum of squares. - Input range: (0, +infinity). - Search range: [ 1E-100, 1E100] - - DFD < --> Degrees of freedom of the denominator sum of squares. - Input range: (0, +infinity). - Search range: [ 1E-100, 1E100] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.6.2 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce the computation - of the cumulative distribution function for the F variate to - that of an incomplete beta. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - - WARNING - - The value of the cumulative F distribution is not necessarily - monotone in either degrees of freedom. There thus may be two - values that provide a given CDF value. This routine assumes - monotonicity and will find an arbitrary one of the two values. - -**********************************************************************/ -{ -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define inf 1.0e100 - static int K1 = 1; - static double K2 = 0.0e0; - static double K4 = 0.5e0; - static double K5 = 5.0e0; - static double pq, fx, cum, ccum; - static unsigned long qhi, qleft, qporq; - static double T3, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 4.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q <= 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q <= 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 2) goto S130; - /* - F - */ - if (!(*f < 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -4; - return; -S130: -S120: - if (*which == 3) goto S150; - /* - DFN - */ - if (!(*dfn <= 0.0e0)) goto S140; - *bound = 0.0e0; - *status = -5; - return; -S150: -S140: - if (*which == 4) goto S170; - /* - DFD - */ - if (!(*dfd <= 0.0e0)) goto S160; - *bound = 0.0e0; - *status = -6; - return; -S170: -S160: - if (*which == 1) goto S210; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S200; - if (!(pq < 0.0e0)) goto S180; - *bound = 0.0e0; - goto S190; -S180: - *bound = 1.0e0; -S190: - *status = 3; - return; -S210: -S200: - if (!(*which == 1)) qporq = *p <= *q; - /* - Select the minimum of P or Q - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P - */ - cumf(f, dfn, dfd, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Calculating F - */ - *f = 5.0e0; - T3 = inf; - T6 = atol; - T7 = tol; - dstinv(&K2, &T3, &K4, &K4, &K5, &T6, &T7); - *status = 0; - dinvr(status, f, &fx, &qleft, &qhi); - S220: - if (!(*status == 1)) goto S250; - cumf(f, dfn, dfd, &cum, &ccum); - if (!qporq) goto S230; - fx = cum - *p; - goto S240; - S230: - fx = ccum - *q; - S240: - dinvr(status, f, &fx, &qleft, &qhi); - goto S220; - S250: - if (!(*status == -1)) goto S280; - if (!qleft) goto S260; - *status = 1; - *bound = 0.0e0; - goto S270; - S260: - *status = 2; - *bound = inf; - S280: - S270:; - } - else if (3 == *which) { - /* - Calculating DFN - */ - *dfn = 5.0e0; - T8 = zero; - T9 = inf; - T10 = atol; - T11 = tol; - dstinv(&T8, &T9, &K4, &K4, &K5, &T10, &T11); - *status = 0; - dinvr(status, dfn, &fx, &qleft, &qhi); - S290: - if (!(*status == 1)) goto S320; - cumf(f, dfn, dfd, &cum, &ccum); - if (!qporq) goto S300; - fx = cum - *p; - goto S310; - S300: - fx = ccum - *q; - S310: - dinvr(status, dfn, &fx, &qleft, &qhi); - goto S290; - S320: - if (!(*status == -1)) goto S350; - if (!qleft) goto S330; - *status = 1; - *bound = zero; - goto S340; - S330: - *status = 2; - *bound = inf; - S350: - S340:; - } - else if (4 == *which) { - /* - Calculating DFD - */ - *dfd = 5.0e0; - T12 = zero; - T13 = inf; - T14 = atol; - T15 = tol; - dstinv(&T12, &T13, &K4, &K4, &K5, &T14, &T15); - *status = 0; - dinvr(status, dfd, &fx, &qleft, &qhi); - S360: - if (!(*status == 1)) goto S390; - cumf(f, dfn, dfd, &cum, &ccum); - if (!qporq) goto S370; - fx = cum - *p; - goto S380; - S370: - fx = ccum - *q; - S380: - dinvr(status, dfd, &fx, &qleft, &qhi); - goto S360; - S390: - if (!(*status == -1)) goto S420; - if (!qleft) goto S400; - *status = 1; - *bound = zero; - goto S410; - S400: - *status = 2; - *bound = inf; - S410:; - } -S420: - return; -#undef tol -#undef atol -#undef zero -#undef inf -} -void cdffnc( - int *which, double *p, double *q, double *f, double *dfn, double *dfd, double *phonc, int *status, double *bound) -/********************************************************************** - - void cdffnc(int *which,double *p,double *q,double *f,double *dfn, - double *dfd,double *phonc,int *status,double *bound) - - Cumulative Distribution Function - Non-central F distribution - - - Function - - - Calculates any one parameter of the Non-central F - distribution given values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next five argument - values is to be calculated from the others. - Legal range: 1..5 - iwhich = 1 : Calculate P and Q from F,DFN,DFD and PNONC - iwhich = 2 : Calculate F from P,Q,DFN,DFD and PNONC - iwhich = 3 : Calculate DFN from P,Q,F,DFD and PNONC - iwhich = 4 : Calculate DFD from P,Q,F,DFN and PNONC - iwhich = 5 : Calculate PNONC from P,Q,F,DFN and DFD - - P <--> The integral from 0 to F of the non-central f-density. - Input range: [0,1-1E-16). - - Q <--> 1-P. - Q is not used by this subroutine and is only included - for similarity with other cdf* routines. - - F <--> Upper limit of integration of the non-central f-density. - Input range: [0, +infinity). - Search range: [0,1E100] - - DFN < --> Degrees of freedom of the numerator sum of squares. - Input range: (0, +infinity). - Search range: [ 1E-100, 1E100] - - DFD < --> Degrees of freedom of the denominator sum of squares. - Must be in range: (0, +infinity). - Input range: (0, +infinity). - Search range: [ 1E-100, 1E100] - - PNONC <-> The non-centrality parameter - Input range: [0,infinity) - Search range: [0,1E4] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.6.20 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to compute the cumulative - distribution function. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - - WARNING - - The computation time required for this routine is proportional - to the noncentrality parameter (PNONC). Very large values of - this parameter can consume immense computer resources. This is - why the search range is bounded by 10,000. - - WARNING - - The value of the cumulative noncentral F distribution is not - necessarily monotone in either degrees of freedom. There thus - may be two values that provide a given CDF value. This routine - assumes monotonicity and will find an arbitrary one of the two - values. - -**********************************************************************/ -{ -#define tent4 1.0e4 -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define one (1.0e0 - 1.0e-16) -#define inf 1.0e100 - static double K1 = 0.0e0; - static double K3 = 0.5e0; - static double K4 = 5.0e0; - static double fx, cum, ccum; - static unsigned long qhi, qleft; - static double T2, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 5)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 5.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > one)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = one; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 2) goto S90; - /* - F - */ - if (!(*f < 0.0e0)) goto S80; - *bound = 0.0e0; - *status = -4; - return; -S90: -S80: - if (*which == 3) goto S110; - /* - DFN - */ - if (!(*dfn <= 0.0e0)) goto S100; - *bound = 0.0e0; - *status = -5; - return; -S110: -S100: - if (*which == 4) goto S130; - /* - DFD - */ - if (!(*dfd <= 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -6; - return; -S130: -S120: - if (*which == 5) goto S150; - /* - PHONC - */ - if (!(*phonc < 0.0e0)) goto S140; - *bound = 0.0e0; - *status = -7; - return; -S150: -S140: - /* - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P - */ - cumfnc(f, dfn, dfd, phonc, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Calculating F - */ - *f = 5.0e0; - T2 = inf; - T5 = atol; - T6 = tol; - dstinv(&K1, &T2, &K3, &K3, &K4, &T5, &T6); - *status = 0; - dinvr(status, f, &fx, &qleft, &qhi); - S160: - if (!(*status == 1)) goto S170; - cumfnc(f, dfn, dfd, phonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, f, &fx, &qleft, &qhi); - goto S160; - S170: - if (!(*status == -1)) goto S200; - if (!qleft) goto S180; - *status = 1; - *bound = 0.0e0; - goto S190; - S180: - *status = 2; - *bound = inf; - S200: - S190:; - } - else if (3 == *which) { - /* - Calculating DFN - */ - *dfn = 5.0e0; - T7 = zero; - T8 = inf; - T9 = atol; - T10 = tol; - dstinv(&T7, &T8, &K3, &K3, &K4, &T9, &T10); - *status = 0; - dinvr(status, dfn, &fx, &qleft, &qhi); - S210: - if (!(*status == 1)) goto S220; - cumfnc(f, dfn, dfd, phonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, dfn, &fx, &qleft, &qhi); - goto S210; - S220: - if (!(*status == -1)) goto S250; - if (!qleft) goto S230; - *status = 1; - *bound = zero; - goto S240; - S230: - *status = 2; - *bound = inf; - S250: - S240:; - } - else if (4 == *which) { - /* - Calculating DFD - */ - *dfd = 5.0e0; - T11 = zero; - T12 = inf; - T13 = atol; - T14 = tol; - dstinv(&T11, &T12, &K3, &K3, &K4, &T13, &T14); - *status = 0; - dinvr(status, dfd, &fx, &qleft, &qhi); - S260: - if (!(*status == 1)) goto S270; - cumfnc(f, dfn, dfd, phonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, dfd, &fx, &qleft, &qhi); - goto S260; - S270: - if (!(*status == -1)) goto S300; - if (!qleft) goto S280; - *status = 1; - *bound = zero; - goto S290; - S280: - *status = 2; - *bound = inf; - S300: - S290:; - } - else if (5 == *which) { - /* - Calculating PHONC - */ - *phonc = 5.0e0; - T15 = tent4; - T16 = atol; - T17 = tol; - dstinv(&K1, &T15, &K3, &K3, &K4, &T16, &T17); - *status = 0; - dinvr(status, phonc, &fx, &qleft, &qhi); - S310: - if (!(*status == 1)) goto S320; - cumfnc(f, dfn, dfd, phonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, phonc, &fx, &qleft, &qhi); - goto S310; - S320: - if (!(*status == -1)) goto S350; - if (!qleft) goto S330; - *status = 1; - *bound = 0.0e0; - goto S340; - S330: - *status = 2; - *bound = tent4; - S340:; - } -S350: - return; -#undef tent4 -#undef tol -#undef atol -#undef zero -#undef one -#undef inf -} -void cdfgam(int *which, double *p, double *q, double *x, double *shape, double *scale, int *status, double *bound) -/********************************************************************** - - void cdfgam(int *which,double *p,double *q,double *x,double *shape, - double *scale,int *status,double *bound) - - Cumulative Distribution Function - GAMma Distribution - - - Function - - - Calculates any one parameter of the gamma - distribution given values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next four argument - values is to be calculated from the others. - Legal range: 1..4 - iwhich = 1 : Calculate P and Q from X,SHAPE and SCALE - iwhich = 2 : Calculate X from P,Q,SHAPE and SCALE - iwhich = 3 : Calculate SHAPE from P,Q,X and SCALE - iwhich = 4 : Calculate SCALE from P,Q,X and SHAPE - - P <--> The integral from 0 to X of the gamma density. - Input range: [0,1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - X <--> The upper limit of integration of the gamma density. - Input range: [0, +infinity). - Search range: [0,1E100] - - SHAPE <--> The shape parameter of the gamma density. - Input range: (0, +infinity). - Search range: [1E-100,1E100] - - SCALE <--> The scale parameter of the gamma density. - Input range: (0, +infinity). - Search range: (1E-100,1E100] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - 10 if the gamma or inverse gamma routine cannot - compute the answer. Usually happens only for - X and SHAPE very large (gt 1E10 or more) - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Cumulative distribution function (P) is calculated directly by - the code associated with: - - DiDinato, A. R. and Morris, A. H. Computation of the incomplete - gamma function ratios and their inverse. ACM Trans. Math. - Softw. 12 (1986), 377-393. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - - - Note - - - - The gamma density is proportional to - T**(SHAPE - 1) * EXP(- SCALE * T) - -**********************************************************************/ -{ -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define inf 1.0e100 - static int K1 = 1; - static double K5 = 0.5e0; - static double K6 = 5.0e0; - static double xx, fx, xscale, cum, ccum, pq, porq; - static int ierr; - static unsigned long qhi, qleft, qporq; - static double T2, T3, T4, T7, T8, T9; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 4.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q <= 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q <= 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 2) goto S130; - /* - X - */ - if (!(*x < 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -4; - return; -S130: -S120: - if (*which == 3) goto S150; - /* - SHAPE - */ - if (!(*shape <= 0.0e0)) goto S140; - *bound = 0.0e0; - *status = -5; - return; -S150: -S140: - if (*which == 4) goto S170; - /* - SCALE - */ - if (!(*scale <= 0.0e0)) goto S160; - *bound = 0.0e0; - *status = -6; - return; -S170: -S160: - if (*which == 1) goto S210; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S200; - if (!(pq < 0.0e0)) goto S180; - *bound = 0.0e0; - goto S190; -S180: - *bound = 1.0e0; -S190: - *status = 3; - return; -S210: -S200: - if (*which == 1) goto S240; - /* - Select the minimum of P or Q - */ - qporq = *p <= *q; - if (!qporq) goto S220; - porq = *p; - goto S230; -S220: - porq = *q; -S240: -S230: - /* - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P - */ - *status = 0; - xscale = *x * *scale; - cumgam(&xscale, shape, p, q); - if (porq > 1.5e0) *status = 10; - } - else if (2 == *which) { - /* - Computing X - */ - T2 = -1.0e0; - gaminv(shape, &xx, &T2, p, q, &ierr); - if (ierr < 0.0e0) { - *status = 10; - return; - } - else { - *x = xx / *scale; - *status = 0; - } - } - else if (3 == *which) { - /* - Computing SHAPE - */ - *shape = 5.0e0; - xscale = *x * *scale; - T3 = zero; - T4 = inf; - T7 = atol; - T8 = tol; - dstinv(&T3, &T4, &K5, &K5, &K6, &T7, &T8); - *status = 0; - dinvr(status, shape, &fx, &qleft, &qhi); - S250: - if (!(*status == 1)) goto S290; - cumgam(&xscale, shape, &cum, &ccum); - if (!qporq) goto S260; - fx = cum - *p; - goto S270; - S260: - fx = ccum - *q; - S270: - if (!((qporq && cum > 1.5e0) || (!qporq && ccum > 1.5e0))) goto S280; - *status = 10; - return; - S280: - dinvr(status, shape, &fx, &qleft, &qhi); - goto S250; - S290: - if (!(*status == -1)) goto S320; - if (!qleft) goto S300; - *status = 1; - *bound = zero; - goto S310; - S300: - *status = 2; - *bound = inf; - S320: - S310:; - } - else if (4 == *which) { - /* - Computing SCALE - */ - T9 = -1.0e0; - gaminv(shape, &xx, &T9, p, q, &ierr); - if (ierr < 0.0e0) { - *status = 10; - return; - } - else { - *scale = xx / *x; - *status = 0; - } - } - return; -#undef tol -#undef atol -#undef zero -#undef inf -} -void cdfnbn( - int *which, double *p, double *q, double *s, double *xn, double *pr, double *ompr, int *status, double *bound) -/********************************************************************** - - void cdfnbn(int *which,double *p,double *q,double *s,double *xn, - double *pr,double *ompr,int *status,double *bound) - - Cumulative Distribution Function - Negative BiNomial distribution - - - Function - - - Calculates any one parameter of the negative binomial - distribution given values for the others. - - The cumulative negative binomial distribution returns the - probability that there will be F or fewer failures before the - XNth success in binomial trials each of which has probability of - success PR. - - The individual term of the negative binomial is the probability of - S failures before XN successes and is - Choose( S, XN+S-1 ) * PR^(XN) * (1-PR)^S - - - Arguments - - - WHICH --> Integer indicating which of the next four argument - values is to be calculated from the others. - Legal range: 1..4 - iwhich = 1 : Calculate P and Q from S,XN,PR and OMPR - iwhich = 2 : Calculate S from P,Q,XN,PR and OMPR - iwhich = 3 : Calculate XN from P,Q,S,PR and OMPR - iwhich = 4 : Calculate PR and OMPR from P,Q,S and XN - - P <--> The cumulation from 0 to S of the negative - binomial distribution. - Input range: [0,1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - S <--> The upper limit of cumulation of the binomial distribution. - There are F or fewer failures before the XNth success. - Input range: [0, +infinity). - Search range: [0, 1E100] - - XN <--> The number of successes. - Input range: [0, +infinity). - Search range: [0, 1E100] - - PR <--> The probability of success in each binomial trial. - Input range: [0,1]. - Search range: [0,1]. - - OMPR <--> 1-PR - Input range: [0,1]. - Search range: [0,1] - PR + OMPR = 1.0 - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - 4 if PR + OMPR .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.5.26 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce calculation of - the cumulative distribution function to that of an incomplete - beta. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - -**********************************************************************/ -{ -#define tol 1.0e-8 -#define atol 1.0e-50 -#define inf 1.0e100 -#define one 1.0e0 - static int K1 = 1; - static double K2 = 0.0e0; - static double K4 = 0.5e0; - static double K5 = 5.0e0; - static double K11 = 1.0e0; - static double fx, xhi, xlo, pq, prompr, cum, ccum; - static unsigned long qhi, qleft, qporq; - static double T3, T6, T7, T8, T9, T10, T12, T13; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 4.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q <= 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q <= 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 2) goto S130; - /* - S - */ - if (!(*s < 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -4; - return; -S130: -S120: - if (*which == 3) goto S150; - /* - XN - */ - if (!(*xn < 0.0e0)) goto S140; - *bound = 0.0e0; - *status = -5; - return; -S150: -S140: - if (*which == 4) goto S190; - /* - PR - */ - if (!(*pr < 0.0e0 || *pr > 1.0e0)) goto S180; - if (!(*pr < 0.0e0)) goto S160; - *bound = 0.0e0; - goto S170; -S160: - *bound = 1.0e0; -S170: - *status = -6; - return; -S190: -S180: - if (*which == 4) goto S230; - /* - OMPR - */ - if (!(*ompr < 0.0e0 || *ompr > 1.0e0)) goto S220; - if (!(*ompr < 0.0e0)) goto S200; - *bound = 0.0e0; - goto S210; -S200: - *bound = 1.0e0; -S210: - *status = -7; - return; -S230: -S220: - if (*which == 1) goto S270; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S260; - if (!(pq < 0.0e0)) goto S240; - *bound = 0.0e0; - goto S250; -S240: - *bound = 1.0e0; -S250: - *status = 3; - return; -S270: -S260: - if (*which == 4) goto S310; - /* - PR + OMPR - */ - prompr = *pr + *ompr; - if (!(fabs(prompr - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S300; - if (!(prompr < 0.0e0)) goto S280; - *bound = 0.0e0; - goto S290; -S280: - *bound = 1.0e0; -S290: - *status = 4; - return; -S310: -S300: - if (!(*which == 1)) qporq = *p <= *q; - /* - Select the minimum of P or Q - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P - */ - cumnbn(s, xn, pr, ompr, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Calculating S - */ - *s = 5.0e0; - T3 = inf; - T6 = atol; - T7 = tol; - dstinv(&K2, &T3, &K4, &K4, &K5, &T6, &T7); - *status = 0; - dinvr(status, s, &fx, &qleft, &qhi); - S320: - if (!(*status == 1)) goto S350; - cumnbn(s, xn, pr, ompr, &cum, &ccum); - if (!qporq) goto S330; - fx = cum - *p; - goto S340; - S330: - fx = ccum - *q; - S340: - dinvr(status, s, &fx, &qleft, &qhi); - goto S320; - S350: - if (!(*status == -1)) goto S380; - if (!qleft) goto S360; - *status = 1; - *bound = 0.0e0; - goto S370; - S360: - *status = 2; - *bound = inf; - S380: - S370:; - } - else if (3 == *which) { - /* - Calculating XN - */ - *xn = 5.0e0; - T8 = inf; - T9 = atol; - T10 = tol; - dstinv(&K2, &T8, &K4, &K4, &K5, &T9, &T10); - *status = 0; - dinvr(status, xn, &fx, &qleft, &qhi); - S390: - if (!(*status == 1)) goto S420; - cumnbn(s, xn, pr, ompr, &cum, &ccum); - if (!qporq) goto S400; - fx = cum - *p; - goto S410; - S400: - fx = ccum - *q; - S410: - dinvr(status, xn, &fx, &qleft, &qhi); - goto S390; - S420: - if (!(*status == -1)) goto S450; - if (!qleft) goto S430; - *status = 1; - *bound = 0.0e0; - goto S440; - S430: - *status = 2; - *bound = inf; - S450: - S440:; - } - else if (4 == *which) { - /* - Calculating PR and OMPR - */ - T12 = atol; - T13 = tol; - dstzr(&K2, &K11, &T12, &T13); - if (!qporq) goto S480; - *status = 0; - dzror(status, pr, &fx, &xlo, &xhi, &qleft, &qhi); - *ompr = one - *pr; - S460: - if (!(*status == 1)) goto S470; - cumnbn(s, xn, pr, ompr, &cum, &ccum); - fx = cum - *p; - dzror(status, pr, &fx, &xlo, &xhi, &qleft, &qhi); - *ompr = one - *pr; - goto S460; - S470: - goto S510; - S480: - *status = 0; - dzror(status, ompr, &fx, &xlo, &xhi, &qleft, &qhi); - *pr = one - *ompr; - S490: - if (!(*status == 1)) goto S500; - cumnbn(s, xn, pr, ompr, &cum, &ccum); - fx = ccum - *q; - dzror(status, ompr, &fx, &xlo, &xhi, &qleft, &qhi); - *pr = one - *ompr; - goto S490; - S510: - S500: - if (!(*status == -1)) goto S540; - if (!qleft) goto S520; - *status = 1; - *bound = 0.0e0; - goto S530; - S520: - *status = 2; - *bound = 1.0e0; - S530:; - } -S540: - return; -#undef tol -#undef atol -#undef inf -#undef one -} -void cdfnor(int *which, double *p, double *q, double *x, double *mean, double *sd, int *status, double *bound) -/********************************************************************** - - void cdfnor(int *which,double *p,double *q,double *x,double *mean, - double *sd,int *status,double *bound) - - Cumulative Distribution Function - NORmal distribution - - - Function - - - Calculates any one parameter of the normal - distribution given values for the others. - - - Arguments - - - WHICH --> Integer indicating which of the next parameter - values is to be calculated using values of the others. - Legal range: 1..4 - iwhich = 1 : Calculate P and Q from X,MEAN and SD - iwhich = 2 : Calculate X from P,Q,MEAN and SD - iwhich = 3 : Calculate MEAN from P,Q,X and SD - iwhich = 4 : Calculate SD from P,Q,X and MEAN - - P <--> The integral from -infinity to X of the normal density. - Input range: (0,1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - X < --> Upper limit of integration of the normal-density. - Input range: ( -infinity, +infinity) - - MEAN <--> The mean of the normal density. - Input range: (-infinity, +infinity) - - SD <--> Standard Deviation of the normal density. - Input range: (0, +infinity). - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - - - A slightly modified version of ANORM from - - Cody, W.D. (1993). "ALGORITHM 715: SPECFUN - A Portabel FORTRAN - Package of Special Function Routines and Test Drivers" - acm Transactions on Mathematical Software. 19, 22-32. - - is used to calulate the cumulative standard normal distribution. - - The rational functions from pages 90-95 of Kennedy and Gentle, - Statistical Computing, Marcel Dekker, NY, 1980 are used as - starting values to Newton's Iterations which compute the inverse - standard normal. Therefore no searches are necessary for any - parameter. - - For X < -15, the asymptotic expansion for the normal is used as - the starting value in finding the inverse standard normal. - This is formula 26.2.12 of Abramowitz and Stegun. - - - Note - - - The normal density is proportional to - exp( - 0.5 * (( X - MEAN)/SD)**2) - -**********************************************************************/ -{ - static int K1 = 1; - static double z, pq; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - *status = 0; - if (!(*which < 1 || *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 4.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p <= 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p <= 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q <= 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q <= 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 1) goto S150; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S140; - if (!(pq < 0.0e0)) goto S120; - *bound = 0.0e0; - goto S130; -S120: - *bound = 1.0e0; -S130: - *status = 3; - return; -S150: -S140: - if (*which == 4) goto S170; - /* - SD - */ - if (!(*sd <= 0.0e0)) goto S160; - *bound = 0.0e0; - *status = -6; - return; -S170: -S160: - /* - Calculate ANSWERS - */ - if (1 == *which) { - /* - Computing P - */ - z = (*x - *mean) / *sd; - cumnor(&z, p, q); - } - else if (2 == *which) { - /* - Computing X - */ - z = dinvnr(p, q); - *x = *sd * z + *mean; - } - else if (3 == *which) { - /* - Computing the MEAN - */ - z = dinvnr(p, q); - *mean = *x - *sd * z; - } - else if (4 == *which) { - /* - Computing SD - */ - z = dinvnr(p, q); - *sd = (*x - *mean) / z; - } - return; -} -void cdfpoi(int *which, double *p, double *q, double *s, double *xlam, int *status, double *bound) -/********************************************************************** - - void cdfpoi(int *which,double *p,double *q,double *s,double *xlam, - int *status,double *bound) - - Cumulative Distribution Function - POIsson distribution - - - Function - - - Calculates any one parameter of the Poisson - distribution given values for the others. - - - Arguments - - - WHICH --> Integer indicating which argument - value is to be calculated from the others. - Legal range: 1..3 - iwhich = 1 : Calculate P and Q from S and XLAM - iwhich = 2 : Calculate A from P,Q and XLAM - iwhich = 3 : Calculate XLAM from P,Q and S - - P <--> The cumulation from 0 to S of the poisson density. - Input range: [0,1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - S <--> Upper limit of cumulation of the Poisson. - Input range: [0, +infinity). - Search range: [0,1E100] - - XLAM <--> Mean of the Poisson distribution. - Input range: [0, +infinity). - Search range: [0,1E100] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.4.21 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce the computation - of the cumulative distribution function to that of computing a - chi-square, hence an incomplete gamma function. - - Cumulative distribution function (P) is calculated directly. - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - -**********************************************************************/ -{ -#define tol 1.0e-8 -#define atol 1.0e-50 -#define inf 1.0e100 - static int K1 = 1; - static double K2 = 0.0e0; - static double K4 = 0.5e0; - static double K5 = 5.0e0; - static double fx, cum, ccum, pq; - static unsigned long qhi, qleft, qporq; - static double T3, T6, T7, T8, T9, T10; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 3)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 3.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p < 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q <= 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q <= 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 2) goto S130; - /* - S - */ - if (!(*s < 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -4; - return; -S130: -S120: - if (*which == 3) goto S150; - /* - XLAM - */ - if (!(*xlam < 0.0e0)) goto S140; - *bound = 0.0e0; - *status = -5; - return; -S150: -S140: - if (*which == 1) goto S190; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S180; - if (!(pq < 0.0e0)) goto S160; - *bound = 0.0e0; - goto S170; -S160: - *bound = 1.0e0; -S170: - *status = 3; - return; -S190: -S180: - if (!(*which == 1)) qporq = *p <= *q; - /* - Select the minimum of P or Q - Calculate ANSWERS - */ - if (1 == *which) { - /* - Calculating P - */ - cumpoi(s, xlam, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Calculating S - */ - *s = 5.0e0; - T3 = inf; - T6 = atol; - T7 = tol; - dstinv(&K2, &T3, &K4, &K4, &K5, &T6, &T7); - *status = 0; - dinvr(status, s, &fx, &qleft, &qhi); - S200: - if (!(*status == 1)) goto S230; - cumpoi(s, xlam, &cum, &ccum); - if (!qporq) goto S210; - fx = cum - *p; - goto S220; - S210: - fx = ccum - *q; - S220: - dinvr(status, s, &fx, &qleft, &qhi); - goto S200; - S230: - if (!(*status == -1)) goto S260; - if (!qleft) goto S240; - *status = 1; - *bound = 0.0e0; - goto S250; - S240: - *status = 2; - *bound = inf; - S260: - S250:; - } - else if (3 == *which) { - /* - Calculating XLAM - */ - *xlam = 5.0e0; - T8 = inf; - T9 = atol; - T10 = tol; - dstinv(&K2, &T8, &K4, &K4, &K5, &T9, &T10); - *status = 0; - dinvr(status, xlam, &fx, &qleft, &qhi); - S270: - if (!(*status == 1)) goto S300; - cumpoi(s, xlam, &cum, &ccum); - if (!qporq) goto S280; - fx = cum - *p; - goto S290; - S280: - fx = ccum - *q; - S290: - dinvr(status, xlam, &fx, &qleft, &qhi); - goto S270; - S300: - if (!(*status == -1)) goto S330; - if (!qleft) goto S310; - *status = 1; - *bound = 0.0e0; - goto S320; - S310: - *status = 2; - *bound = inf; - S320:; - } -S330: - return; -#undef tol -#undef atol -#undef inf -} -void cdft(int *which, double *p, double *q, double *t, double *df, int *status, double *bound) -/********************************************************************** - - void cdft(int *which,double *p,double *q,double *t,double *df, - int *status,double *bound) - - Cumulative Distribution Function - T distribution - - - Function - - - Calculates any one parameter of the t distribution given - values for the others. - - - Arguments - - - WHICH --> Integer indicating which argument - values is to be calculated from the others. - Legal range: 1..3 - iwhich = 1 : Calculate P and Q from T and DF - iwhich = 2 : Calculate T from P,Q and DF - iwhich = 3 : Calculate DF from P,Q and T - - P <--> The integral from -infinity to t of the t-density. - Input range: (0,1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - T <--> Upper limit of integration of the t-density. - Input range: ( -infinity, +infinity). - Search range: [ -1E100, 1E100 ] - - DF <--> Degrees of freedom of the t-distribution. - Input range: (0 , +infinity). - Search range: [1e-100, 1E10] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - - Method - - - Formula 26.5.27 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce the computation - of the cumulative distribution function to that of an incomplete - beta. - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - -**********************************************************************/ -{ -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define inf 1.0e100 -#define rtinf 1.0e100 -#define maxdf 1.0e10 - static int K1 = 1; - static double K4 = 0.5e0; - static double K5 = 5.0e0; - static double fx, cum, ccum, pq; - static unsigned long qhi, qleft, qporq; - static double T2, T3, T6, T7, T8, T9, T10, T11; - /* - .. - .. Executable Statements .. - */ - /* - Check arguments - */ - if (!(*which < 1 || *which > 3)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 3.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - /* - P - */ - if (!(*p <= 0.0e0 || *p > 1.0e0)) goto S60; - if (!(*p <= 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = 1.0e0; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 1) goto S110; - /* - Q - */ - if (!(*q <= 0.0e0 || *q > 1.0e0)) goto S100; - if (!(*q <= 0.0e0)) goto S80; - *bound = 0.0e0; - goto S90; -S80: - *bound = 1.0e0; -S90: - *status = -3; - return; -S110: -S100: - if (*which == 3) goto S130; - /* - DF - */ - if (!(*df <= 0.0e0)) goto S120; - *bound = 0.0e0; - *status = -5; - return; -S130: -S120: - if (*which == 1) goto S170; - /* - P + Q - */ - pq = *p + *q; - if (!(fabs(pq - 0.5e0 - 0.5e0) > 3.0e0 * spmpar(&K1))) goto S160; - if (!(pq < 0.0e0)) goto S140; - *bound = 0.0e0; - goto S150; -S140: - *bound = 1.0e0; -S150: - *status = 3; - return; -S170: -S160: - if (!(*which == 1)) qporq = *p <= *q; - /* - Select the minimum of P or Q - Calculate ANSWERS - */ - if (1 == *which) { - /* - Computing P and Q - */ - cumt(t, df, p, q); - *status = 0; - } - else if (2 == *which) { - /* - Computing T - .. Get initial approximation for T - */ - *t = dt1(p, q, df); - T2 = -rtinf; - T3 = rtinf; - T6 = atol; - T7 = tol; - dstinv(&T2, &T3, &K4, &K4, &K5, &T6, &T7); - *status = 0; - dinvr(status, t, &fx, &qleft, &qhi); - S180: - if (!(*status == 1)) goto S210; - cumt(t, df, &cum, &ccum); - if (!qporq) goto S190; - fx = cum - *p; - goto S200; - S190: - fx = ccum - *q; - S200: - dinvr(status, t, &fx, &qleft, &qhi); - goto S180; - S210: - if (!(*status == -1)) goto S240; - if (!qleft) goto S220; - *status = 1; - *bound = -rtinf; - goto S230; - S220: - *status = 2; - *bound = rtinf; - S240: - S230:; - } - else if (3 == *which) { - /* - Computing DF - */ - *df = 5.0e0; - T8 = zero; - T9 = maxdf; - T10 = atol; - T11 = tol; - dstinv(&T8, &T9, &K4, &K4, &K5, &T10, &T11); - *status = 0; - dinvr(status, df, &fx, &qleft, &qhi); - S250: - if (!(*status == 1)) goto S280; - cumt(t, df, &cum, &ccum); - if (!qporq) goto S260; - fx = cum - *p; - goto S270; - S260: - fx = ccum - *q; - S270: - dinvr(status, df, &fx, &qleft, &qhi); - goto S250; - S280: - if (!(*status == -1)) goto S310; - if (!qleft) goto S290; - *status = 1; - *bound = zero; - goto S300; - S290: - *status = 2; - *bound = maxdf; - S300:; - } -S310: - return; -#undef tol -#undef atol -#undef zero -#undef inf -#undef rtinf -#undef maxdf -} -void cdftnc(int *which, double *p, double *q, double *t, double *df, double *pnonc, int *status, double *bound) -/********************************************************************** - - void cdftnc(int *which,double *p,double *q,double *t,double *df, - double *pnonc,int *status,double *bound) - - Cumulative Distribution Function - Non-Central T distribution - - Function - - Calculates any one parameter of the noncentral t distribution give - values for the others. - - Arguments - - WHICH --> Integer indicating which argument - values is to be calculated from the others. - Legal range: 1..3 - iwhich = 1 : Calculate P and Q from T,DF,PNONC - iwhich = 2 : Calculate T from P,Q,DF,PNONC - iwhich = 3 : Calculate DF from P,Q,T - iwhich = 4 : Calculate PNONC from P,Q,DF,T - - P <--> The integral from -infinity to t of the noncentral t-den - Input range: (0,1]. - - Q <--> 1-P. - Input range: (0, 1]. - P + Q = 1.0. - - T <--> Upper limit of integration of the noncentral t-density. - Input range: ( -infinity, +infinity). - Search range: [ -1E100, 1E100 ] - - DF <--> Degrees of freedom of the noncentral t-distribution. - Input range: (0 , +infinity). - Search range: [1e-100, 1E10] - - PNONC <--> Noncentrality parameter of the noncentral t-distributio - Input range: [-infinity , +infinity). - Search range: [-1e4, 1E4] - - STATUS <-- 0 if calculation completed correctly - -I if input parameter number I is out of range - 1 if answer appears to be lower than lowest - search bound - 2 if answer appears to be higher than greatest - search bound - 3 if P + Q .ne. 1 - - BOUND <-- Undefined if STATUS is 0 - - Bound exceeded by parameter number I if STATUS - is negative. - - Lower search bound if STATUS is 1. - - Upper search bound if STATUS is 2. - - Method - - Upper tail of the cumulative noncentral t is calculated usin - formulae from page 532 of Johnson, Kotz, Balakrishnan, Coninuou - Univariate Distributions, Vol 2, 2nd Edition. Wiley (1995) - - Computation of other parameters involve a seach for a value that - produces the desired value of P. The search relies on the - monotinicity of P with the other parameter. - -**********************************************************************/ -{ -#define tent4 1.0e4 -#define tol 1.0e-8 -#define atol 1.0e-50 -#define zero 1.0e-100 -#define one (1.0e0 - 1.0e-16) -#define inf 1.0e100 - static double K3 = 0.5e0; - static double K4 = 5.0e0; - static double ccum, cum, fx; - static unsigned long qhi, qleft; - static double T1, T2, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14; - /* - .. - .. Executable Statements .. - */ - if (!(*which < 1 || *which > 4)) goto S30; - if (!(*which < 1)) goto S10; - *bound = 1.0e0; - goto S20; -S10: - *bound = 5.0e0; -S20: - *status = -1; - return; -S30: - if (*which == 1) goto S70; - if (!(*p < 0.0e0 || *p > one)) goto S60; - if (!(*p < 0.0e0)) goto S40; - *bound = 0.0e0; - goto S50; -S40: - *bound = one; -S50: - *status = -2; - return; -S70: -S60: - if (*which == 3) goto S90; - if (!(*df <= 0.0e0)) goto S80; - *bound = 0.0e0; - *status = -5; - return; -S90: -S80: - if (*which == 4) goto S100; -S100: - if (1 == *which) { - cumtnc(t, df, pnonc, p, q); - *status = 0; - } - else if (2 == *which) { - *t = 5.0e0; - T1 = -inf; - T2 = inf; - T5 = atol; - T6 = tol; - dstinv(&T1, &T2, &K3, &K3, &K4, &T5, &T6); - *status = 0; - dinvr(status, t, &fx, &qleft, &qhi); - S110: - if (!(*status == 1)) goto S120; - cumtnc(t, df, pnonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, t, &fx, &qleft, &qhi); - goto S110; - S120: - if (!(*status == -1)) goto S150; - if (!qleft) goto S130; - *status = 1; - *bound = -inf; - goto S140; - S130: - *status = 2; - *bound = inf; - S150: - S140:; - } - else if (3 == *which) { - *df = 5.0e0; - T7 = zero; - T8 = tent4; - T9 = atol; - T10 = tol; - dstinv(&T7, &T8, &K3, &K3, &K4, &T9, &T10); - *status = 0; - dinvr(status, df, &fx, &qleft, &qhi); - S160: - if (!(*status == 1)) goto S170; - cumtnc(t, df, pnonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, df, &fx, &qleft, &qhi); - goto S160; - S170: - if (!(*status == -1)) goto S200; - if (!qleft) goto S180; - *status = 1; - *bound = zero; - goto S190; - S180: - *status = 2; - *bound = inf; - S200: - S190:; - } - else if (4 == *which) { - *pnonc = 5.0e0; - T11 = -tent4; - T12 = tent4; - T13 = atol; - T14 = tol; - dstinv(&T11, &T12, &K3, &K3, &K4, &T13, &T14); - *status = 0; - dinvr(status, pnonc, &fx, &qleft, &qhi); - S210: - if (!(*status == 1)) goto S220; - cumtnc(t, df, pnonc, &cum, &ccum); - fx = cum - *p; - dinvr(status, pnonc, &fx, &qleft, &qhi); - goto S210; - S220: - if (!(*status == -1)) goto S250; - if (!qleft) goto S230; - *status = 1; - *bound = 0.0e0; - goto S240; - S230: - *status = 2; - *bound = tent4; - S240:; - } -S250: - return; -#undef tent4 -#undef tol -#undef atol -#undef zero -#undef one -#undef inf -} -void cumbet(double *x, double *y, double *a, double *b, double *cum, double *ccum) -/* -********************************************************************** - - void cumbet(double *x,double *y,double *a,double *b,double *cum, - double *ccum) - - Double precision cUMulative incomplete BETa distribution - - - Function - - - Calculates the cdf to X of the incomplete beta distribution - with parameters a and b. This is the integral from 0 to x - of (1/B(a,b))*f(t)) where f(t) = t**(a-1) * (1-t)**(b-1) - - - Arguments - - - X --> Upper limit of integration. - X is DOUBLE PRECISION - - Y --> 1 - X. - Y is DOUBLE PRECISION - - A --> First parameter of the beta distribution. - A is DOUBLE PRECISION - - B --> Second parameter of the beta distribution. - B is DOUBLE PRECISION - - CUM <-- Cumulative incomplete beta distribution. - CUM is DOUBLE PRECISION - - CCUM <-- Compliment of Cumulative incomplete beta distribution. - CCUM is DOUBLE PRECISION - - - Method - - - Calls the routine BRATIO. - - References - - Didonato, Armido R. and Morris, Alfred H. Jr. (1992) Algorithim - 708 Significant Digit Computation of the Incomplete Beta Function - Ratios. ACM ToMS, Vol.18, No. 3, Sept. 1992, 360-373. - -********************************************************************** -*/ -{ - static int ierr; - /* - .. - .. Executable Statements .. - */ - if (!(*x <= 0.0e0)) goto S10; - *cum = 0.0e0; - *ccum = 1.0e0; - return; -S10: - if (!(*y <= 0.0e0)) goto S20; - *cum = 1.0e0; - *ccum = 0.0e0; - return; -S20: - bratio(a, b, x, y, cum, ccum, &ierr); - /* - Call bratio routine - */ - return; -} -void cumbin(double *s, double *xn, double *pr, double *ompr, double *cum, double *ccum) -/* -********************************************************************** - - void cumbin(double *s,double *xn,double *pr,double *ompr, - double *cum,double *ccum) - - CUmulative BINomial distribution - - - Function - - - Returns the probability of 0 to S successes in XN binomial - trials, each of which has a probability of success, PBIN. - - - Arguments - - - S --> The upper limit of cumulation of the binomial distribution. - S is DOUBLE PRECISION - - XN --> The number of binomial trials. - XN is DOUBLE PRECISIO - - PBIN --> The probability of success in each binomial trial. - PBIN is DOUBLE PRECIS - - OMPR --> 1 - PBIN - OMPR is DOUBLE PRECIS - - CUM <-- Cumulative binomial distribution. - CUM is DOUBLE PRECISI - - CCUM <-- Compliment of Cumulative binomial distribution. - CCUM is DOUBLE PRECIS - - - Method - - - Formula 26.5.24 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce the binomial - distribution to the cumulative beta distribution. - -********************************************************************** -*/ -{ - static double T1, T2; - /* - .. - .. Executable Statements .. - */ - if (!(*s < *xn)) goto S10; - T1 = *s + 1.0e0; - T2 = *xn - *s; - cumbet(pr, ompr, &T1, &T2, ccum, cum); - goto S20; -S10: - *cum = 1.0e0; - *ccum = 0.0e0; -S20: - return; -} -void cumchi(double *x, double *df, double *cum, double *ccum) -/* -********************************************************************** - - void cumchi(double *x,double *df,double *cum,double *ccum) - CUMulative of the CHi-square distribution - - - Function - - - Calculates the cumulative chi-square distribution. - - - Arguments - - - X --> Upper limit of integration of the - chi-square distribution. - X is DOUBLE PRECISION - - DF --> Degrees of freedom of the - chi-square distribution. - DF is DOUBLE PRECISION - - CUM <-- Cumulative chi-square distribution. - CUM is DOUBLE PRECISIO - - CCUM <-- Compliment of Cumulative chi-square distribution. - CCUM is DOUBLE PRECISI - - - Method - - - Calls incomplete gamma function (CUMGAM) - -********************************************************************** -*/ -{ - static double a, xx; - /* - .. - .. Executable Statements .. - */ - a = *df * 0.5e0; - xx = *x * 0.5e0; - cumgam(&xx, &a, cum, ccum); - return; -} -void cumchn(double *x, double *df, double *pnonc, double *cum, double *ccum) -/********************************************************************** - - void cumchn(double *x,double *df,double *pnonc,double *cum, - double *ccum) - - CUMulative of the Non-central CHi-square distribution - - Function - - Calculates the cumulative non-central chi-square - distribution, i.e., the probability that a random variable - which follows the non-central chi-square distribution, with - non-centrality parameter PNONC and continuous degrees of - freedom DF, is less than or equal to X. - - Arguments - - X --> Upper limit of integration of the non-central - chi-square distribution. - - DF --> Degrees of freedom of the non-central - chi-square distribution. - - PNONC --> Non-centrality parameter of the non-central - chi-square distribution. - - CUM <-- Cumulative non-central chi-square distribution. - - CCUM <-- Compliment of Cumulative non-central chi-square distribut - - - Method - - Uses formula 26.4.25 of Abramowitz and Stegun, Handbook of - Mathematical Functions, US NBS (1966) to calculate the - non-central chi-square. - - Variables - - EPS --- Convergence criterion. The sum stops when a - term is less than EPS*SUM. - - CCUM <-- Compliment of Cumulative non-central - chi-square distribution. - -**********************************************************************/ -{ -#define dg(i) (*df + 2.0e0 * (double)(i)) -#define qsmall(xx) (int)(sum < 1.0e-20 || (xx) < eps * sum) - static double eps = 1.0e-5; - static double adj, centaj, centwt, chid2, dfd2, lcntaj, lcntwt, lfact, pcent, pterm, sum, sumadj, term, wt, xnonc; - static int i, icent; - static double T1, T2, T3; - /* - .. - .. Executable Statements .. - */ - if (!(*x <= 0.0e0)) goto S10; - *cum = 0.0e0; - *ccum = 1.0e0; - return; -S10: - if (!(*pnonc <= 1.0e-10)) goto S20; - /* - When non-centrality parameter is (essentially) zero, - use cumulative chi-square distribution - */ - cumchi(x, df, cum, ccum); - return; -S20: - xnonc = *pnonc / 2.0e0; - /* - *********************************************************************** - The following code calcualtes the weight, chi-square, and - adjustment term for the central term in the infinite series. - The central term is the one in which the poisson weight is - greatest. The adjustment term is the amount that must - be subtracted from the chi-square to move up two degrees - of freedom. - *********************************************************************** - */ - icent = fifidint(xnonc); - if (icent == 0) icent = 1; - chid2 = *x / 2.0e0; - /* - Calculate central weight term - */ - T1 = (double)(icent + 1); - lfact = alngam(&T1); - lcntwt = -xnonc + (double)icent * log(xnonc) - lfact; - centwt = exp(lcntwt); - /* - Calculate central chi-square - */ - T2 = dg(icent); - cumchi(x, &T2, &pcent, ccum); - /* - Calculate central adjustment term - */ - dfd2 = dg(icent) / 2.0e0; - T3 = 1.0e0 + dfd2; - lfact = alngam(&T3); - lcntaj = dfd2 * log(chid2) - chid2 - lfact; - centaj = exp(lcntaj); - sum = centwt * pcent; - /* - *********************************************************************** - Sum backwards from the central term towards zero. - Quit whenever either - (1) the zero term is reached, or - (2) the term gets small relative to the sum - *********************************************************************** - */ - sumadj = 0.0e0; - adj = centaj; - wt = centwt; - i = icent; - goto S40; -S30: - if (qsmall(term) || i == 0) goto S50; -S40: - dfd2 = dg(i) / 2.0e0; - /* - Adjust chi-square for two fewer degrees of freedom. - The adjusted value ends up in PTERM. - */ - adj = adj * dfd2 / chid2; - sumadj += adj; - pterm = pcent + sumadj; - /* - Adjust poisson weight for J decreased by one - */ - wt *= ((double)i / xnonc); - term = wt * pterm; - sum += term; - i -= 1; - goto S30; -S50: - /* - *********************************************************************** - Now sum forward from the central term towards infinity. - Quit when either - (1) the term gets small relative to the sum, or - *********************************************************************** - */ - sumadj = adj = centaj; - wt = centwt; - i = icent; - goto S70; -S60: - if (qsmall(term)) goto S80; -S70: - /* - Update weights for next higher J - */ - wt *= (xnonc / (double)(i + 1)); - /* - Calculate PTERM and add term to sum - */ - pterm = pcent - sumadj; - term = wt * pterm; - sum += term; - /* - Update adjustment term for DF for next iteration - */ - i += 1; - dfd2 = dg(i) / 2.0e0; - adj = adj * chid2 / dfd2; - sumadj += adj; - goto S60; -S80: - *cum = sum; - *ccum = 0.5e0 + (0.5e0 - *cum); - return; -#undef dg -#undef qsmall -} -void cumf(double *f, double *dfn, double *dfd, double *cum, double *ccum) -/* -********************************************************************** - - void cumf(double *f,double *dfn,double *dfd,double *cum,double *ccum) - CUMulative F distribution - - - Function - - - Computes the integral from 0 to F of the f-density with DFN - and DFD degrees of freedom. - - - Arguments - - - F --> Upper limit of integration of the f-density. - F is DOUBLE PRECISION - - DFN --> Degrees of freedom of the numerator sum of squares. - DFN is DOUBLE PRECISI - - DFD --> Degrees of freedom of the denominator sum of squares. - DFD is DOUBLE PRECISI - - CUM <-- Cumulative f distribution. - CUM is DOUBLE PRECISI - - CCUM <-- Compliment of Cumulative f distribution. - CCUM is DOUBLE PRECIS - - - Method - - - Formula 26.5.28 of Abramowitz and Stegun is used to reduce - the cumulative F to a cumulative beta distribution. - - - Note - - - If F is less than or equal to 0, 0 is returned. - -********************************************************************** -*/ -{ -#define half 0.5e0 -#define done 1.0e0 - static double dsum, prod, xx, yy; - static int ierr; - static double T1, T2; - /* - .. - .. Executable Statements .. - */ - if (!(*f <= 0.0e0)) goto S10; - *cum = 0.0e0; - *ccum = 1.0e0; - return; -S10: - prod = *dfn * *f; - /* - XX is such that the incomplete beta with parameters - DFD/2 and DFN/2 evaluated at XX is 1 - CUM or CCUM - YY is 1 - XX - Calculate the smaller of XX and YY accurately - */ - dsum = *dfd + prod; - xx = *dfd / dsum; - if (xx > half) { - yy = prod / dsum; - xx = done - yy; - } - else - yy = done - xx; - T1 = *dfd * half; - T2 = *dfn * half; - bratio(&T1, &T2, &xx, &yy, ccum, cum, &ierr); - return; -#undef half -#undef done -} -void cumfnc(double *f, double *dfn, double *dfd, double *pnonc, double *cum, double *ccum) -/* -********************************************************************** - - F -NON- -C-ENTRAL F DISTRIBUTION - - - - Function - - - COMPUTES NONCENTRAL F DISTRIBUTION WITH DFN AND DFD - DEGREES OF FREEDOM AND NONCENTRALITY PARAMETER PNONC - - - Arguments - - - X --> UPPER LIMIT OF INTEGRATION OF NONCENTRAL F IN EQUATION - - DFN --> DEGREES OF FREEDOM OF NUMERATOR - - DFD --> DEGREES OF FREEDOM OF DENOMINATOR - - PNONC --> NONCENTRALITY PARAMETER. - - CUM <-- CUMULATIVE NONCENTRAL F DISTRIBUTION - - CCUM <-- COMPLIMENT OF CUMMULATIVE - - - Method - - - USES FORMULA 26.6.20 OF REFERENCE FOR INFINITE SERIES. - SERIES IS CALCULATED BACKWARD AND FORWARD FROM J = LAMBDA/2 - (THIS IS THE TERM WITH THE LARGEST POISSON WEIGHT) UNTIL - THE CONVERGENCE CRITERION IS MET. - - FOR SPEED, THE INCOMPLETE BETA FUNCTIONS ARE EVALUATED - BY FORMULA 26.5.16. - - - REFERENCE - - - HANDBOOD OF MATHEMATICAL FUNCTIONS - EDITED BY MILTON ABRAMOWITZ AND IRENE A. STEGUN - NATIONAL BUREAU OF STANDARDS APPLIED MATEMATICS SERIES - 55 - MARCH 1965 - P 947, EQUATIONS 26.6.17, 26.6.18 - - - Note - - - THE SUM CONTINUES UNTIL A SUCCEEDING TERM IS LESS THAN EPS - TIMES THE SUM (OR THE SUM IS LESS THAN 1.0E-20). EPS IS - SET TO 1.0E-4 IN A DATA STATEMENT WHICH CAN BE CHANGED. - -********************************************************************** -*/ -{ -#define qsmall(x) (int)(sum < 1.0e-20 || (x) < eps * sum) -#define half 0.5e0 -#define done 1.0e0 - static double eps = 1.0e-4; - static double dsum, dummy, prod, xx, yy, adn, aup, b, betdn, betup, centwt, dnterm, sum, upterm, xmult, xnonc; - static int i, icent, ierr; - static double T1, T2, T3, T4, T5, T6; - /* - .. - .. Executable Statements .. - */ - if (!(*f <= 0.0e0)) goto S10; - *cum = 0.0e0; - *ccum = 1.0e0; - return; -S10: - if (!(*pnonc < 1.0e-10)) goto S20; - /* - Handle case in which the non-centrality parameter is - (essentially) zero. - */ - cumf(f, dfn, dfd, cum, ccum); - return; -S20: - xnonc = *pnonc / 2.0e0; - /* - Calculate the central term of the poisson weighting factor. - */ - icent = (long)(xnonc); - if (icent == 0) icent = 1; - /* - Compute central weight term - */ - T1 = (double)(icent + 1); - centwt = exp(-xnonc + (double)icent * log(xnonc) - alngam(&T1)); - /* - Compute central incomplete beta term - Assure that minimum of arg to beta and 1 - arg is computed - accurately. - */ - prod = *dfn * *f; - dsum = *dfd + prod; - yy = *dfd / dsum; - if (yy > half) { - xx = prod / dsum; - yy = done - xx; - } - else - xx = done - yy; - T2 = *dfn * half + (double)icent; - T3 = *dfd * half; - bratio(&T2, &T3, &xx, &yy, &betdn, &dummy, &ierr); - adn = *dfn / 2.0e0 + (double)icent; - aup = adn; - b = *dfd / 2.0e0; - betup = betdn; - sum = centwt * betdn; - /* - Now sum terms backward from icent until convergence or all done - */ - xmult = centwt; - i = icent; - T4 = adn + b; - T5 = adn + 1.0e0; - dnterm = exp(alngam(&T4) - alngam(&T5) - alngam(&b) + adn * log(xx) + b * log(yy)); -S30: - if (qsmall(xmult * betdn) || i <= 0) goto S40; - xmult *= ((double)i / xnonc); - i -= 1; - adn -= 1.0; - dnterm = (adn + 1.0) / ((adn + b) * xx) * dnterm; - betdn += dnterm; - sum += (xmult * betdn); - goto S30; -S40: - i = icent + 1; - /* - Now sum forwards until convergence - */ - xmult = centwt; - if (aup - 1.0 + b == 0) - upterm = exp(-alngam(&aup) - alngam(&b) + (aup - 1.0) * log(xx) + b * log(yy)); - else { - T6 = aup - 1.0 + b; - upterm = exp(alngam(&T6) - alngam(&aup) - alngam(&b) + (aup - 1.0) * log(xx) + b * log(yy)); - } - goto S60; -S50: - if (qsmall(xmult * betup)) goto S70; -S60: - xmult *= (xnonc / (double)i); - i += 1; - aup += 1.0; - upterm = (aup + b - 2.0e0) * xx / (aup - 1.0) * upterm; - betup -= upterm; - sum += (xmult * betup); - goto S50; -S70: - *cum = sum; - *ccum = 0.5e0 + (0.5e0 - *cum); - return; -#undef qsmall -#undef half -#undef done -} -void cumgam(double *x, double *a, double *cum, double *ccum) -/* -********************************************************************** - - void cumgam(double *x,double *a,double *cum,double *ccum) - Double precision cUMulative incomplete GAMma distribution - - - Function - - - Computes the cumulative of the incomplete gamma - distribution, i.e., the integral from 0 to X of - (1/GAM(A))*EXP(-T)*T**(A-1) DT - where GAM(A) is the complete gamma function of A, i.e., - GAM(A) = integral from 0 to infinity of - EXP(-T)*T**(A-1) DT - - - Arguments - - - X --> The upper limit of integration of the incomplete gamma. - X is DOUBLE PRECISION - - A --> The shape parameter of the incomplete gamma. - A is DOUBLE PRECISION - - CUM <-- Cumulative incomplete gamma distribution. - CUM is DOUBLE PRECISION - - CCUM <-- Compliment of Cumulative incomplete gamma distribution. - CCUM is DOUBLE PRECISIO - - - Method - - - Calls the routine GRATIO. - -********************************************************************** -*/ -{ - static int K1 = 0; - /* - .. - .. Executable Statements .. - */ - if (!(*x <= 0.0e0)) goto S10; - *cum = 0.0e0; - *ccum = 1.0e0; - return; -S10: - gratio(a, x, cum, ccum, &K1); - /* - Call gratio routine - */ - return; -} -void cumnbn(double *s, double *xn, double *pr, double *ompr, double *cum, double *ccum) -/* -********************************************************************** - - void cumnbn(double *s,double *xn,double *pr,double *ompr, - double *cum,double *ccum) - - CUmulative Negative BINomial distribution - - - Function - - - Returns the probability that it there will be S or fewer failures - before there are XN successes, with each binomial trial having - a probability of success PR. - - Prob(# failures = S | XN successes, PR) = - ( XN + S - 1 ) - ( ) * PR^XN * (1-PR)^S - ( S ) - - - Arguments - - - S --> The number of failures - S is DOUBLE PRECISION - - XN --> The number of successes - XN is DOUBLE PRECISIO - - PR --> The probability of success in each binomial trial. - PR is DOUBLE PRECISIO - - OMPR --> 1 - PR - OMPR is DOUBLE PRECIS - - CUM <-- Cumulative negative binomial distribution. - CUM is DOUBLE PRECISI - - CCUM <-- Compliment of Cumulative negative binomial distribution. - CCUM is DOUBLE PRECIS - - - Method - - - Formula 26.5.26 of Abramowitz and Stegun, Handbook of - Mathematical Functions (1966) is used to reduce the negative - binomial distribution to the cumulative beta distribution. - -********************************************************************** -*/ -{ - static double T1; - /* - .. - .. Executable Statements .. - */ - T1 = *s + 1.e0; - cumbet(pr, ompr, xn, &T1, cum, ccum); - return; -} -void cumnor(double *arg, double *result, double *ccum) -/* -********************************************************************** - - void cumnor(double *arg,double *result,double *ccum) - - - Function - - - Computes the cumulative of the normal distribution, i.e., - the integral from -infinity to x of - (1/sqrt(2*pi)) exp(-u*u/2) du - - X --> Upper limit of integration. - X is DOUBLE PRECISION - - RESULT <-- Cumulative normal distribution. - RESULT is DOUBLE PRECISION - - CCUM <-- Compliment of Cumulative normal distribution. - CCUM is DOUBLE PRECISION - - Renaming of function ANORM from: - - Cody, W.D. (1993). "ALGORITHM 715: SPECFUN - A Portabel FORTRAN - Package of Special Function Routines and Test Drivers" - acm Transactions on Mathematical Software. 19, 22-32. - - with slight modifications to return ccum and to deal with - machine constants. - -********************************************************************** - Original Comments: ------------------------------------------------------------------- - - This function evaluates the normal distribution function: - - / x - 1 | -t*t/2 - P(x) = ----------- | e dt - sqrt(2 pi) | - /-oo - - The main computation evaluates near-minimax approximations - derived from those in "Rational Chebyshev approximations for - the error function" by W. J. Cody, Math. Comp., 1969, 631-637. - This transportable program uses rational functions that - theoretically approximate the normal distribution function to - at least 18 significant decimal digits. The accuracy achieved - depends on the arithmetic system, the compiler, the intrinsic - functions, and proper selection of the machine-dependent - constants. - -******************************************************************* -******************************************************************* - - Explanation of machine-dependent constants. - - MIN = smallest machine representable number. - - EPS = argument below which anorm(x) may be represented by - 0.5 and above which x*x will not underflow. - A conservative value is the largest machine number X - such that 1.0 + X = 1.0 to machine precision. -******************************************************************* -******************************************************************* - - Error returns - - The program returns ANORM = 0 for ARG .LE. XLOW. - - - Intrinsic functions required are: - - ABS, AINT, EXP - - - Author: W. J. Cody - Mathematics and Computer Science Division - Argonne National Laboratory - Argonne, IL 60439 - - Latest modification: March 15, 1992 - ------------------------------------------------------------------- -*/ -{ - static double a[5] = {2.2352520354606839287e00, - 1.6102823106855587881e02, - 1.0676894854603709582e03, - 1.8154981253343561249e04, - 6.5682337918207449113e-2}; - static double b[4] = { - 4.7202581904688241870e01, 9.7609855173777669322e02, 1.0260932208618978205e04, 4.5507789335026729956e04}; - static double c[9] = {3.9894151208813466764e-1, - 8.8831497943883759412e00, - 9.3506656132177855979e01, - 5.9727027639480026226e02, - 2.4945375852903726711e03, - 6.8481904505362823326e03, - 1.1602651437647350124e04, - 9.8427148383839780218e03, - 1.0765576773720192317e-8}; - static double d[8] = {2.2266688044328115691e01, - 2.3538790178262499861e02, - 1.5193775994075548050e03, - 6.4855582982667607550e03, - 1.8615571640885098091e04, - 3.4900952721145977266e04, - 3.8912003286093271411e04, - 1.9685429676859990727e04}; - static double half = 0.5e0; - static double p[6] = {2.1589853405795699e-1, - 1.274011611602473639e-1, - 2.2235277870649807e-2, - 1.421619193227893466e-3, - 2.9112874951168792e-5, - 2.307344176494017303e-2}; - static double one = 1.0e0; - static double q[5] = {1.28426009614491121e00, - 4.68238212480865118e-1, - 6.59881378689285515e-2, - 3.78239633202758244e-3, - 7.29751555083966205e-5}; - static double sixten = 1.60e0; - static double sqrpi = 3.9894228040143267794e-1; - static double thrsh = 0.66291e0; - static double root32 = 5.656854248e0; - static double zero = 0.0e0; - static int K1 = 1; - static int K2 = 2; - static int i; - static double del, eps, temp, x, xden, xnum, y, xsq, min; - /* - ------------------------------------------------------------------ - Machine dependent constants - ------------------------------------------------------------------ - */ - eps = spmpar(&K1) * 0.5e0; - min = spmpar(&K2); - x = *arg; - y = fabs(x); - if (y <= thrsh) { - /* - ------------------------------------------------------------------ - Evaluate anorm for |X| <= 0.66291 - ------------------------------------------------------------------ - */ - xsq = zero; - if (y > eps) xsq = x * x; - xnum = a[4] * xsq; - xden = xsq; - for (i = 0; i < 3; i++) { - xnum = (xnum + a[i]) * xsq; - xden = (xden + b[i]) * xsq; - } - *result = x * (xnum + a[3]) / (xden + b[3]); - temp = *result; - *result = half + temp; - *ccum = half - temp; - } - /* - ------------------------------------------------------------------ - Evaluate anorm for 0.66291 <= |X| <= sqrt(32) - ------------------------------------------------------------------ - */ - else if (y <= root32) { - xnum = c[8] * y; - xden = y; - for (i = 0; i < 7; i++) { - xnum = (xnum + c[i]) * y; - xden = (xden + d[i]) * y; - } - *result = (xnum + c[7]) / (xden + d[7]); - xsq = fifdint(y * sixten) / sixten; - del = (y - xsq) * (y + xsq); - *result = exp(-(xsq * xsq * half)) * exp(-(del * half)) * *result; - *ccum = one - *result; - if (x > zero) { - temp = *result; - *result = *ccum; - *ccum = temp; - } - } - /* - ------------------------------------------------------------------ - Evaluate anorm for |X| > sqrt(32) - ------------------------------------------------------------------ - */ - else { - *result = zero; - xsq = one / (x * x); - xnum = p[5] * xsq; - xden = xsq; - for (i = 0; i < 4; i++) { - xnum = (xnum + p[i]) * xsq; - xden = (xden + q[i]) * xsq; - } - *result = xsq * (xnum + p[4]) / (xden + q[4]); - *result = (sqrpi - *result) / y; - xsq = fifdint(x * sixten) / sixten; - del = (x - xsq) * (x + xsq); - *result = exp(-(xsq * xsq * half)) * exp(-(del * half)) * *result; - *ccum = one - *result; - if (x > zero) { - temp = *result; - *result = *ccum; - *ccum = temp; - } - } - if (*result < min) *result = 0.0e0; - /* - ------------------------------------------------------------------ - Fix up for negative argument, erf, etc. - ------------------------------------------------------------------ - ----------Last card of ANORM ---------- - */ - if (*ccum < min) *ccum = 0.0e0; -} -void cumpoi(double *s, double *xlam, double *cum, double *ccum) -/* -********************************************************************** - - void cumpoi(double *s,double *xlam,double *cum,double *ccum) - CUMulative POIsson distribution - - - Function - - - Returns the probability of S or fewer events in a Poisson - distribution with mean XLAM. - - - Arguments - - - S --> Upper limit of cumulation of the Poisson. - S is DOUBLE PRECISION - - XLAM --> Mean of the Poisson distribution. - XLAM is DOUBLE PRECIS - - CUM <-- Cumulative poisson distribution. - CUM is DOUBLE PRECISION - - CCUM <-- Compliment of Cumulative poisson distribution. - CCUM is DOUBLE PRECIS - - - Method - - - Uses formula 26.4.21 of Abramowitz and Stegun, Handbook of - Mathematical Functions to reduce the cumulative Poisson to - the cumulative chi-square distribution. - -********************************************************************** -*/ -{ - static double chi, df; - /* - .. - .. Executable Statements .. - */ - df = 2.0e0 * (*s + 1.0e0); - chi = 2.0e0 * *xlam; - cumchi(&chi, &df, ccum, cum); - return; -} -void cumt(double *t, double *df, double *cum, double *ccum) -/* -********************************************************************** - - void cumt(double *t,double *df,double *cum,double *ccum) - CUMulative T-distribution - - - Function - - - Computes the integral from -infinity to T of the t-density. - - - Arguments - - - T --> Upper limit of integration of the t-density. - T is DOUBLE PRECISION - - DF --> Degrees of freedom of the t-distribution. - DF is DOUBLE PRECISIO - - CUM <-- Cumulative t-distribution. - CCUM is DOUBLE PRECIS - - CCUM <-- Compliment of Cumulative t-distribution. - CCUM is DOUBLE PRECIS - - - Method - - - Formula 26.5.27 of Abramowitz and Stegun, Handbook of - Mathematical Functions is used to reduce the t-distribution - to an incomplete beta. - -********************************************************************** -*/ -{ - static double K2 = 0.5e0; - static double xx, a, oma, tt, yy, dfptt, T1; - /* - .. - .. Executable Statements .. - */ - tt = *t * *t; - dfptt = *df + tt; - xx = *df / dfptt; - yy = tt / dfptt; - T1 = 0.5e0 * *df; - cumbet(&xx, &yy, &T1, &K2, &a, &oma); - if (!(*t <= 0.0e0)) goto S10; - *cum = 0.5e0 * a; - *ccum = oma + *cum; - goto S20; -S10: - *ccum = 0.5e0 * a; - *cum = oma + *ccum; -S20: - return; -} -void cumtnc(double *t, double *df, double *pnonc, double *cum, double *ccum) -/********************************************************************** - - void cumtnc(double *t,double *df,double *pnonc,double *cum, - double *ccum) - - CUMulative Non-Central T-distribution - - - Function - - - Computes the integral from -infinity to T of the non-central - t-density. - - - Arguments - - - T --> Upper limit of integration of the non-central t-density. - - DF --> Degrees of freedom of the non-central t-distribution. - - PNONC --> Non-centrality parameter of the non-central t distibutio - - CUM <-- Cumulative t-distribution. - - CCUM <-- Compliment of Cumulative t-distribution. - - - Method - - Upper tail of the cumulative noncentral t using - formulae from page 532 of Johnson, Kotz, Balakrishnan, Coninuous - Univariate Distributions, Vol 2, 2nd Edition. Wiley (1995) - - This implementation starts the calculation at i = lambda, - which is near the largest Di. It then sums forward and backward. -**********************************************************************/ -{ -#define one 1.0e0 -#define zero 0.0e0 -#define half 0.5e0 -#define two 2.0e0 -#define onep5 1.5e0 -#define conv 1.0e-7 -#define tiny 1.0e-10 - static double alghdf, b, bb, bbcent, bcent, cent, d, dcent, dpnonc, dum1, dum2, e, ecent, halfdf, lambda, lnomx, lnx, - omx, pnonc2, s, scent, ss, sscent, t2, term, tt, twoi, x, xi, xlnd, xlne; - static int ierr; - static unsigned long qrevs; - static double T1, T2, T3, T4, T5, T6, T7, T8, T9, T10; - /* - .. - .. Executable Statements .. - */ - /* - Case pnonc essentially zero - */ - if (fabs(*pnonc) <= tiny) { - cumt(t, df, cum, ccum); - return; - } - qrevs = *t < zero; - if (qrevs) { - tt = -*t; - dpnonc = -*pnonc; - } - else { - tt = *t; - dpnonc = *pnonc; - } - pnonc2 = dpnonc * dpnonc; - t2 = tt * tt; - if (fabs(tt) <= tiny) { - T1 = -*pnonc; - cumnor(&T1, cum, ccum); - return; - } - lambda = half * pnonc2; - x = *df / (*df + t2); - omx = one - x; - lnx = log(x); - lnomx = log(omx); - halfdf = half * *df; - alghdf = gamln(&halfdf); - /* - ******************** Case i = lambda - */ - cent = fifidint(lambda); - if (cent < one) cent = one; - /* - Compute d=T(2i) in log space and offset by exp(-lambda) - */ - T2 = cent + one; - xlnd = cent * log(lambda) - gamln(&T2) - lambda; - dcent = exp(xlnd); - /* - Compute e=t(2i+1) in log space offset by exp(-lambda) - */ - T3 = cent + onep5; - xlne = (cent + half) * log(lambda) - gamln(&T3) - lambda; - ecent = exp(xlne); - if (dpnonc < zero) ecent = -ecent; - /* - Compute bcent=B(2*cent) - */ - T4 = cent + half; - bratio(&halfdf, &T4, &x, &omx, &bcent, &dum1, &ierr); - /* - compute bbcent=B(2*cent+1) - */ - T5 = cent + one; - bratio(&halfdf, &T5, &x, &omx, &bbcent, &dum2, &ierr); - /* - Case bcent and bbcent are essentially zero - Thus t is effectively infinite - */ - if (bcent + bbcent < tiny) { - if (qrevs) { - *cum = zero; - *ccum = one; - } - else { - *cum = one; - *ccum = zero; - } - return; - } - /* - Case bcent and bbcent are essentially one - Thus t is effectively zero - */ - if (dum1 + dum2 < tiny) { - T6 = -*pnonc; - cumnor(&T6, cum, ccum); - return; - } - /* - First term in ccum is D*B + E*BB - */ - *ccum = dcent * bcent + ecent * bbcent; - /* - compute s(cent) = B(2*(cent+1)) - B(2*cent)) - */ - T7 = halfdf + cent + half; - T8 = cent + onep5; - scent = gamln(&T7) - gamln(&T8) - alghdf + halfdf * lnx + (cent + half) * lnomx; - scent = exp(scent); - /* - compute ss(cent) = B(2*cent+3) - B(2*cent+1) - */ - T9 = halfdf + cent + one; - T10 = cent + two; - sscent = gamln(&T9) - gamln(&T10) - alghdf + halfdf * lnx + (cent + one) * lnomx; - sscent = exp(sscent); - /* - ******************** Sum Forward - */ - xi = cent + one; - twoi = two * xi; - d = dcent; - e = ecent; - b = bcent; - bb = bbcent; - s = scent; - ss = sscent; -S10: - b += s; - bb += ss; - d = lambda / xi * d; - e = lambda / (xi + half) * e; - term = d * b + e * bb; - *ccum += term; - s = s * omx * (*df + twoi - one) / (twoi + one); - ss = ss * omx * (*df + twoi) / (twoi + two); - xi += one; - twoi = two * xi; - if (fabs(term) > conv * *ccum) goto S10; - /* - ******************** Sum Backward - */ - xi = cent; - twoi = two * xi; - d = dcent; - e = ecent; - b = bcent; - bb = bbcent; - s = scent * (one + twoi) / ((*df + twoi - one) * omx); - ss = sscent * (two + twoi) / ((*df + twoi) * omx); -S20: - b -= s; - bb -= ss; - d *= (xi / lambda); - e *= ((xi + half) / lambda); - term = d * b + e * bb; - *ccum += term; - xi -= one; - if (xi < half) goto S30; - twoi = two * xi; - s = s * (one + twoi) / ((*df + twoi - one) * omx); - ss = ss * (two + twoi) / ((*df + twoi) * omx); - if (fabs(term) > conv * *ccum) goto S20; -S30: - if (qrevs) { - *cum = half * *ccum; - *ccum = one - *cum; - } - else { - *ccum = half * *ccum; - *cum = one - *ccum; - } - /* - Due to roundoff error the answer may not lie between zero and one - Force it to do so - */ - *cum = fifdmax1(fifdmin1(*cum, one), zero); - *ccum = fifdmax1(fifdmin1(*ccum, one), zero); - return; -#undef one -#undef zero -#undef half -#undef two -#undef onep5 -#undef conv -#undef tiny -} -double devlpl(double a[], int *n, double *x) -/* -********************************************************************** - - double devlpl(double a[],int *n,double *x) - Double precision EVALuate a PoLynomial at X - - - Function - - - returns - A(1) + A(2)*X + ... + A(N)*X**(N-1) - - - Arguments - - - A --> Array of coefficients of the polynomial. - A is DOUBLE PRECISION(N) - - N --> Length of A, also degree of polynomial - 1. - N is INTEGER - - X --> Point at which the polynomial is to be evaluated. - X is DOUBLE PRECISION - -********************************************************************** -*/ -{ - static double devlpl, term; - static int i; - /* - .. - .. Executable Statements .. - */ - term = a[*n - 1]; - for (i = *n - 1 - 1; i >= 0; i--) term = a[i] + term * *x; - devlpl = term; - return devlpl; -} -double dinvnr(double *p, double *q) -/* -********************************************************************** - - double dinvnr(double *p,double *q) - Double precision NoRmal distribution INVerse - - - Function - - - Returns X such that CUMNOR(X) = P, i.e., the integral from - - infinity to X of (1/SQRT(2*PI)) EXP(-U*U/2) dU is P - - - Arguments - - - P --> The probability whose normal deviate is sought. - P is DOUBLE PRECISION - - Q --> 1-P - P is DOUBLE PRECISION - - - Method - - - The rational function on page 95 of Kennedy and Gentle, - Statistical Computing, Marcel Dekker, NY , 1980 is used as a start - value for the Newton method of finding roots. - - - Note - - - If P or Q .lt. machine EPS returns +/- DINVNR(EPS) - -********************************************************************** -*/ -{ -#define maxit 100 -#define eps 1.0e-13 -#define r2pi 0.3989422804014326e0 -#define nhalf -0.5e0 -#define dennor(x) (r2pi * exp(nhalf * (x) * (x))) - static double dinvnr, strtx, xcur, cum, ccum, pp, dx; - static int i; - static unsigned long qporq; - /* - .. - .. Executable Statements .. - */ - /* - FIND MINIMUM OF P AND Q - */ - qporq = *p <= *q; - if (!qporq) goto S10; - pp = *p; - goto S20; -S10: - pp = *q; -S20: - /* - INITIALIZATION STEP - */ - strtx = stvaln(&pp); - xcur = strtx; - /* - NEWTON INTERATIONS - */ - for (i = 1; i <= maxit; i++) { - cumnor(&xcur, &cum, &ccum); - dx = (cum - pp) / dennor(xcur); - xcur -= dx; - if (fabs(dx / xcur) < eps) goto S40; - } - dinvnr = strtx; - /* - IF WE GET HERE, NEWTON HAS FAILED - */ - if (!qporq) dinvnr = -dinvnr; - return dinvnr; -S40: - /* - IF WE GET HERE, NEWTON HAS SUCCEDED - */ - dinvnr = xcur; - if (!qporq) dinvnr = -dinvnr; - return dinvnr; -#undef maxit -#undef eps -#undef r2pi -#undef nhalf -#undef dennor -} -/* DEFINE DINVR */ -static void E0000(int IENTRY, - int *status, - double *x, - double *fx, - unsigned long *qleft, - unsigned long *qhi, - double *zabsst, - double *zabsto, - double *zbig, - double *zrelst, - double *zrelto, - double *zsmall, - double *zstpmu) -{ -#define qxmon(zx, zy, zz) (int)((zx) <= (zy) && (zy) <= (zz)) - static double absstp, abstol, big, fbig, fsmall, relstp, reltol, small, step, stpmul, xhi, xlb, xlo, xsave, xub, yy; - static int i99999; - static unsigned long qbdd, qcond, qdum1, qdum2, qincr, qlim, qup; - switch (IENTRY) { - case 0: - goto DINVR; - case 1: - goto DSTINV; - } -DINVR: - if (*status > 0) goto S310; - qcond = !qxmon(small, *x, big); - if (qcond) ftnstop(" SMALL, X, BIG not monotone in INVR"); - xsave = *x; - /* - See that SMALL and BIG bound the zero and set QINCR - */ - *x = small; - /* - GET-FUNCTION-VALUE - */ - i99999 = 1; - goto S300; -S10: - fsmall = *fx; - *x = big; - /* - GET-FUNCTION-VALUE - */ - i99999 = 2; - goto S300; -S20: - fbig = *fx; - qincr = fbig > fsmall; - if (!qincr) goto S50; - if (fsmall <= 0.0e0) goto S30; - *status = -1; - *qleft = *qhi = 1; - return; -S30: - if (fbig >= 0.0e0) goto S40; - *status = -1; - *qleft = *qhi = 0; - return; -S40: - goto S80; -S50: - if (fsmall >= 0.0e0) goto S60; - *status = -1; - *qleft = 1; - *qhi = 0; - return; -S60: - if (fbig <= 0.0e0) goto S70; - *status = -1; - *qleft = 0; - *qhi = 1; - return; -S80: -S70: - *x = xsave; - step = fifdmax1(absstp, relstp * fabs(*x)); - /* - YY = F(X) - Y - GET-FUNCTION-VALUE - */ - i99999 = 3; - goto S300; -S90: - yy = *fx; - if (!(yy == 0.0e0)) goto S100; - *status = 0; - return; -S100: - qup = (qincr && yy < 0.0e0) || (!qincr && yy > 0.0e0); - /* - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - HANDLE CASE IN WHICH WE MUST STEP HIGHER - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - */ - if (!qup) goto S170; - xlb = xsave; - xub = fifdmin1(xlb + step, big); - goto S120; -S110: - if (qcond) goto S150; -S120: - /* - YY = F(XUB) - Y - */ - *x = xub; - /* - GET-FUNCTION-VALUE - */ - i99999 = 4; - goto S300; -S130: - yy = *fx; - qbdd = (qincr && yy >= 0.0e0) || (!qincr && yy <= 0.0e0); - qlim = xub >= big; - qcond = qbdd || qlim; - if (qcond) goto S140; - step = stpmul * step; - xlb = xub; - xub = fifdmin1(xlb + step, big); -S140: - goto S110; -S150: - if (!(qlim && !qbdd)) goto S160; - *status = -1; - *qleft = 0; - *qhi = !qincr; - *x = big; - return; -S160: - goto S240; -S170: - /* - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - HANDLE CASE IN WHICH WE MUST STEP LOWER - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - */ - xub = xsave; - xlb = fifdmax1(xub - step, small); - goto S190; -S180: - if (qcond) goto S220; -S190: - /* - YY = F(XLB) - Y - */ - *x = xlb; - /* - GET-FUNCTION-VALUE - */ - i99999 = 5; - goto S300; -S200: - yy = *fx; - qbdd = (qincr && yy <= 0.0e0) || (!qincr && yy >= 0.0e0); - qlim = xlb <= small; - qcond = qbdd || qlim; - if (qcond) goto S210; - step = stpmul * step; - xub = xlb; - xlb = fifdmax1(xub - step, small); -S210: - goto S180; -S220: - if (!(qlim && !qbdd)) goto S230; - *status = -1; - *qleft = 1; - *qhi = qincr; - *x = small; - return; -S240: -S230: - dstzr(&xlb, &xub, &abstol, &reltol); - /* - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - IF WE REACH HERE, XLB AND XUB BOUND THE ZERO OF F. - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - */ - *status = 0; - goto S260; -S250: - if (!(*status == 1)) goto S290; -S260: - dzror(status, x, fx, &xlo, &xhi, &qdum1, &qdum2); - if (!(*status == 1)) goto S280; - /* - GET-FUNCTION-VALUE - */ - i99999 = 6; - goto S300; -S280: -S270: - goto S250; -S290: - *x = xlo; - *status = 0; - return; -DSTINV: - small = *zsmall; - big = *zbig; - absstp = *zabsst; - relstp = *zrelst; - stpmul = *zstpmu; - abstol = *zabsto; - reltol = *zrelto; - return; -S300: - /* - TO GET-FUNCTION-VALUE - */ - *status = 1; - return; -S310: - switch ((int)i99999) { - case 1: - goto S10; - case 2: - goto S20; - case 3: - goto S90; - case 4: - goto S130; - case 5: - goto S200; - case 6: - goto S270; - default: - break; - } -#undef qxmon -} -void dinvr(int *status, double *x, double *fx, unsigned long *qleft, unsigned long *qhi) -/* -********************************************************************** - - void dinvr(int *status,double *x,double *fx, - unsigned long *qleft,unsigned long *qhi) - - Double precision - bounds the zero of the function and invokes zror - Reverse Communication - - - Function - - - Bounds the function and invokes ZROR to perform the zero - finding. STINVR must have been called before this routine - in order to set its parameters. - - - Arguments - - - STATUS <--> At the beginning of a zero finding problem, STATUS - should be set to 0 and INVR invoked. (The value - of parameters other than X will be ignored on this cal - - When INVR needs the function evaluated, it will set - STATUS to 1 and return. The value of the function - should be set in FX and INVR again called without - changing any of its other parameters. - - When INVR has finished without error, it will return - with STATUS 0. In that case X is approximately a root - of F(X). - - If INVR cannot bound the function, it returns status - -1 and sets QLEFT and QHI. - INTEGER STATUS - - X <-- The value of X at which F(X) is to be evaluated. - DOUBLE PRECISION X - - FX --> The value of F(X) calculated when INVR returns with - STATUS = 1. - DOUBLE PRECISION FX - - QLEFT <-- Defined only if QMFINV returns .FALSE. In that - case it is .TRUE. If the stepping search terminated - unsucessfully at SMALL. If it is .FALSE. the search - terminated unsucessfully at BIG. - QLEFT is LOGICAL - - QHI <-- Defined only if QMFINV returns .FALSE. In that - case it is .TRUE. if F(X) .GT. Y at the termination - of the search and .FALSE. if F(X) .LT. Y at the - termination of the search. - QHI is LOGICAL - -********************************************************************** -*/ -{ - E0000(0, status, x, fx, qleft, qhi, NULL, NULL, NULL, NULL, NULL, NULL, NULL); -} -void dstinv( - double *zsmall, double *zbig, double *zabsst, double *zrelst, double *zstpmu, double *zabsto, double *zrelto) -/* -********************************************************************** - void dstinv(double *zsmall,double *zbig,double *zabsst, - double *zrelst,double *zstpmu,double *zabsto, - double *zrelto) - - Double Precision - SeT INverse finder - Reverse Communication - Function - Concise Description - Given a monotone function F finds X - such that F(X) = Y. Uses Reverse communication -- see invr. - This routine sets quantities needed by INVR. - More Precise Description of INVR - - F must be a monotone function, the results of QMFINV are - otherwise undefined. QINCR must be .TRUE. if F is non- - decreasing and .FALSE. if F is non-increasing. - QMFINV will return .TRUE. if and only if F(SMALL) and - F(BIG) bracket Y, i. e., - QINCR is .TRUE. and F(SMALL).LE.Y.LE.F(BIG) or - QINCR is .FALSE. and F(BIG).LE.Y.LE.F(SMALL) - if QMFINV returns .TRUE., then the X returned satisfies - the following condition. let - TOL(X) = MAX(ABSTOL,RELTOL*ABS(X)) - then if QINCR is .TRUE., - F(X-TOL(X)) .LE. Y .LE. F(X+TOL(X)) - and if QINCR is .FALSE. - F(X-TOL(X)) .GE. Y .GE. F(X+TOL(X)) - Arguments - SMALL --> The left endpoint of the interval to be - searched for a solution. - SMALL is DOUBLE PRECISION - BIG --> The right endpoint of the interval to be - searched for a solution. - BIG is DOUBLE PRECISION - ABSSTP, RELSTP --> The initial step size in the search - is MAX(ABSSTP,RELSTP*ABS(X)). See algorithm. - ABSSTP is DOUBLE PRECISION - RELSTP is DOUBLE PRECISION - STPMUL --> When a step doesn't bound the zero, the step - size is multiplied by STPMUL and another step - taken. A popular value is 2.0 - DOUBLE PRECISION STPMUL - ABSTOL, RELTOL --> Two numbers that determine the accuracy - of the solution. See function for a precise definition. - ABSTOL is DOUBLE PRECISION - RELTOL is DOUBLE PRECISION - Method - Compares F(X) with Y for the input value of X then uses QINCR - to determine whether to step left or right to bound the - desired x. the initial step size is - MAX(ABSSTP,RELSTP*ABS(S)) for the input value of X. - Iteratively steps right or left until it bounds X. - At each step which doesn't bound X, the step size is doubled. - The routine is careful never to step beyond SMALL or BIG. If - it hasn't bounded X at SMALL or BIG, QMFINV returns .FALSE. - after setting QLEFT and QHI. - If X is successfully bounded then Algorithm R of the paper - 'Two Efficient Algorithms with Guaranteed Convergence for - Finding a Zero of a Function' by J. C. P. Bus and - T. J. Dekker in ACM Transactions on Mathematical - Software, Volume 1, No. 4 page 330 (DEC. '75) is employed - to find the zero of the function F(X)-Y. This is routine - QRZERO. -********************************************************************** -*/ -{ - E0000(1, NULL, NULL, NULL, NULL, NULL, zabsst, zabsto, zbig, zrelst, zrelto, zsmall, zstpmu); -} -double dt1(double *p, double *q, double *df) -/* -********************************************************************** - - double dt1(double *p,double *q,double *df) - Double precision Initalize Approximation to - INVerse of the cumulative T distribution - - - Function - - - Returns the inverse of the T distribution function, i.e., - the integral from 0 to INVT of the T density is P. This is an - initial approximation - - - Arguments - - - P --> The p-value whose inverse from the T distribution is - desired. - P is DOUBLE PRECISION - - Q --> 1-P. - Q is DOUBLE PRECISION - - DF --> Degrees of freedom of the T distribution. - DF is DOUBLE PRECISION - -********************************************************************** -*/ -{ - static double coef[4][5] = {{1.0e0, 1.0e0, 0.0e0, 0.0e0, 0.0e0}, - {3.0e0, 16.0e0, 5.0e0, 0.0e0, 0.0e0}, - {-15.0e0, 17.0e0, 19.0e0, 3.0e0, 0.0e0}, - {-945.0e0, -1920.0e0, 1482.0e0, 776.0e0, 79.0e0}}; - static double denom[4] = {4.0e0, 96.0e0, 384.0e0, 92160.0e0}; - static int ideg[4] = {2, 3, 4, 5}; - static double dt1, denpow, sum, term, x, xp, xx; - static int i; - /* - .. - .. Executable Statements .. - */ - x = fabs(dinvnr(p, q)); - xx = x * x; - sum = x; - denpow = 1.0e0; - for (i = 0; i < 4; i++) { - term = devlpl(&coef[i][0], &ideg[i], &xx) * x; - denpow *= *df; - sum += (term / (denpow * denom[i])); - } - if (!(*p >= 0.5e0)) goto S20; - xp = sum; - goto S30; -S20: - xp = -sum; -S30: - dt1 = xp; - return dt1; -} -/* DEFINE DZROR */ -static void E0001(int IENTRY, - int *status, - double *x, - double *fx, - double *xlo, - double *xhi, - unsigned long *qleft, - unsigned long *qhi, - double *zabstl, - double *zreltl, - double *zxhi, - double *zxlo) -{ -#define ftol(zx) (0.5e0 * fifdmax1(abstol, reltol * fabs((zx)))) - static double a, abstol, b, c, d, fa, fb, fc, fd, fda, fdb, m, mb, p, q, reltol, tol, w, xxhi, xxlo; - static int ext, i99999; - static unsigned long first, qrzero; - switch (IENTRY) { - case 0: - goto DZROR; - case 1: - goto DSTZR; - } -DZROR: - if (*status > 0) goto S280; - *xlo = xxlo; - *xhi = xxhi; - b = *x = *xlo; - /* - GET-FUNCTION-VALUE - */ - i99999 = 1; - goto S270; -S10: - fb = *fx; - *xlo = *xhi; - a = *x = *xlo; - /* - GET-FUNCTION-VALUE - */ - i99999 = 2; - goto S270; -S20: - /* - Check that F(ZXLO) < 0 < F(ZXHI) or - F(ZXLO) > 0 > F(ZXHI) - */ - if (!(fb < 0.0e0)) goto S40; - if (!(*fx < 0.0e0)) goto S30; - *status = -1; - *qleft = *fx < fb; - *qhi = 0; - return; -S40: -S30: - if (!(fb > 0.0e0)) goto S60; - if (!(*fx > 0.0e0)) goto S50; - *status = -1; - *qleft = *fx > fb; - *qhi = 1; - return; -S60: -S50: - fa = *fx; - first = 1; -S70: - c = a; - fc = fa; - ext = 0; -S80: - if (!(fabs(fc) < fabs(fb))) goto S100; - if (!(c != a)) goto S90; - d = a; - fd = fa; -S90: - a = b; - fa = fb; - *xlo = c; - b = *xlo; - fb = fc; - c = a; - fc = fa; -S100: - tol = ftol(*xlo); - m = (c + b) * .5e0; - mb = m - b; - if (!(fabs(mb) > tol)) goto S240; - if (!(ext > 3)) goto S110; - w = mb; - goto S190; -S110: - tol = fifdsign(tol, mb); - p = (b - a) * fb; - if (!first) goto S120; - q = fa - fb; - first = 0; - goto S130; -S120: - fdb = (fd - fb) / (d - b); - fda = (fd - fa) / (d - a); - p = fda * p; - q = fdb * fa - fda * fb; -S130: - if (!(p < 0.0e0)) goto S140; - p = -p; - q = -q; -S140: - if (ext == 3) p *= 2.0e0; - if (!(p * 1.0e0 == 0.0e0 || p <= q * tol)) goto S150; - w = tol; - goto S180; -S150: - if (!(p < mb * q)) goto S160; - w = p / q; - goto S170; -S160: - w = mb; -S190: -S180: -S170: - d = a; - fd = fa; - a = b; - fa = fb; - b += w; - *xlo = b; - *x = *xlo; - /* - GET-FUNCTION-VALUE - */ - i99999 = 3; - goto S270; -S200: - fb = *fx; - if (!(fc * fb >= 0.0e0)) goto S210; - goto S70; -S210: - if (!(w == mb)) goto S220; - ext = 0; - goto S230; -S220: - ext += 1; -S230: - goto S80; -S240: - *xhi = c; - qrzero = (fc >= 0.0e0 && fb <= 0.0e0) || (fc < 0.0e0 && fb >= 0.0e0); - if (!qrzero) goto S250; - *status = 0; - goto S260; -S250: - *status = -1; -S260: - return; -DSTZR: - xxlo = *zxlo; - xxhi = *zxhi; - abstol = *zabstl; - reltol = *zreltl; - return; -S270: - /* - TO GET-FUNCTION-VALUE - */ - *status = 1; - return; -S280: - switch ((int)i99999) { - case 1: - goto S10; - case 2: - goto S20; - case 3: - goto S200; - default: - break; - } -#undef ftol -} -void dzror(int *status, double *x, double *fx, double *xlo, double *xhi, unsigned long *qleft, unsigned long *qhi) -/* -********************************************************************** - - void dzror(int *status,double *x,double *fx,double *xlo, - double *xhi,unsigned long *qleft,unsigned long *qhi) - - Double precision ZeRo of a function -- Reverse Communication - - - Function - - - Performs the zero finding. STZROR must have been called before - this routine in order to set its parameters. - - - Arguments - - - STATUS <--> At the beginning of a zero finding problem, STATUS - should be set to 0 and ZROR invoked. (The value - of other parameters will be ignored on this call.) - - When ZROR needs the function evaluated, it will set - STATUS to 1 and return. The value of the function - should be set in FX and ZROR again called without - changing any of its other parameters. - - When ZROR has finished without error, it will return - with STATUS 0. In that case (XLO,XHI) bound the answe - - If ZROR finds an error (which implies that F(XLO)-Y an - F(XHI)-Y have the same sign, it returns STATUS -1. In - this case, XLO and XHI are undefined. - INTEGER STATUS - - X <-- The value of X at which F(X) is to be evaluated. - DOUBLE PRECISION X - - FX --> The value of F(X) calculated when ZROR returns with - STATUS = 1. - DOUBLE PRECISION FX - - XLO <-- When ZROR returns with STATUS = 0, XLO bounds the - inverval in X containing the solution below. - DOUBLE PRECISION XLO - - XHI <-- When ZROR returns with STATUS = 0, XHI bounds the - inverval in X containing the solution above. - DOUBLE PRECISION XHI - - QLEFT <-- .TRUE. if the stepping search terminated unsucessfully - at XLO. If it is .FALSE. the search terminated - unsucessfully at XHI. - QLEFT is LOGICAL - - QHI <-- .TRUE. if F(X) .GT. Y at the termination of the - search and .FALSE. if F(X) .LT. Y at the - termination of the search. - QHI is LOGICAL - -********************************************************************** -*/ -{ - E0001(0, status, x, fx, xlo, xhi, qleft, qhi, NULL, NULL, NULL, NULL); -} -void dstzr(double *zxlo, double *zxhi, double *zabstl, double *zreltl) -/* -********************************************************************** - void dstzr(double *zxlo,double *zxhi,double *zabstl,double *zreltl) - Double precision SeT ZeRo finder - Reverse communication version - Function - Sets quantities needed by ZROR. The function of ZROR - and the quantities set is given here. - Concise Description - Given a function F - find XLO such that F(XLO) = 0. - More Precise Description - - Input condition. F is a double precision function of a single - double precision argument and XLO and XHI are such that - F(XLO)*F(XHI) .LE. 0.0 - If the input condition is met, QRZERO returns .TRUE. - and output values of XLO and XHI satisfy the following - F(XLO)*F(XHI) .LE. 0. - ABS(F(XLO) .LE. ABS(F(XHI) - ABS(XLO-XHI) .LE. TOL(X) - where - TOL(X) = MAX(ABSTOL,RELTOL*ABS(X)) - If this algorithm does not find XLO and XHI satisfying - these conditions then QRZERO returns .FALSE. This - implies that the input condition was not met. - Arguments - XLO --> The left endpoint of the interval to be - searched for a solution. - XLO is DOUBLE PRECISION - XHI --> The right endpoint of the interval to be - for a solution. - XHI is DOUBLE PRECISION - ABSTOL, RELTOL --> Two numbers that determine the accuracy - of the solution. See function for a - precise definition. - ABSTOL is DOUBLE PRECISION - RELTOL is DOUBLE PRECISION - Method - Algorithm R of the paper 'Two Efficient Algorithms with - Guaranteed Convergence for Finding a Zero of a Function' - by J. C. P. Bus and T. J. Dekker in ACM Transactions on - Mathematical Software, Volume 1, no. 4 page 330 - (Dec. '75) is employed to find the zero of F(X)-Y. -********************************************************************** -*/ -{ - E0001(1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, zabstl, zreltl, zxhi, zxlo); -} -double erf1(double *x) -/* ------------------------------------------------------------------------ - EVALUATION OF THE REAL ERROR FUNCTION ------------------------------------------------------------------------ -*/ -{ - static double c = .564189583547756e0; - static double a[5] = { - .771058495001320e-04, -.133733772997339e-02, .323076579225834e-01, .479137145607681e-01, .128379167095513e+00}; - static double b[3] = {.301048631703895e-02, .538971687740286e-01, .375795757275549e+00}; - static double p[8] = {-1.36864857382717e-07, - 5.64195517478974e-01, - 7.21175825088309e+00, - 4.31622272220567e+01, - 1.52989285046940e+02, - 3.39320816734344e+02, - 4.51918953711873e+02, - 3.00459261020162e+02}; - static double q[8] = {1.00000000000000e+00, - 1.27827273196294e+01, - 7.70001529352295e+01, - 2.77585444743988e+02, - 6.38980264465631e+02, - 9.31354094850610e+02, - 7.90950925327898e+02, - 3.00459260956983e+02}; - static double r[5] = { - 2.10144126479064e+00, 2.62370141675169e+01, 2.13688200555087e+01, 4.65807828718470e+00, 2.82094791773523e-01}; - static double s[4] = {9.41537750555460e+01, 1.87114811799590e+02, 9.90191814623914e+01, 1.80124575948747e+01}; - static double erf1, ax, bot, t, top, x2; - /* - .. - .. Executable Statements .. - */ - ax = fabs(*x); - if (ax > 0.5e0) goto S10; - t = *x * *x; - top = (((a[0] * t + a[1]) * t + a[2]) * t + a[3]) * t + a[4] + 1.0e0; - bot = ((b[0] * t + b[1]) * t + b[2]) * t + 1.0e0; - erf1 = *x * (top / bot); - return erf1; -S10: - if (ax > 4.0e0) goto S20; - top = ((((((p[0] * ax + p[1]) * ax + p[2]) * ax + p[3]) * ax + p[4]) * ax + p[5]) * ax + p[6]) * ax + p[7]; - bot = ((((((q[0] * ax + q[1]) * ax + q[2]) * ax + q[3]) * ax + q[4]) * ax + q[5]) * ax + q[6]) * ax + q[7]; - erf1 = 0.5e0 + (0.5e0 - exp(-(*x * *x)) * top / bot); - if (*x < 0.0e0) erf1 = -erf1; - return erf1; -S20: - if (ax >= 5.8e0) goto S30; - x2 = *x * *x; - t = 1.0e0 / x2; - top = (((r[0] * t + r[1]) * t + r[2]) * t + r[3]) * t + r[4]; - bot = (((s[0] * t + s[1]) * t + s[2]) * t + s[3]) * t + 1.0e0; - erf1 = (c - top / (x2 * bot)) / ax; - erf1 = 0.5e0 + (0.5e0 - exp(-x2) * erf1); - if (*x < 0.0e0) erf1 = -erf1; - return erf1; -S30: - erf1 = fifdsign(1.0e0, *x); - return erf1; -} -double erfc1(int *ind, double *x) -/* ------------------------------------------------------------------------ - EVALUATION OF THE COMPLEMENTARY ERROR FUNCTION - - ERFC1(IND,X) = ERFC(X) IF IND = 0 - ERFC1(IND,X) = EXP(X*X)*ERFC(X) OTHERWISE ------------------------------------------------------------------------ -*/ -{ - static double c = .564189583547756e0; - static double a[5] = { - .771058495001320e-04, -.133733772997339e-02, .323076579225834e-01, .479137145607681e-01, .128379167095513e+00}; - static double b[3] = {.301048631703895e-02, .538971687740286e-01, .375795757275549e+00}; - static double p[8] = {-1.36864857382717e-07, - 5.64195517478974e-01, - 7.21175825088309e+00, - 4.31622272220567e+01, - 1.52989285046940e+02, - 3.39320816734344e+02, - 4.51918953711873e+02, - 3.00459261020162e+02}; - static double q[8] = {1.00000000000000e+00, - 1.27827273196294e+01, - 7.70001529352295e+01, - 2.77585444743988e+02, - 6.38980264465631e+02, - 9.31354094850610e+02, - 7.90950925327898e+02, - 3.00459260956983e+02}; - static double r[5] = { - 2.10144126479064e+00, 2.62370141675169e+01, 2.13688200555087e+01, 4.65807828718470e+00, 2.82094791773523e-01}; - static double s[4] = {9.41537750555460e+01, 1.87114811799590e+02, 9.90191814623914e+01, 1.80124575948747e+01}; - static int K1 = 1; - static double erfc1, ax, bot, e, t, top, w; - /* - .. - .. Executable Statements .. - */ - /* - ABS(X) .LE. 0.5 - */ - ax = fabs(*x); - if (ax > 0.5e0) goto S10; - t = *x * *x; - top = (((a[0] * t + a[1]) * t + a[2]) * t + a[3]) * t + a[4] + 1.0e0; - bot = ((b[0] * t + b[1]) * t + b[2]) * t + 1.0e0; - erfc1 = 0.5e0 + (0.5e0 - *x * (top / bot)); - if (*ind != 0) erfc1 = exp(t) * erfc1; - return erfc1; -S10: - /* - 0.5 .LT. ABS(X) .LE. 4 - */ - if (ax > 4.0e0) goto S20; - top = ((((((p[0] * ax + p[1]) * ax + p[2]) * ax + p[3]) * ax + p[4]) * ax + p[5]) * ax + p[6]) * ax + p[7]; - bot = ((((((q[0] * ax + q[1]) * ax + q[2]) * ax + q[3]) * ax + q[4]) * ax + q[5]) * ax + q[6]) * ax + q[7]; - erfc1 = top / bot; - goto S40; -S20: - /* - ABS(X) .GT. 4 - */ - if (*x <= -5.6e0) goto S60; - if (*ind != 0) goto S30; - if (*x > 100.0e0) goto S70; - if (*x * *x > -exparg(&K1)) goto S70; -S30: - t = pow(1.0e0 / *x, 2.0); - top = (((r[0] * t + r[1]) * t + r[2]) * t + r[3]) * t + r[4]; - bot = (((s[0] * t + s[1]) * t + s[2]) * t + s[3]) * t + 1.0e0; - erfc1 = (c - t * top / bot) / ax; -S40: - /* - FINAL ASSEMBLY - */ - if (*ind == 0) goto S50; - if (*x < 0.0e0) erfc1 = 2.0e0 * exp(*x * *x) - erfc1; - return erfc1; -S50: - w = *x * *x; - t = w; - e = w - t; - erfc1 = (0.5e0 + (0.5e0 - e)) * exp(-t) * erfc1; - if (*x < 0.0e0) erfc1 = 2.0e0 - erfc1; - return erfc1; -S60: - /* - LIMIT VALUE FOR LARGE NEGATIVE X - */ - erfc1 = 2.0e0; - if (*ind != 0) erfc1 = 2.0e0 * exp(*x * *x); - return erfc1; -S70: - /* - LIMIT VALUE FOR LARGE POSITIVE X - WHEN IND = 0 - */ - erfc1 = 0.0e0; - return erfc1; -} -double esum(int *mu, double *x) -/* ------------------------------------------------------------------------ - EVALUATION OF EXP(MU + X) ------------------------------------------------------------------------ -*/ -{ - static double esum, w; - /* - .. - .. Executable Statements .. - */ - if (*x > 0.0e0) goto S10; - if (*mu < 0) goto S20; - w = (double)*mu + *x; - if (w > 0.0e0) goto S20; - esum = exp(w); - return esum; -S10: - if (*mu > 0) goto S20; - w = (double)*mu + *x; - if (w < 0.0e0) goto S20; - esum = exp(w); - return esum; -S20: - w = *mu; - esum = exp(w) * exp(*x); - return esum; -} -double exparg(int *l) -/* --------------------------------------------------------------------- - IF L = 0 THEN EXPARG(L) = THE LARGEST POSITIVE W FOR WHICH - EXP(W) CAN BE COMPUTED. - - IF L IS NONZERO THEN EXPARG(L) = THE LARGEST NEGATIVE W FOR - WHICH THE COMPUTED VALUE OF EXP(W) IS NONZERO. - - NOTE... ONLY AN APPROXIMATE VALUE FOR EXPARG(L) IS NEEDED. --------------------------------------------------------------------- -*/ -{ - static int K1 = 4; - static int K2 = 9; - static int K3 = 10; - static double exparg, lnb; - static int b, m; - /* - .. - .. Executable Statements .. - */ - b = ipmpar(&K1); - if (b != 2) goto S10; - lnb = .69314718055995e0; - goto S40; -S10: - if (b != 8) goto S20; - lnb = 2.0794415416798e0; - goto S40; -S20: - if (b != 16) goto S30; - lnb = 2.7725887222398e0; - goto S40; -S30: - lnb = log((double)b); -S40: - if (*l == 0) goto S50; - m = ipmpar(&K2) - 1; - exparg = 0.99999e0 * ((double)m * lnb); - return exparg; -S50: - m = ipmpar(&K3); - exparg = 0.99999e0 * ((double)m * lnb); - return exparg; -} -double fpser(double *a, double *b, double *x, double *eps) -/* ------------------------------------------------------------------------ - - EVALUATION OF I (A,B) - X - - FOR B .LT. MIN(EPS,EPS*A) AND X .LE. 0.5. - ------------------------------------------------------------------------ - - SET FPSER = X**A -*/ -{ - static int K1 = 1; - static double fpser, an, c, s, t, tol; - /* - .. - .. Executable Statements .. - */ - fpser = 1.0e0; - if (*a <= 1.e-3 * *eps) goto S10; - fpser = 0.0e0; - t = *a * log(*x); - if (t < exparg(&K1)) return fpser; - fpser = exp(t); -S10: - /* - NOTE THAT 1/B(A,B) = B - */ - fpser = *b / *a * fpser; - tol = *eps / *a; - an = *a + 1.0e0; - t = *x; - s = t / an; -S20: - an += 1.0e0; - t = *x * t; - c = t / an; - s += c; - if (fabs(c) > tol) goto S20; - fpser *= (1.0e0 + *a * s); - return fpser; -} -double gam1(double *a) -/* - ------------------------------------------------------------------ - COMPUTATION OF 1/GAMMA(A+1) - 1 FOR -0.5 .LE. A .LE. 1.5 - ------------------------------------------------------------------ -*/ -{ - static double s1 = .273076135303957e+00; - static double s2 = .559398236957378e-01; - static double p[7] = {.577215664901533e+00, - -.409078193005776e+00, - -.230975380857675e+00, - .597275330452234e-01, - .766968181649490e-02, - -.514889771323592e-02, - .589597428611429e-03}; - static double q[5] = { - .100000000000000e+01, .427569613095214e+00, .158451672430138e+00, .261132021441447e-01, .423244297896961e-02}; - static double r[9] = {-.422784335098468e+00, - -.771330383816272e+00, - -.244757765222226e+00, - .118378989872749e+00, - .930357293360349e-03, - -.118290993445146e-01, - .223047661158249e-02, - .266505979058923e-03, - -.132674909766242e-03}; - static double gam1, bot, d, t, top, w, T1; - /* - .. - .. Executable Statements .. - */ - t = *a; - d = *a - 0.5e0; - if (d > 0.0e0) t = d - 0.5e0; - T1 = t; - if (T1 < 0) - goto S40; - else if (T1 == 0) - goto S10; - else - goto S20; -S10: - gam1 = 0.0e0; - return gam1; -S20: - top = (((((p[6] * t + p[5]) * t + p[4]) * t + p[3]) * t + p[2]) * t + p[1]) * t + p[0]; - bot = (((q[4] * t + q[3]) * t + q[2]) * t + q[1]) * t + 1.0e0; - w = top / bot; - if (d > 0.0e0) goto S30; - gam1 = *a * w; - return gam1; -S30: - gam1 = t / *a * (w - 0.5e0 - 0.5e0); - return gam1; -S40: - top = (((((((r[8] * t + r[7]) * t + r[6]) * t + r[5]) * t + r[4]) * t + r[3]) * t + r[2]) * t + r[1]) * t + r[0]; - bot = (s2 * t + s1) * t + 1.0e0; - w = top / bot; - if (d > 0.0e0) goto S50; - gam1 = *a * (w + 0.5e0 + 0.5e0); - return gam1; -S50: - gam1 = t * w / *a; - return gam1; -} -void gaminv(double *a, double *x, double *x0, double *p, double *q, int *ierr) -/* - ---------------------------------------------------------------------- - INVERSE INCOMPLETE GAMMA RATIO FUNCTION - - GIVEN POSITIVE A, AND NONEGATIVE P AND Q WHERE P + Q = 1. - THEN X IS COMPUTED WHERE P(A,X) = P AND Q(A,X) = Q. SCHRODER - ITERATION IS EMPLOYED. THE ROUTINE ATTEMPTS TO COMPUTE X - TO 10 SIGNIFICANT DIGITS IF THIS IS POSSIBLE FOR THE - PARTICULAR COMPUTER ARITHMETIC BEING USED. - - ------------ - - X IS A VARIABLE. IF P = 0 THEN X IS ASSIGNED THE VALUE 0, - AND IF Q = 0 THEN X IS SET TO THE LARGEST FLOATING POINT - NUMBER AVAILABLE. OTHERWISE, GAMINV ATTEMPTS TO OBTAIN - A SOLUTION FOR P(A,X) = P AND Q(A,X) = Q. IF THE ROUTINE - IS SUCCESSFUL THEN THE SOLUTION IS STORED IN X. - - X0 IS AN OPTIONAL INITIAL APPROXIMATION FOR X. IF THE USER - DOES NOT WISH TO SUPPLY AN INITIAL APPROXIMATION, THEN SET - X0 .LE. 0. - - IERR IS A VARIABLE THAT REPORTS THE STATUS OF THE RESULTS. - WHEN THE ROUTINE TERMINATES, IERR HAS ONE OF THE FOLLOWING - VALUES ... - - IERR = 0 THE SOLUTION WAS OBTAINED. ITERATION WAS - NOT USED. - IERR.GT.0 THE SOLUTION WAS OBTAINED. IERR ITERATIONS - WERE PERFORMED. - IERR = -2 (INPUT ERROR) A .LE. 0 - IERR = -3 NO SOLUTION WAS OBTAINED. THE RATIO Q/A - IS TOO LARGE. - IERR = -4 (INPUT ERROR) P + Q .NE. 1 - IERR = -6 20 ITERATIONS WERE PERFORMED. THE MOST - RECENT VALUE OBTAINED FOR X IS GIVEN. - THIS CANNOT OCCUR IF X0 .LE. 0. - IERR = -7 ITERATION FAILED. NO VALUE IS GIVEN FOR X. - THIS MAY OCCUR WHEN X IS APPROXIMATELY 0. - IERR = -8 A VALUE FOR X HAS BEEN OBTAINED, BUT THE - ROUTINE IS NOT CERTAIN OF ITS ACCURACY. - ITERATION CANNOT BE PERFORMED IN THIS - CASE. IF X0 .LE. 0, THIS CAN OCCUR ONLY - WHEN P OR Q IS APPROXIMATELY 0. IF X0 IS - POSITIVE THEN THIS CAN OCCUR WHEN A IS - EXCEEDINGLY CLOSE TO X AND A IS EXTREMELY - LARGE (SAY A .GE. 1.E20). - ---------------------------------------------------------------------- - WRITTEN BY ALFRED H. MORRIS, JR. - NAVAL SURFACE WEAPONS CENTER - DAHLGREN, VIRGINIA - ------------------- -*/ -{ - static double a0 = 3.31125922108741e0; - static double a1 = 11.6616720288968e0; - static double a2 = 4.28342155967104e0; - static double a3 = .213623493715853e0; - static double b1 = 6.61053765625462e0; - static double b2 = 6.40691597760039e0; - static double b3 = 1.27364489782223e0; - static double b4 = .036117081018842e0; - static double c = .577215664901533e0; - static double ln10 = 2.302585e0; - static double tol = 1.e-5; - static double amin[2] = {500.0e0, 100.0e0}; - static double bmin[2] = {1.e-28, 1.e-13}; - static double dmin[2] = {1.e-06, 1.e-04}; - static double emin[2] = {2.e-03, 6.e-03}; - static double eps0[2] = {1.e-10, 1.e-08}; - static int K1 = 1; - static int K2 = 2; - static int K3 = 3; - static int K8 = 0; - static double am1, amax, ap1, ap2, ap3, apn, b, c1, c2, c3, c4, c5, d, e, e2, eps, g, h, pn, qg, qn, r, rta, s, s2, - sum, t, u, w, xmax, xmin, xn, y, z; - static int iop; - static double T4, T5, T6, T7, T9; - /* - .. - .. Executable Statements .. - */ - /* - ****** E, XMIN, AND XMAX ARE MACHINE DEPENDENT CONSTANTS. - E IS THE SMALLEST NUMBER FOR WHICH 1.0 + E .GT. 1.0. - XMIN IS THE SMALLEST POSITIVE NUMBER AND XMAX IS THE - LARGEST POSITIVE NUMBER. - */ - e = spmpar(&K1); - xmin = spmpar(&K2); - xmax = spmpar(&K3); - *x = 0.0e0; - if (*a <= 0.0e0) goto S300; - t = *p + *q - 1.e0; - if (fabs(t) > e) goto S320; - *ierr = 0; - if (*p == 0.0e0) return; - if (*q == 0.0e0) goto S270; - if (*a == 1.0e0) goto S280; - e2 = 2.0e0 * e; - amax = 0.4e-10 / (e * e); - iop = 1; - if (e > 1.e-10) iop = 2; - eps = eps0[iop - 1]; - xn = *x0; - if (*x0 > 0.0e0) goto S160; - /* - SELECTION OF THE INITIAL APPROXIMATION XN OF X - WHEN A .LT. 1 - */ - if (*a > 1.0e0) goto S80; - T4 = *a + 1.0e0; - g = Xgamm(&T4); - qg = *q * g; - if (qg == 0.0e0) goto S360; - b = qg / *a; - if (qg > 0.6e0 * *a) goto S40; - if (*a >= 0.30e0 || b < 0.35e0) goto S10; - t = exp(-(b + c)); - u = t * exp(t); - xn = t * exp(u); - goto S160; -S10: - if (b >= 0.45e0) goto S40; - if (b == 0.0e0) goto S360; - y = -log(b); - s = 0.5e0 + (0.5e0 - *a); - z = log(y); - t = y - s * z; - if (b < 0.15e0) goto S20; - xn = y - s * log(t) - log(1.0e0 + s / (t + 1.0e0)); - goto S220; -S20: - if (b <= 0.01e0) goto S30; - u = ((t + 2.0e0 * (3.0e0 - *a)) * t + (2.0e0 - *a) * (3.0e0 - *a)) / ((t + (5.0e0 - *a)) * t + 2.0e0); - xn = y - s * log(t) - log(u); - goto S220; -S30: - c1 = -(s * z); - c2 = -(s * (1.0e0 + c1)); - c3 = s * ((0.5e0 * c1 + (2.0e0 - *a)) * c1 + (2.5e0 - 1.5e0 * *a)); - c4 = -(s * (((c1 / 3.0e0 + (2.5e0 - 1.5e0 * *a)) * c1 + ((*a - 6.0e0) * *a + 7.0e0)) * c1 + - ((11.0e0 * *a - 46.0) * *a + 47.0e0) / 6.0e0)); - c5 = -(s * ((((-(c1 / 4.0e0) + (11.0e0 * *a - 17.0e0) / 6.0e0) * c1 + ((-(3.0e0 * *a) + 13.0e0) * *a - 13.0e0)) * c1 + - 0.5e0 * (((2.0e0 * *a - 25.0e0) * *a + 72.0e0) * *a - 61.0e0)) * - c1 + - (((25.0e0 * *a - 195.0e0) * *a + 477.0e0) * *a - 379.0e0) / 12.0e0)); - xn = (((c5 / y + c4) / y + c3) / y + c2) / y + c1 + y; - if (*a > 1.0e0) goto S220; - if (b > bmin[iop - 1]) goto S220; - *x = xn; - return; -S40: - if (b * *q > 1.e-8) goto S50; - xn = exp(-(*q / *a + c)); - goto S70; -S50: - if (*p <= 0.9e0) goto S60; - T5 = -*q; - xn = exp((alnrel(&T5) + gamln1(a)) / *a); - goto S70; -S60: - xn = exp(log(*p * g) / *a); -S70: - if (xn == 0.0e0) goto S310; - t = 0.5e0 + (0.5e0 - xn / (*a + 1.0e0)); - xn /= t; - goto S160; -S80: - /* - SELECTION OF THE INITIAL APPROXIMATION XN OF X - WHEN A .GT. 1 - */ - if (*q <= 0.5e0) goto S90; - w = log(*p); - goto S100; -S90: - w = log(*q); -S100: - t = sqrt(-(2.0e0 * w)); - s = t - (((a3 * t + a2) * t + a1) * t + a0) / ((((b4 * t + b3) * t + b2) * t + b1) * t + 1.0e0); - if (*q > 0.5e0) s = -s; - rta = sqrt(*a); - s2 = s * s; - xn = *a + s * rta + (s2 - 1.0e0) / 3.0e0 + s * (s2 - 7.0e0) / (36.0e0 * rta) - - ((3.0e0 * s2 + 7.0e0) * s2 - 16.0e0) / (810.0e0 * *a) + - s * ((9.0e0 * s2 + 256.0e0) * s2 - 433.0e0) / (38880.0e0 * *a * rta); - xn = fifdmax1(xn, 0.0e0); - if (*a < amin[iop - 1]) goto S110; - *x = xn; - d = 0.5e0 + (0.5e0 - *x / *a); - if (fabs(d) <= dmin[iop - 1]) return; -S110: - if (*p <= 0.5e0) goto S130; - if (xn < 3.0e0 * *a) goto S220; - y = -(w + gamln(a)); - d = fifdmax1(2.0e0, *a * (*a - 1.0e0)); - if (y < ln10 * d) goto S120; - s = 1.0e0 - *a; - z = log(y); - goto S30; -S120: - t = *a - 1.0e0; - T6 = -(t / (xn + 1.0e0)); - xn = y + t * log(xn) - alnrel(&T6); - T7 = -(t / (xn + 1.0e0)); - xn = y + t * log(xn) - alnrel(&T7); - goto S220; -S130: - ap1 = *a + 1.0e0; - if (xn > 0.70e0 * ap1) goto S170; - w += gamln(&ap1); - if (xn > 0.15e0 * ap1) goto S140; - ap2 = *a + 2.0e0; - ap3 = *a + 3.0e0; - *x = exp((w + *x) / *a); - *x = exp((w + *x - log(1.0e0 + *x / ap1 * (1.0e0 + *x / ap2))) / *a); - *x = exp((w + *x - log(1.0e0 + *x / ap1 * (1.0e0 + *x / ap2))) / *a); - *x = exp((w + *x - log(1.0e0 + *x / ap1 * (1.0e0 + *x / ap2 * (1.0e0 + *x / ap3)))) / *a); - xn = *x; - if (xn > 1.e-2 * ap1) goto S140; - if (xn <= emin[iop - 1] * ap1) return; - goto S170; -S140: - apn = ap1; - t = xn / apn; - sum = 1.0e0 + t; -S150: - apn += 1.0e0; - t *= (xn / apn); - sum += t; - if (t > 1.e-4) goto S150; - t = w - log(sum); - xn = exp((xn + t) / *a); - xn *= (1.0e0 - (*a * log(xn) - xn - t) / (*a - xn)); - goto S170; -S160: - /* - SCHRODER ITERATION USING P - */ - if (*p > 0.5e0) goto S220; -S170: - if (*p <= 1.e10 * xmin) goto S350; - am1 = *a - 0.5e0 - 0.5e0; -S180: - if (*a <= amax) goto S190; - d = 0.5e0 + (0.5e0 - xn / *a); - if (fabs(d) <= e2) goto S350; -S190: - if (*ierr >= 20) goto S330; - *ierr += 1; - gratio(a, &xn, &pn, &qn, &K8); - if (pn == 0.0e0 || qn == 0.0e0) goto S350; - r = rcomp(a, &xn); - if (r == 0.0e0) goto S350; - t = (pn - *p) / r; - w = 0.5e0 * (am1 - xn); - if (fabs(t) <= 0.1e0 && fabs(w * t) <= 0.1e0) goto S200; - *x = xn * (1.0e0 - t); - if (*x <= 0.0e0) goto S340; - d = fabs(t); - goto S210; -S200: - h = t * (1.0e0 + w * t); - *x = xn * (1.0e0 - h); - if (*x <= 0.0e0) goto S340; - if (fabs(w) >= 1.0e0 && fabs(w) * t * t <= eps) return; - d = fabs(h); -S210: - xn = *x; - if (d > tol) goto S180; - if (d <= eps) return; - if (fabs(*p - pn) <= tol * *p) return; - goto S180; -S220: - /* - SCHRODER ITERATION USING Q - */ - if (*q <= 1.e10 * xmin) goto S350; - am1 = *a - 0.5e0 - 0.5e0; -S230: - if (*a <= amax) goto S240; - d = 0.5e0 + (0.5e0 - xn / *a); - if (fabs(d) <= e2) goto S350; -S240: - if (*ierr >= 20) goto S330; - *ierr += 1; - gratio(a, &xn, &pn, &qn, &K8); - if (pn == 0.0e0 || qn == 0.0e0) goto S350; - r = rcomp(a, &xn); - if (r == 0.0e0) goto S350; - t = (*q - qn) / r; - w = 0.5e0 * (am1 - xn); - if (fabs(t) <= 0.1e0 && fabs(w * t) <= 0.1e0) goto S250; - *x = xn * (1.0e0 - t); - if (*x <= 0.0e0) goto S340; - d = fabs(t); - goto S260; -S250: - h = t * (1.0e0 + w * t); - *x = xn * (1.0e0 - h); - if (*x <= 0.0e0) goto S340; - if (fabs(w) >= 1.0e0 && fabs(w) * t * t <= eps) return; - d = fabs(h); -S260: - xn = *x; - if (d > tol) goto S230; - if (d <= eps) return; - if (fabs(*q - qn) <= tol * *q) return; - goto S230; -S270: - /* - SPECIAL CASES - */ - *x = xmax; - return; -S280: - if (*q < 0.9e0) goto S290; - T9 = -*p; - *x = -alnrel(&T9); - return; -S290: - *x = -log(*q); - return; -S300: - /* - ERROR RETURN - */ - *ierr = -2; - return; -S310: - *ierr = -3; - return; -S320: - *ierr = -4; - return; -S330: - *ierr = -6; - return; -S340: - *ierr = -7; - return; -S350: - *x = xn; - *ierr = -8; - return; -S360: - *x = xmax; - *ierr = -8; - return; -} -double gamln(double *a) -/* ------------------------------------------------------------------------ - EVALUATION OF LN(GAMMA(A)) FOR POSITIVE A ------------------------------------------------------------------------ - WRITTEN BY ALFRED H. MORRIS - NAVAL SURFACE WARFARE CENTER - DAHLGREN, VIRGINIA --------------------------- - D = 0.5*(LN(2*PI) - 1) --------------------------- -*/ -{ - static double c0 = .833333333333333e-01; - static double c1 = -.277777777760991e-02; - static double c2 = .793650666825390e-03; - static double c3 = -.595202931351870e-03; - static double c4 = .837308034031215e-03; - static double c5 = -.165322962780713e-02; - static double d = .418938533204673e0; - static double gamln, t, w; - static int i, n; - static double T1; - /* - .. - .. Executable Statements .. - */ - if (*a > 0.8e0) goto S10; - gamln = gamln1(a) - log(*a); - return gamln; -S10: - if (*a > 2.25e0) goto S20; - t = *a - 0.5e0 - 0.5e0; - gamln = gamln1(&t); - return gamln; -S20: - if (*a >= 10.0e0) goto S40; - n = (long)(*a - 1.25e0); - t = *a; - w = 1.0e0; - for (i = 1; i <= n; i++) { - t -= 1.0e0; - w = t * w; - } - T1 = t - 1.0e0; - gamln = gamln1(&T1) + log(w); - return gamln; -S40: - t = pow(1.0e0 / *a, 2.0); - w = (((((c5 * t + c4) * t + c3) * t + c2) * t + c1) * t + c0) / *a; - gamln = d + w + (*a - 0.5e0) * (log(*a) - 1.0e0); - return gamln; -} -double gamln1(double *a) -/* ------------------------------------------------------------------------ - EVALUATION OF LN(GAMMA(1 + A)) FOR -0.2 .LE. A .LE. 1.25 ------------------------------------------------------------------------ -*/ -{ - static double p0 = .577215664901533e+00; - static double p1 = .844203922187225e+00; - static double p2 = -.168860593646662e+00; - static double p3 = -.780427615533591e+00; - static double p4 = -.402055799310489e+00; - static double p5 = -.673562214325671e-01; - static double p6 = -.271935708322958e-02; - static double q1 = .288743195473681e+01; - static double q2 = .312755088914843e+01; - static double q3 = .156875193295039e+01; - static double q4 = .361951990101499e+00; - static double q5 = .325038868253937e-01; - static double q6 = .667465618796164e-03; - static double r0 = .422784335098467e+00; - static double r1 = .848044614534529e+00; - static double r2 = .565221050691933e+00; - static double r3 = .156513060486551e+00; - static double r4 = .170502484022650e-01; - static double r5 = .497958207639485e-03; - static double s1 = .124313399877507e+01; - static double s2 = .548042109832463e+00; - static double s3 = .101552187439830e+00; - static double s4 = .713309612391000e-02; - static double s5 = .116165475989616e-03; - static double gamln1, w, x; - /* - .. - .. Executable Statements .. - */ - if (*a >= 0.6e0) goto S10; - w = ((((((p6 * *a + p5) * *a + p4) * *a + p3) * *a + p2) * *a + p1) * *a + p0) / - ((((((q6 * *a + q5) * *a + q4) * *a + q3) * *a + q2) * *a + q1) * *a + 1.0e0); - gamln1 = -(*a * w); - return gamln1; -S10: - x = *a - 0.5e0 - 0.5e0; - w = (((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x + r0) / - (((((s5 * x + s4) * x + s3) * x + s2) * x + s1) * x + 1.0e0); - gamln1 = x * w; - return gamln1; -} -double Xgamm(double *a) -/* ------------------------------------------------------------------------ - - EVALUATION OF THE GAMMA FUNCTION FOR REAL ARGUMENTS - - ----------- - - GAMMA(A) IS ASSIGNED THE VALUE 0 WHEN THE GAMMA FUNCTION CANNOT - BE COMPUTED. - ------------------------------------------------------------------------ - WRITTEN BY ALFRED H. MORRIS, JR. - NAVAL SURFACE WEAPONS CENTER - DAHLGREN, VIRGINIA ------------------------------------------------------------------------ -*/ -{ - static double d = .41893853320467274178e0; - static double pi = 3.1415926535898e0; - static double r1 = .820756370353826e-03; - static double r2 = -.595156336428591e-03; - static double r3 = .793650663183693e-03; - static double r4 = -.277777777770481e-02; - static double r5 = .833333333333333e-01; - static double p[7] = {.539637273585445e-03, - .261939260042690e-02, - .204493667594920e-01, - .730981088720487e-01, - .279648642639792e+00, - .553413866010467e+00, - 1.0e0}; - static double q[7] = {-.832979206704073e-03, - .470059485860584e-02, - .225211131035340e-01, - -.170458969313360e+00, - -.567902761974940e-01, - .113062953091122e+01, - 1.0e0}; - static int K2 = 3; - static int K3 = 0; - static double Xgamm, bot, g, lnx, s, t, top, w, x, z; - static int i, j, m, n, T1; - /* - .. - .. Executable Statements .. - */ - Xgamm = 0.0e0; - x = *a; - if (fabs(*a) >= 15.0e0) goto S110; - /* - ----------------------------------------------------------------------- - EVALUATION OF GAMMA(A) FOR ABS(A) .LT. 15 - ----------------------------------------------------------------------- - */ - t = 1.0e0; - m = fifidint(*a) - 1; - /* - LET T BE THE PRODUCT OF A-J WHEN A .GE. 2 - */ - T1 = m; - if (T1 < 0) - goto S40; - else if (T1 == 0) - goto S30; - else - goto S10; -S10: - for (j = 1; j <= m; j++) { - x -= 1.0e0; - t = x * t; - } -S30: - x -= 1.0e0; - goto S80; -S40: - /* - LET T BE THE PRODUCT OF A+J WHEN A .LT. 1 - */ - t = *a; - if (*a > 0.0e0) goto S70; - m = -m - 1; - if (m == 0) goto S60; - for (j = 1; j <= m; j++) { - x += 1.0e0; - t = x * t; - } -S60: - x += (0.5e0 + 0.5e0); - t = x * t; - if (t == 0.0e0) return Xgamm; -S70: - /* - THE FOLLOWING CODE CHECKS IF 1/T CAN OVERFLOW. THIS - CODE MAY BE OMITTED IF DESIRED. - */ - if (fabs(t) >= 1.e-30) goto S80; - if (fabs(t) * spmpar(&K2) <= 1.0001e0) return Xgamm; - Xgamm = 1.0e0 / t; - return Xgamm; -S80: - /* - COMPUTE GAMMA(1 + X) FOR 0 .LE. X .LT. 1 - */ - top = p[0]; - bot = q[0]; - for (i = 1; i < 7; i++) { - top = p[i] + x * top; - bot = q[i] + x * bot; - } - Xgamm = top / bot; - /* - TERMINATION - */ - if (*a < 1.0e0) goto S100; - Xgamm *= t; - return Xgamm; -S100: - Xgamm /= t; - return Xgamm; -S110: - /* - ----------------------------------------------------------------------- - EVALUATION OF GAMMA(A) FOR ABS(A) .GE. 15 - ----------------------------------------------------------------------- - */ - if (fabs(*a) >= 1.e3) return Xgamm; - if (*a > 0.0e0) goto S120; - x = -*a; - n = (long)(x); - t = x - (double)n; - if (t > 0.9e0) t = 1.0e0 - t; - s = sin(pi * t) / pi; - if (fifmod(n, 2) == 0) s = -s; - if (s == 0.0e0) return Xgamm; -S120: - /* - COMPUTE THE MODIFIED ASYMPTOTIC SUM - */ - t = 1.0e0 / (x * x); - g = ((((r1 * t + r2) * t + r3) * t + r4) * t + r5) / x; - /* - ONE MAY REPLACE THE NEXT STATEMENT WITH LNX = ALOG(X) - BUT LESS ACCURACY WILL NORMALLY BE OBTAINED. - */ - lnx = log(x); - /* - FINAL ASSEMBLY - */ - z = x; - g = d + g + (z - 0.5e0) * (lnx - 1.e0); - w = g; - t = g - w; - if (w > 0.99999e0 * exparg(&K3)) return Xgamm; - Xgamm = exp(w) * (1.0e0 + t); - if (*a < 0.0e0) Xgamm = 1.0e0 / (Xgamm * s) / x; - return Xgamm; -} -void grat1(double *a, double *x, double *r, double *p, double *q, double *eps) -{ - static int K2 = 0; - static double a2n, a2nm1, am0, an, an0, b2n, b2nm1, c, cma, g, h, j, l, sum, t, tol, w, z, T1, T3; - /* - .. - .. Executable Statements .. - */ - /* - ----------------------------------------------------------------------- - EVALUATION OF THE INCOMPLETE GAMMA RATIO FUNCTIONS - P(A,X) AND Q(A,X) - IT IS ASSUMED THAT A .LE. 1. EPS IS THE TOLERANCE TO BE USED. - THE INPUT ARGUMENT R HAS THE VALUE E**(-X)*X**A/GAMMA(A). - ----------------------------------------------------------------------- - */ - if (*a * *x == 0.0e0) goto S120; - if (*a == 0.5e0) goto S100; - if (*x < 1.1e0) goto S10; - goto S60; -S10: - /* - TAYLOR SERIES FOR P(A,X)/X**A - */ - an = 3.0e0; - c = *x; - sum = *x / (*a + 3.0e0); - tol = 0.1e0 * *eps / (*a + 1.0e0); -S20: - an += 1.0e0; - c = -(c * (*x / an)); - t = c / (*a + an); - sum += t; - if (fabs(t) > tol) goto S20; - j = *a * *x * ((sum / 6.0e0 - 0.5e0 / (*a + 2.0e0)) * *x + 1.0e0 / (*a + 1.0e0)); - z = *a * log(*x); - h = gam1(a); - g = 1.0e0 + h; - if (*x < 0.25e0) goto S30; - if (*a < *x / 2.59e0) goto S50; - goto S40; -S30: - if (z > -.13394e0) goto S50; -S40: - w = exp(z); - *p = w * g * (0.5e0 + (0.5e0 - j)); - *q = 0.5e0 + (0.5e0 - *p); - return; -S50: - l = rexp(&z); - w = 0.5e0 + (0.5e0 + l); - *q = (w * j - l) * g - h; - if (*q < 0.0e0) goto S90; - *p = 0.5e0 + (0.5e0 - *q); - return; -S60: - /* - CONTINUED FRACTION EXPANSION - */ - a2nm1 = a2n = 1.0e0; - b2nm1 = *x; - b2n = *x + (1.0e0 - *a); - c = 1.0e0; -S70: - a2nm1 = *x * a2n + c * a2nm1; - b2nm1 = *x * b2n + c * b2nm1; - am0 = a2nm1 / b2nm1; - c += 1.0e0; - cma = c - *a; - a2n = a2nm1 + cma * a2n; - b2n = b2nm1 + cma * b2n; - an0 = a2n / b2n; - if (fabs(an0 - am0) >= *eps * an0) goto S70; - *q = *r * an0; - *p = 0.5e0 + (0.5e0 - *q); - return; -S80: - /* - SPECIAL CASES - */ - *p = 0.0e0; - *q = 1.0e0; - return; -S90: - *p = 1.0e0; - *q = 0.0e0; - return; -S100: - if (*x >= 0.25e0) goto S110; - T1 = sqrt(*x); - *p = erf1(&T1); - *q = 0.5e0 + (0.5e0 - *p); - return; -S110: - T3 = sqrt(*x); - *q = erfc1(&K2, &T3); - *p = 0.5e0 + (0.5e0 - *q); - return; -S120: - if (*x <= *a) goto S80; - goto S90; -} -void gratio(double *a, double *x, double *ans, double *qans, int *ind) -/* - ---------------------------------------------------------------------- - EVALUATION OF THE INCOMPLETE GAMMA RATIO FUNCTIONS - P(A,X) AND Q(A,X) - - ---------- - - IT IS ASSUMED THAT A AND X ARE NONNEGATIVE, WHERE A AND X - ARE NOT BOTH 0. - - ANS AND QANS ARE VARIABLES. GRATIO ASSIGNS ANS THE VALUE - P(A,X) AND QANS THE VALUE Q(A,X). IND MAY BE ANY INTEGER. - IF IND = 0 THEN THE USER IS REQUESTING AS MUCH ACCURACY AS - POSSIBLE (UP TO 14 SIGNIFICANT DIGITS). OTHERWISE, IF - IND = 1 THEN ACCURACY IS REQUESTED TO WITHIN 1 UNIT OF THE - 6-TH SIGNIFICANT DIGIT, AND IF IND .NE. 0,1 THEN ACCURACY - IS REQUESTED TO WITHIN 1 UNIT OF THE 3RD SIGNIFICANT DIGIT. - - ERROR RETURN ... - ANS IS ASSIGNED THE VALUE 2 WHEN A OR X IS NEGATIVE, - WHEN A*X = 0, OR WHEN P(A,X) AND Q(A,X) ARE INDETERMINANT. - P(A,X) AND Q(A,X) ARE COMPUTATIONALLY INDETERMINANT WHEN - X IS EXCEEDINGLY CLOSE TO A AND A IS EXTREMELY LARGE. - ---------------------------------------------------------------------- - WRITTEN BY ALFRED H. MORRIS, JR. - NAVAL SURFACE WEAPONS CENTER - DAHLGREN, VIRGINIA - -------------------- -*/ -{ - static double alog10 = 2.30258509299405e0; - static double d10 = -.185185185185185e-02; - static double d20 = .413359788359788e-02; - static double d30 = .649434156378601e-03; - static double d40 = -.861888290916712e-03; - static double d50 = -.336798553366358e-03; - static double d60 = .531307936463992e-03; - static double d70 = .344367606892378e-03; - static double rt2pin = .398942280401433e0; - static double rtpi = 1.77245385090552e0; - static double third = .333333333333333e0; - static double acc0[3] = {5.e-15, 5.e-7, 5.e-4}; - static double big[3] = {20.0e0, 14.0e0, 10.0e0}; - static double d0[13] = {.833333333333333e-01, - -.148148148148148e-01, - .115740740740741e-02, - .352733686067019e-03, - -.178755144032922e-03, - .391926317852244e-04, - -.218544851067999e-05, - -.185406221071516e-05, - .829671134095309e-06, - -.176659527368261e-06, - .670785354340150e-08, - .102618097842403e-07, - -.438203601845335e-08}; - static double d1[12] = {-.347222222222222e-02, - .264550264550265e-02, - -.990226337448560e-03, - .205761316872428e-03, - -.401877572016461e-06, - -.180985503344900e-04, - .764916091608111e-05, - -.161209008945634e-05, - .464712780280743e-08, - .137863344691572e-06, - -.575254560351770e-07, - .119516285997781e-07}; - static double d2[10] = {-.268132716049383e-02, - .771604938271605e-03, - .200938786008230e-05, - -.107366532263652e-03, - .529234488291201e-04, - -.127606351886187e-04, - .342357873409614e-07, - .137219573090629e-05, - -.629899213838006e-06, - .142806142060642e-06}; - static double d3[8] = {.229472093621399e-03, - -.469189494395256e-03, - .267720632062839e-03, - -.756180167188398e-04, - -.239650511386730e-06, - .110826541153473e-04, - -.567495282699160e-05, - .142309007324359e-05}; - static double d4[6] = {.784039221720067e-03, - -.299072480303190e-03, - -.146384525788434e-05, - .664149821546512e-04, - -.396836504717943e-04, - .113757269706784e-04}; - static double d5[4] = {-.697281375836586e-04, .277275324495939e-03, -.199325705161888e-03, .679778047793721e-04}; - static double d6[2] = {-.592166437353694e-03, .270878209671804e-03}; - static double e00[3] = {.25e-3, .25e-1, .14e0}; - static double x00[3] = {31.0e0, 17.0e0, 9.7e0}; - static int K1 = 1; - static int K2 = 0; - static double a2n, a2nm1, acc, am0, amn, an, an0, apn, b2n, b2nm1, c, c0, c1, c2, c3, c4, c5, c6, cma, e, e0, g, h, j, - l, r, rta, rtx, s, sum, t, t1, tol, twoa, u, w, x0, y, z; - static int i, iop, m, max, n; - static double wk[20], T3; - static int T4, T5; - static double T6, T7; - /* - .. - .. Executable Statements .. - */ - /* - -------------------- - ****** E IS A MACHINE DEPENDENT CONSTANT. E IS THE SMALLEST - FLOATING POINT NUMBER FOR WHICH 1.0 + E .GT. 1.0 . - */ - e = spmpar(&K1); - if (*a < 0.0e0 || *x < 0.0e0) goto S430; - if (*a == 0.0e0 && *x == 0.0e0) goto S430; - if (*a * *x == 0.0e0) goto S420; - iop = *ind + 1; - if (iop != 1 && iop != 2) iop = 3; - acc = fifdmax1(acc0[iop - 1], e); - e0 = e00[iop - 1]; - x0 = x00[iop - 1]; - /* - SELECT THE APPROPRIATE ALGORITHM - */ - if (*a >= 1.0e0) goto S10; - if (*a == 0.5e0) goto S390; - if (*x < 1.1e0) goto S160; - t1 = *a * log(*x) - *x; - u = *a * exp(t1); - if (u == 0.0e0) goto S380; - r = u * (1.0e0 + gam1(a)); - goto S250; -S10: - if (*a >= big[iop - 1]) goto S30; - if (*a > *x || *x >= x0) goto S20; - twoa = *a + *a; - m = fifidint(twoa); - if (twoa != (double)m) goto S20; - i = m / 2; - if (*a == (double)i) goto S210; - goto S220; -S20: - t1 = *a * log(*x) - *x; - r = exp(t1) / Xgamm(a); - goto S40; -S30: - l = *x / *a; - if (l == 0.0e0) goto S370; - s = 0.5e0 + (0.5e0 - l); - z = rlog(&l); - if (z >= 700.0e0 / *a) goto S410; - y = *a * z; - rta = sqrt(*a); - if (fabs(s) <= e0 / rta) goto S330; - if (fabs(s) <= 0.4e0) goto S270; - t = pow(1.0e0 / *a, 2.0); - t1 = (((0.75e0 * t - 1.0e0) * t + 3.5e0) * t - 105.0e0) / (*a * 1260.0e0); - t1 -= y; - r = rt2pin * rta * exp(t1); -S40: - if (r == 0.0e0) goto S420; - if (*x <= fifdmax1(*a, alog10)) goto S50; - if (*x < x0) goto S250; - goto S100; -S50: - /* - TAYLOR SERIES FOR P/R - */ - apn = *a + 1.0e0; - t = *x / apn; - wk[0] = t; - for (n = 2; n <= 20; n++) { - apn += 1.0e0; - t *= (*x / apn); - if (t <= 1.e-3) goto S70; - wk[n - 1] = t; - } - n = 20; -S70: - sum = t; - tol = 0.5e0 * acc; -S80: - apn += 1.0e0; - t *= (*x / apn); - sum += t; - if (t > tol) goto S80; - max = n - 1; - for (m = 1; m <= max; m++) { - n -= 1; - sum += wk[n - 1]; - } - *ans = r / *a * (1.0e0 + sum); - *qans = 0.5e0 + (0.5e0 - *ans); - return; -S100: - /* - ASYMPTOTIC EXPANSION - */ - amn = *a - 1.0e0; - t = amn / *x; - wk[0] = t; - for (n = 2; n <= 20; n++) { - amn -= 1.0e0; - t *= (amn / *x); - if (fabs(t) <= 1.e-3) goto S120; - wk[n - 1] = t; - } - n = 20; -S120: - sum = t; -S130: - if (fabs(t) <= acc) goto S140; - amn -= 1.0e0; - t *= (amn / *x); - sum += t; - goto S130; -S140: - max = n - 1; - for (m = 1; m <= max; m++) { - n -= 1; - sum += wk[n - 1]; - } - *qans = r / *x * (1.0e0 + sum); - *ans = 0.5e0 + (0.5e0 - *qans); - return; -S160: - /* - TAYLOR SERIES FOR P(A,X)/X**A - */ - an = 3.0e0; - c = *x; - sum = *x / (*a + 3.0e0); - tol = 3.0e0 * acc / (*a + 1.0e0); -S170: - an += 1.0e0; - c = -(c * (*x / an)); - t = c / (*a + an); - sum += t; - if (fabs(t) > tol) goto S170; - j = *a * *x * ((sum / 6.0e0 - 0.5e0 / (*a + 2.0e0)) * *x + 1.0e0 / (*a + 1.0e0)); - z = *a * log(*x); - h = gam1(a); - g = 1.0e0 + h; - if (*x < 0.25e0) goto S180; - if (*a < *x / 2.59e0) goto S200; - goto S190; -S180: - if (z > -.13394e0) goto S200; -S190: - w = exp(z); - *ans = w * g * (0.5e0 + (0.5e0 - j)); - *qans = 0.5e0 + (0.5e0 - *ans); - return; -S200: - l = rexp(&z); - w = 0.5e0 + (0.5e0 + l); - *qans = (w * j - l) * g - h; - if (*qans < 0.0e0) goto S380; - *ans = 0.5e0 + (0.5e0 - *qans); - return; -S210: - /* - FINITE SUMS FOR Q WHEN A .GE. 1 - AND 2*A IS AN INTEGER - */ - sum = exp(-*x); - t = sum; - n = 1; - c = 0.0e0; - goto S230; -S220: - rtx = sqrt(*x); - sum = erfc1(&K2, &rtx); - t = exp(-*x) / (rtpi * rtx); - n = 0; - c = -0.5e0; -S230: - if (n == i) goto S240; - n += 1; - c += 1.0e0; - t = *x * t / c; - sum += t; - goto S230; -S240: - *qans = sum; - *ans = 0.5e0 + (0.5e0 - *qans); - return; -S250: - /* - CONTINUED FRACTION EXPANSION - */ - tol = fifdmax1(5.0e0 * e, acc); - a2nm1 = a2n = 1.0e0; - b2nm1 = *x; - b2n = *x + (1.0e0 - *a); - c = 1.0e0; -S260: - a2nm1 = *x * a2n + c * a2nm1; - b2nm1 = *x * b2n + c * b2nm1; - am0 = a2nm1 / b2nm1; - c += 1.0e0; - cma = c - *a; - a2n = a2nm1 + cma * a2n; - b2n = b2nm1 + cma * b2n; - an0 = a2n / b2n; - if (fabs(an0 - am0) >= tol * an0) goto S260; - *qans = r * an0; - *ans = 0.5e0 + (0.5e0 - *qans); - return; -S270: - /* - GENERAL TEMME EXPANSION - */ - if (fabs(s) <= 2.0e0 * e && *a * e * e > 3.28e-3) goto S430; - c = exp(-y); - T3 = sqrt(y); - w = 0.5e0 * erfc1(&K1, &T3); - u = 1.0e0 / *a; - z = sqrt(z + z); - if (l < 1.0e0) z = -z; - T4 = iop - 2; - if (T4 < 0) - goto S280; - else if (T4 == 0) - goto S290; - else - goto S300; -S280: - if (fabs(s) <= 1.e-3) goto S340; - c0 = ((((((((((((d0[12] * z + d0[11]) * z + d0[10]) * z + d0[9]) * z + d0[8]) * z + d0[7]) * z + d0[6]) * z + d0[5]) * - z + - d0[4]) * - z + - d0[3]) * - z + - d0[2]) * - z + - d0[1]) * - z + - d0[0]) * - z - - third; - c1 = (((((((((((d1[11] * z + d1[10]) * z + d1[9]) * z + d1[8]) * z + d1[7]) * z + d1[6]) * z + d1[5]) * z + d1[4]) * - z + - d1[3]) * - z + - d1[2]) * - z + - d1[1]) * - z + - d1[0]) * - z + - d10; - c2 = (((((((((d2[9] * z + d2[8]) * z + d2[7]) * z + d2[6]) * z + d2[5]) * z + d2[4]) * z + d2[3]) * z + d2[2]) * z + - d2[1]) * - z + - d2[0]) * - z + - d20; - c3 = - (((((((d3[7] * z + d3[6]) * z + d3[5]) * z + d3[4]) * z + d3[3]) * z + d3[2]) * z + d3[1]) * z + d3[0]) * z + d30; - c4 = (((((d4[5] * z + d4[4]) * z + d4[3]) * z + d4[2]) * z + d4[1]) * z + d4[0]) * z + d40; - c5 = (((d5[3] * z + d5[2]) * z + d5[1]) * z + d5[0]) * z + d50; - c6 = (d6[1] * z + d6[0]) * z + d60; - t = ((((((d70 * u + c6) * u + c5) * u + c4) * u + c3) * u + c2) * u + c1) * u + c0; - goto S310; -S290: - c0 = (((((d0[5] * z + d0[4]) * z + d0[3]) * z + d0[2]) * z + d0[1]) * z + d0[0]) * z - third; - c1 = (((d1[3] * z + d1[2]) * z + d1[1]) * z + d1[0]) * z + d10; - c2 = d2[0] * z + d20; - t = (c2 * u + c1) * u + c0; - goto S310; -S300: - t = ((d0[2] * z + d0[1]) * z + d0[0]) * z - third; -S310: - if (l < 1.0e0) goto S320; - *qans = c * (w + rt2pin * t / rta); - *ans = 0.5e0 + (0.5e0 - *qans); - return; -S320: - *ans = c * (w - rt2pin * t / rta); - *qans = 0.5e0 + (0.5e0 - *ans); - return; -S330: - /* - TEMME EXPANSION FOR L = 1 - */ - if (*a * e * e > 3.28e-3) goto S430; - c = 0.5e0 + (0.5e0 - y); - w = (0.5e0 - sqrt(y) * (0.5e0 + (0.5e0 - y / 3.0e0)) / rtpi) / c; - u = 1.0e0 / *a; - z = sqrt(z + z); - if (l < 1.0e0) z = -z; - T5 = iop - 2; - if (T5 < 0) - goto S340; - else if (T5 == 0) - goto S350; - else - goto S360; -S340: - c0 = ((((((d0[6] * z + d0[5]) * z + d0[4]) * z + d0[3]) * z + d0[2]) * z + d0[1]) * z + d0[0]) * z - third; - c1 = (((((d1[5] * z + d1[4]) * z + d1[3]) * z + d1[2]) * z + d1[1]) * z + d1[0]) * z + d10; - c2 = ((((d2[4] * z + d2[3]) * z + d2[2]) * z + d2[1]) * z + d2[0]) * z + d20; - c3 = (((d3[3] * z + d3[2]) * z + d3[1]) * z + d3[0]) * z + d30; - c4 = (d4[1] * z + d4[0]) * z + d40; - c5 = (d5[1] * z + d5[0]) * z + d50; - c6 = d6[0] * z + d60; - t = ((((((d70 * u + c6) * u + c5) * u + c4) * u + c3) * u + c2) * u + c1) * u + c0; - goto S310; -S350: - c0 = (d0[1] * z + d0[0]) * z - third; - c1 = d1[0] * z + d10; - t = (d20 * u + c1) * u + c0; - goto S310; -S360: - t = d0[0] * z - third; - goto S310; -S370: - /* - SPECIAL CASES - */ - *ans = 0.0e0; - *qans = 1.0e0; - return; -S380: - *ans = 1.0e0; - *qans = 0.0e0; - return; -S390: - if (*x >= 0.25e0) goto S400; - T6 = sqrt(*x); - *ans = erf1(&T6); - *qans = 0.5e0 + (0.5e0 - *ans); - return; -S400: - T7 = sqrt(*x); - *qans = erfc1(&K2, &T7); - *ans = 0.5e0 + (0.5e0 - *qans); - return; -S410: - if (fabs(s) <= 2.0e0 * e) goto S430; -S420: - if (*x <= *a) goto S370; - goto S380; -S430: - /* - ERROR RETURN - */ - *ans = 2.0e0; - return; -} -double gsumln(double *a, double *b) -/* ------------------------------------------------------------------------ - EVALUATION OF THE FUNCTION LN(GAMMA(A + B)) - FOR 1 .LE. A .LE. 2 AND 1 .LE. B .LE. 2 ------------------------------------------------------------------------ -*/ -{ - static double gsumln, x, T1, T2; - /* - .. - .. Executable Statements .. - */ - x = *a + *b - 2.e0; - if (x > 0.25e0) goto S10; - T1 = 1.0e0 + x; - gsumln = gamln1(&T1); - return gsumln; -S10: - if (x > 1.25e0) goto S20; - gsumln = gamln1(&x) + alnrel(&x); - return gsumln; -S20: - T2 = x - 1.0e0; - gsumln = gamln1(&T2) + log(x * (1.0e0 + x)); - return gsumln; -} -double psi(double *xx) -/* ---------------------------------------------------------------------- - - EVALUATION OF THE DIGAMMA FUNCTION - - ----------- - - PSI(XX) IS ASSIGNED THE VALUE 0 WHEN THE DIGAMMA FUNCTION CANNOT - BE COMPUTED. - - THE MAIN COMPUTATION INVOLVES EVALUATION OF RATIONAL CHEBYSHEV - APPROXIMATIONS PUBLISHED IN MATH. COMP. 27, 123-127(1973) BY - CODY, STRECOK AND THACHER. - ---------------------------------------------------------------------- - PSI WAS WRITTEN AT ARGONNE NATIONAL LABORATORY FOR THE FUNPACK - PACKAGE OF SPECIAL FUNCTION SUBROUTINES. PSI WAS MODIFIED BY - A.H. MORRIS (NSWC). ---------------------------------------------------------------------- -*/ -{ - static double dx0 = 1.461632144968362341262659542325721325e0; - static double piov4 = .785398163397448e0; - static double p1[7] = {.895385022981970e-02, - .477762828042627e+01, - .142441585084029e+03, - .118645200713425e+04, - .363351846806499e+04, - .413810161269013e+04, - .130560269827897e+04}; - static double p2[4] = {-.212940445131011e+01, -.701677227766759e+01, -.448616543918019e+01, -.648157123766197e+00}; - static double q1[6] = {.448452573429826e+02, - .520752771467162e+03, - .221000799247830e+04, - .364127349079381e+04, - .190831076596300e+04, - .691091682714533e-05}; - static double q2[4] = {.322703493791143e+02, .892920700481861e+02, .546117738103215e+02, .777788548522962e+01}; - static int K1 = 3; - static int K2 = 1; - static double psi, aug, den, sgn, upper, w, x, xmax1, xmx0, xsmall, z; - static int i, m, n, nq; - /* - .. - .. Executable Statements .. - */ - /* - --------------------------------------------------------------------- - MACHINE DEPENDENT CONSTANTS ... - XMAX1 = THE SMALLEST POSITIVE FLOATING POINT CONSTANT - WITH ENTIRELY INTEGER REPRESENTATION. ALSO USED - AS NEGATIVE OF LOWER BOUND ON ACCEPTABLE NEGATIVE - ARGUMENTS AND AS THE POSITIVE ARGUMENT BEYOND WHICH - PSI MAY BE REPRESENTED AS ALOG(X). - XSMALL = ABSOLUTE ARGUMENT BELOW WHICH PI*COTAN(PI*X) - MAY BE REPRESENTED BY 1/X. - --------------------------------------------------------------------- - */ - xmax1 = ipmpar(&K1); - xmax1 = fifdmin1(xmax1, 1.0e0 / spmpar(&K2)); - xsmall = 1.e-9; - x = *xx; - aug = 0.0e0; - if (x >= 0.5e0) goto S50; - /* - --------------------------------------------------------------------- - X .LT. 0.5, USE REFLECTION FORMULA - PSI(1-X) = PSI(X) + PI * COTAN(PI*X) - --------------------------------------------------------------------- - */ - if (fabs(x) > xsmall) goto S10; - if (x == 0.0e0) goto S100; - /* - --------------------------------------------------------------------- - 0 .LT. ABS(X) .LE. XSMALL. USE 1/X AS A SUBSTITUTE - FOR PI*COTAN(PI*X) - --------------------------------------------------------------------- - */ - aug = -(1.0e0 / x); - goto S40; -S10: - /* - --------------------------------------------------------------------- - REDUCTION OF ARGUMENT FOR COTAN - --------------------------------------------------------------------- - */ - w = -x; - sgn = piov4; - if (w > 0.0e0) goto S20; - w = -w; - sgn = -sgn; -S20: - /* - --------------------------------------------------------------------- - MAKE AN ERROR EXIT IF X .LE. -XMAX1 - --------------------------------------------------------------------- - */ - if (w >= xmax1) goto S100; - nq = fifidint(w); - w -= (double)nq; - nq = fifidint(w * 4.0e0); - w = 4.0e0 * (w - (double)nq * .25e0); - /* - --------------------------------------------------------------------- - W IS NOW RELATED TO THE FRACTIONAL PART OF 4.0 * X. - ADJUST ARGUMENT TO CORRESPOND TO VALUES IN FIRST - QUADRANT AND DETERMINE SIGN - --------------------------------------------------------------------- - */ - n = nq / 2; - if (n + n != nq) w = 1.0e0 - w; - z = piov4 * w; - m = n / 2; - if (m + m != n) sgn = -sgn; - /* - --------------------------------------------------------------------- - DETERMINE FINAL VALUE FOR -PI*COTAN(PI*X) - --------------------------------------------------------------------- - */ - n = (nq + 1) / 2; - m = n / 2; - m += m; - if (m != n) goto S30; - /* - --------------------------------------------------------------------- - CHECK FOR SINGULARITY - --------------------------------------------------------------------- - */ - if (z == 0.0e0) goto S100; - /* - --------------------------------------------------------------------- - USE COS/SIN AS A SUBSTITUTE FOR COTAN, AND - SIN/COS AS A SUBSTITUTE FOR TAN - --------------------------------------------------------------------- - */ - aug = sgn * (cos(z) / sin(z) * 4.0e0); - goto S40; -S30: - aug = sgn * (sin(z) / cos(z) * 4.0e0); -S40: - x = 1.0e0 - x; -S50: - if (x > 3.0e0) goto S70; - /* - --------------------------------------------------------------------- - 0.5 .LE. X .LE. 3.0 - --------------------------------------------------------------------- - */ - den = x; - upper = p1[0] * x; - for (i = 1; i <= 5; i++) { - den = (den + q1[i - 1]) * x; - upper = (upper + p1[i + 1 - 1]) * x; - } - den = (upper + p1[6]) / (den + q1[5]); - xmx0 = x - dx0; - psi = den * xmx0 + aug; - return psi; -S70: - /* - --------------------------------------------------------------------- - IF X .GE. XMAX1, PSI = LN(X) - --------------------------------------------------------------------- - */ - if (x >= xmax1) goto S90; - /* - --------------------------------------------------------------------- - 3.0 .LT. X .LT. XMAX1 - --------------------------------------------------------------------- - */ - w = 1.0e0 / (x * x); - den = w; - upper = p2[0] * w; - for (i = 1; i <= 3; i++) { - den = (den + q2[i - 1]) * w; - upper = (upper + p2[i + 1 - 1]) * w; - } - aug = upper / (den + q2[3]) - 0.5e0 / x + aug; -S90: - psi = aug + log(x); - return psi; -S100: - /* - --------------------------------------------------------------------- - ERROR RETURN - --------------------------------------------------------------------- - */ - psi = 0.0e0; - return psi; -} -double rcomp(double *a, double *x) -/* - ------------------- - EVALUATION OF EXP(-X)*X**A/GAMMA(A) - ------------------- - RT2PIN = 1/SQRT(2*PI) - ------------------- -*/ -{ - static double rt2pin = .398942280401433e0; - static double rcomp, t, t1, u; - /* - .. - .. Executable Statements .. - */ - rcomp = 0.0e0; - if (*a >= 20.0e0) goto S20; - t = *a * log(*x) - *x; - if (*a >= 1.0e0) goto S10; - rcomp = *a * exp(t) * (1.0e0 + gam1(a)); - return rcomp; -S10: - rcomp = exp(t) / Xgamm(a); - return rcomp; -S20: - u = *x / *a; - if (u == 0.0e0) return rcomp; - t = pow(1.0e0 / *a, 2.0); - t1 = (((0.75e0 * t - 1.0e0) * t + 3.5e0) * t - 105.0e0) / (*a * 1260.0e0); - t1 -= (*a * rlog(&u)); - rcomp = rt2pin * sqrt(*a) * exp(t1); - return rcomp; -} -double rexp(double *x) -/* ------------------------------------------------------------------------ - EVALUATION OF THE FUNCTION EXP(X) - 1 ------------------------------------------------------------------------ -*/ -{ - static double p1 = .914041914819518e-09; - static double p2 = .238082361044469e-01; - static double q1 = -.499999999085958e+00; - static double q2 = .107141568980644e+00; - static double q3 = -.119041179760821e-01; - static double q4 = .595130811860248e-03; - static double rexp, w; - /* - .. - .. Executable Statements .. - */ - if (fabs(*x) > 0.15e0) goto S10; - rexp = *x * (((p2 * *x + p1) * *x + 1.0e0) / ((((q4 * *x + q3) * *x + q2) * *x + q1) * *x + 1.0e0)); - return rexp; -S10: - w = exp(*x); - if (*x > 0.0e0) goto S20; - rexp = w - 0.5e0 - 0.5e0; - return rexp; -S20: - rexp = w * (0.5e0 + (0.5e0 - 1.0e0 / w)); - return rexp; -} -double rlog(double *x) -/* - ------------------- - COMPUTATION OF X - 1 - LN(X) - ------------------- -*/ -{ - static double a = .566749439387324e-01; - static double b = .456512608815524e-01; - static double p0 = .333333333333333e+00; - static double p1 = -.224696413112536e+00; - static double p2 = .620886815375787e-02; - static double q1 = -.127408923933623e+01; - static double q2 = .354508718369557e+00; - static double rlog, r, t, u, w, w1; - /* - .. - .. Executable Statements .. - */ - if (*x < 0.61e0 || *x > 1.57e0) goto S40; - if (*x < 0.82e0) goto S10; - if (*x > 1.18e0) goto S20; - /* - ARGUMENT REDUCTION - */ - u = *x - 0.5e0 - 0.5e0; - w1 = 0.0e0; - goto S30; -S10: - u = *x - 0.7e0; - u /= 0.7e0; - w1 = a - u * 0.3e0; - goto S30; -S20: - u = 0.75e0 * *x - 1.e0; - w1 = b + u / 3.0e0; -S30: - /* - SERIES EXPANSION - */ - r = u / (u + 2.0e0); - t = r * r; - w = ((p2 * t + p1) * t + p0) / ((q2 * t + q1) * t + 1.0e0); - rlog = 2.0e0 * t * (1.0e0 / (1.0e0 - r) - r * w) + w1; - return rlog; -S40: - r = *x - 0.5e0 - 0.5e0; - rlog = r - log(*x); - return rlog; -} -double rlog1(double *x) -/* ------------------------------------------------------------------------ - EVALUATION OF THE FUNCTION X - LN(1 + X) ------------------------------------------------------------------------ -*/ -{ - static double a = .566749439387324e-01; - static double b = .456512608815524e-01; - static double p0 = .333333333333333e+00; - static double p1 = -.224696413112536e+00; - static double p2 = .620886815375787e-02; - static double q1 = -.127408923933623e+01; - static double q2 = .354508718369557e+00; - static double rlog1, h, r, t, w, w1; - /* - .. - .. Executable Statements .. - */ - if (*x < -0.39e0 || *x > 0.57e0) goto S40; - if (*x < -0.18e0) goto S10; - if (*x > 0.18e0) goto S20; - /* - ARGUMENT REDUCTION - */ - h = *x; - w1 = 0.0e0; - goto S30; -S10: - h = *x + 0.3e0; - h /= 0.7e0; - w1 = a - h * 0.3e0; - goto S30; -S20: - h = 0.75e0 * *x - 0.25e0; - w1 = b + h / 3.0e0; -S30: - /* - SERIES EXPANSION - */ - r = h / (h + 2.0e0); - t = r * r; - w = ((p2 * t + p1) * t + p0) / ((q2 * t + q1) * t + 1.0e0); - rlog1 = 2.0e0 * t * (1.0e0 / (1.0e0 - r) - r * w) + w1; - return rlog1; -S40: - w = *x + 0.5e0 + 0.5e0; - rlog1 = *x - log(w); - return rlog1; -} -double spmpar(int *i) -/* ------------------------------------------------------------------------ - - SPMPAR PROVIDES THE SINGLE PRECISION MACHINE CONSTANTS FOR - THE COMPUTER BEING USED. IT IS ASSUMED THAT THE ARGUMENT - I IS AN INTEGER HAVING ONE OF THE VALUES 1, 2, OR 3. IF THE - SINGLE PRECISION ARITHMETIC BEING USED HAS M BASE B DIGITS AND - ITS SMALLEST AND LARGEST EXPONENTS ARE EMIN AND EMAX, THEN - - SPMPAR(1) = B**(1 - M), THE MACHINE PRECISION, - - SPMPAR(2) = B**(EMIN - 1), THE SMALLEST MAGNITUDE, - - SPMPAR(3) = B**EMAX*(1 - B**(-M)), THE LARGEST MAGNITUDE. - ------------------------------------------------------------------------ - WRITTEN BY - ALFRED H. MORRIS, JR. - NAVAL SURFACE WARFARE CENTER - DAHLGREN VIRGINIA ------------------------------------------------------------------------ ------------------------------------------------------------------------ - MODIFIED BY BARRY W. BROWN TO RETURN DOUBLE PRECISION MACHINE - CONSTANTS FOR THE COMPUTER BEING USED. THIS MODIFICATION WAS - MADE AS PART OF CONVERTING BRATIO TO DOUBLE PRECISION ------------------------------------------------------------------------ -*/ -{ - static int K1 = 4; - static int K2 = 8; - static int K3 = 9; - static int K4 = 10; - static double spmpar, b, binv, bm1, one, w, z; - static int emax, emin, ibeta, m; - /* - .. - .. Executable Statements .. - */ - if (*i > 1) goto S10; - b = ipmpar(&K1); - m = ipmpar(&K2); - spmpar = pow(b, (double)(1 - m)); - return spmpar; -S10: - if (*i > 2) goto S20; - b = ipmpar(&K1); - emin = ipmpar(&K3); - one = 1.0; - binv = one / b; - w = pow(b, (double)(emin + 2)); - spmpar = w * binv * binv * binv; - return spmpar; -S20: - ibeta = ipmpar(&K1); - m = ipmpar(&K2); - emax = ipmpar(&K4); - b = ibeta; - bm1 = ibeta - 1; - one = 1.0; - z = pow(b, (double)(m - 1)); - w = ((z - one) * b + bm1) / (b * z); - z = pow(b, (double)(emax - 2)); - spmpar = w * z * b * b; - return spmpar; -} -double stvaln(double *p) -/* -********************************************************************** - - double stvaln(double *p) - STarting VALue for Neton-Raphon - calculation of Normal distribution Inverse - - - Function - - - Returns X such that CUMNOR(X) = P, i.e., the integral from - - infinity to X of (1/SQRT(2*PI)) EXP(-U*U/2) dU is P - - - Arguments - - - P --> The probability whose normal deviate is sought. - P is DOUBLE PRECISION - - - Method - - - The rational function on page 95 of Kennedy and Gentle, - Statistical Computing, Marcel Dekker, NY , 1980. - -********************************************************************** -*/ -{ - static double xden[5] = {0.993484626060e-1, 0.588581570495e0, 0.531103462366e0, 0.103537752850e0, 0.38560700634e-2}; - static double xnum[5] = { - -0.322232431088e0, -1.000000000000e0, -0.342242088547e0, -0.204231210245e-1, -0.453642210148e-4}; - static int K1 = 5; - static double stvaln, sign, y, z; - /* - .. - .. Executable Statements .. - */ - if (!(*p <= 0.5e0)) goto S10; - sign = -1.0e0; - z = *p; - goto S20; -S10: - sign = 1.0e0; - z = 1.0e0 - *p; -S20: - y = sqrt(-(2.0e0 * log(z))); - stvaln = y + devlpl(xnum, &K1, &y) / devlpl(xden, &K1, &y); - stvaln = sign * stvaln; - return stvaln; -} -/************************************************************************ -FIFDINT: -Truncates a double precision number to an integer and returns the -value in a double. -************************************************************************/ -double fifdint(double a) -/* a - number to be truncated */ -{ - long temp; - temp = (long)(a); - return (double)(temp); -} -/************************************************************************ -FIFDMAX1: -returns the maximum of two numbers a and b -************************************************************************/ -double fifdmax1(double a, double b) -/* a - first number */ -/* b - second number */ -{ - if (a < b) - return b; - else - return a; -} -/************************************************************************ -FIFDMIN1: -returns the minimum of two numbers a and b -************************************************************************/ -double fifdmin1(double a, double b) -/* a - first number */ -/* b - second number */ -{ - if (a < b) - return a; - else - return b; -} -/************************************************************************ -FIFDSIGN: -transfers the sign of the variable "sign" to the variable "mag" -************************************************************************/ -double fifdsign(double mag, double sign) -/* mag - magnitude */ -/* sign - sign to be transfered */ -{ - if (mag < 0) mag = -mag; - if (sign < 0) mag = -mag; - return mag; -} -/************************************************************************ -FIFIDINT: -Truncates a double precision number to a long integer -************************************************************************/ -long fifidint(double a) -/* a - number to be truncated */ { return (long)(a); } -/************************************************************************ -FIFMOD: -returns the modulo of a and b -************************************************************************/ -long fifmod(long a, long b) -/* a - numerator */ -/* b - denominator */ { return a % b; } -/************************************************************************ -FTNSTOP: -Prints msg to standard error and then exits -************************************************************************/ -void ftnstop(char *msg) -/* msg - error message */ -{ - if (msg != NULL) fprintf(stderr, "%s\n", msg); - exit(EXIT_FAILURE); /* EXIT_FAILURE from stdlib.h, or use an int */ -} -double sigf(float F, int df1, int df2) -{ - double q, p, bound, d_df1, d_df2, d_F; - double sig; - int status, which; - - d_df1 = (double)df1; - d_df2 = (double)df2; - d_F = (double)F; - which = 1; - cdff(&which, &p, &q, &d_F, &d_df1, &d_df2, &status, &bound); - sig = q; - return sig; -} diff --git a/utils/dct.c b/utils/dct.cpp similarity index 100% rename from utils/dct.c rename to utils/dct.cpp diff --git a/utils/density.c b/utils/density.cpp similarity index 100% rename from utils/density.c rename to utils/density.cpp diff --git a/utils/diag.c b/utils/diag.cpp similarity index 98% rename from utils/diag.c rename to utils/diag.cpp index 148788697d0..3f6a891139f 100644 --- a/utils/diag.c +++ b/utils/diag.cpp @@ -299,7 +299,7 @@ int DiagFprintf(unsigned long diag_bits, char *fmt, ...) Description ------------------------------------------------------*/ -int DiagPrintf(unsigned long diag_bits, char *fmt, ...) +int DiagPrintf(unsigned long diag_bits, const char *fmt, ...) { va_list args; @@ -365,7 +365,7 @@ void DiagShowPctDone(float pct_done, int nprints) } } -int check_finite(char *where, double what) +int check_finite(const char *where, double what) { if (!isfinite(what)) { ErrorPrintf(ERROR_BADPARM, "%s not finite!\n", where); diff --git a/utils/diffuse.c b/utils/diffuse.cpp similarity index 98% rename from utils/diffuse.c rename to utils/diffuse.cpp index 662509c8228..9648a74ff22 100644 --- a/utils/diffuse.c +++ b/utils/diffuse.cpp @@ -23,7 +23,6 @@ * */ -#include #include #include #include @@ -69,11 +68,6 @@ int ImageDiffuse(IMAGE *inImage, IMAGE *outImage, double k, int niter, int which ImageCopy(inImage, fSrcImage); -#if 0 - if (Gdiag & DIAG_TIMER) - DebugTimerStart() ; -#endif - switch (which) { case DIFFUSE_PERONA: ImageDiffusePerona(fSrcImage, fDstImage, k, niter, slope, kimage); @@ -89,17 +83,6 @@ int ImageDiffuse(IMAGE *inImage, IMAGE *outImage, double k, int niter, int which break; } -#if 0 - if (Gdiag & DIAG_TIMER) - { - char str[100] ; - - DebugTimerStop() ; - sprintf(str, "ImageDiffuse for %d iterations: ", niter) ; - DebugTimerShow(str); - } -#endif - ImageCopy(fDstImage, outImage); ImageFree(&fSrcImage); ImageFree(&fDstImage); diff --git a/utils/dmatrix.c b/utils/dmatrix.cpp similarity index 100% rename from utils/dmatrix.c rename to utils/dmatrix.cpp diff --git a/utils/dti.c b/utils/dti.cpp similarity index 98% rename from utils/dti.c rename to utils/dti.cpp index dcdbc7c09b9..adb9d3402b8 100644 --- a/utils/dti.c +++ b/utils/dti.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -72,7 +73,8 @@ int DTIfree(DTI **pdti) int DTIparamsFromSiemensAscii(const char *fname, float *bValue, int *nDir, int *nB0) { - char *tag, *pc; + std::string tag; + char *pc; if (!fio_FileExistsReadable(fname)) { printf("ERROR: cannot read %s\n", fname); @@ -80,9 +82,9 @@ int DTIparamsFromSiemensAscii(const char *fname, float *bValue, int *nDir, int * } tag = "sDiffusion.alBValue[1]"; - pc = SiemensAsciiTag(fname, tag, 0); + pc = SiemensAsciiTag(fname, tag.c_str(), 0); if (pc == NULL) { - printf("ERROR: cannot extract %s from %s\n", tag, fname); + printf("ERROR: cannot extract %s from %s\n", tag.c_str(), fname); return (1); } sscanf(pc, "%f", bValue); @@ -90,9 +92,9 @@ int DTIparamsFromSiemensAscii(const char *fname, float *bValue, int *nDir, int * free(pc); tag = "sWiPMemBlock.alFree[8]"; - pc = SiemensAsciiTag(fname, tag, 0); + pc = SiemensAsciiTag(fname, tag.c_str(), 0); if (pc == NULL) { - printf("ERROR: cannot extract %s from %s\n", tag, fname); + printf("ERROR: cannot extract %s from %s\n", tag.c_str(), fname); return (1); } sscanf(pc, "%d", nB0); @@ -100,9 +102,9 @@ int DTIparamsFromSiemensAscii(const char *fname, float *bValue, int *nDir, int * free(pc); tag = "sDiffusion.lDiffDirections"; - pc = SiemensAsciiTag(fname, tag, 0); + pc = SiemensAsciiTag(fname, tag.c_str(), 0); if (pc == NULL) { - printf("ERROR: cannot extract %s from %s\n", tag, fname); + printf("ERROR: cannot extract %s from %s\n", tag.c_str(), fname); return (1); } sscanf(pc, "%d", nDir); diff --git a/utils/dtk.fs.c b/utils/dtk.fs.cpp similarity index 98% rename from utils/dtk.fs.c rename to utils/dtk.fs.cpp index 0b153368897..c4da4a0a054 100644 --- a/utils/dtk.fs.c +++ b/utils/dtk.fs.cpp @@ -93,7 +93,7 @@ DTK_TRACK_SET *DTKloadTrackSet(char *trkfile, char *mrifile) } dtkset = (DTK_TRACK_SET *)calloc(sizeof(DTK_TRACK_SET), 1); - dtkset->template = mri; + dtkset->mri_template = mri; dtkset->hdr = (DTK_HDR *)calloc(sizeof(DTK_HDR), 1); // This should be 1000 bytes @@ -283,7 +283,7 @@ MRI *DTKmapEndPoints(DTK_TRACK_SET *dtkset) int ntrk, c, r, s, nlast, n; DTK_TRACK *trk; - t = dtkset->template; + t = dtkset->mri_template; mri = MRIalloc(t->width, t->height, t->depth, MRI_INT); MRIcopyHeader(t, mri); @@ -380,7 +380,7 @@ DTK_TRACK_SET *DTKextractCC(DTK_TRACK_SET *trkset) DTK_TRACK_SET *newset; newset = (DTK_TRACK_SET *)calloc(sizeof(DTK_TRACK_SET), 1); - newset->template = trkset->template; + newset->mri_template = trkset->mri_template; newset->hdr = (DTK_HDR *)calloc(sizeof(DTK_HDR), 1); memcpy(newset->hdr, trkset->hdr, sizeof(DTK_HDR)); newset->hdr->n_count = 0; @@ -412,7 +412,7 @@ DTK_TRACK_SET *DTKextractSeg(DTK_TRACK_SET *trkset, int segid) DTK_TRACK_SET *newset; newset = (DTK_TRACK_SET *)calloc(sizeof(DTK_TRACK_SET), 1); - newset->template = trkset->template; + newset->mri_template = trkset->mri_template; newset->hdr = (DTK_HDR *)calloc(sizeof(DTK_HDR), 1); memcpy(newset->hdr, trkset->hdr, sizeof(DTK_HDR)); newset->hdr->n_count = 0; @@ -446,7 +446,7 @@ DTK_TRACK_SET *DTKextractSegEndPoints(DTK_TRACK_SET *trkset, int segid) DTK_TRACK_SET *newset; newset = (DTK_TRACK_SET *)calloc(sizeof(DTK_TRACK_SET), 1); - newset->template = trkset->template; + newset->mri_template = trkset->mri_template; newset->hdr = (DTK_HDR *)calloc(sizeof(DTK_HDR), 1); memcpy(newset->hdr, trkset->hdr, sizeof(DTK_HDR)); newset->hdr->n_count = 0; @@ -525,7 +525,7 @@ MRI *DTKmapTrackNos(DTK_TRACK_SET *trkset) int ntrk, c, r, s, n, nhits, nmaxhits = 10000; DTK_TRACK *trk; - t = trkset->template; + t = trkset->mri_template; mri = MRIallocSequence(t->width, t->height, t->depth, MRI_INT, nmaxhits); if (mri == NULL) return (NULL); MRIcopyHeader(t, mri); diff --git a/utils/error.c b/utils/error.cpp similarity index 96% rename from utils/error.c rename to utils/error.cpp index 395445be094..c5b78581a8d 100644 --- a/utils/error.c +++ b/utils/error.cpp @@ -33,13 +33,11 @@ #include #include -#include - #include "error.h" #include "fsinit.h" #include "hips.h" #include "proto.h" -#include "rgb_image.h" +#include "rgb.h" /*----------------------------------------------------- MACROS AND CONSTANTS @@ -99,7 +97,7 @@ int ErrorInit(char *fname, int (*vprint)(const char *fmt, va_list args)) { FSinit(); - error_exit = (void *)exit; + error_exit = exit; i_seterror(rgb_error); if (fname) strcpy(error_fname, fname); if (vfprint) error_vfprintf = vfprint; @@ -131,7 +129,6 @@ void ErrorExit(int ecode, const char *fmt, ...) fflush(stderr); fflush(stdout); if (errno) perror(NULL); - if (hipserrno) perr(ecode, "Hips error:"); if (ErrorExitDoneFile != NULL) { // This creates a text file with the value of 1. This can @@ -188,10 +185,6 @@ int ErrorPrintf(int ecode, const char *fmt, ...) fflush(stdout); va_end(args); if (errno) perror(NULL); -#if 0 - if (hipserrno) - perr(ecode, "Hips error:") ; -#endif va_start(args, fmt); fp = fopen(ERROR_FNAME, "a"); diff --git a/utils/evschutils.c b/utils/evschutils.cpp similarity index 99% rename from utils/evschutils.c rename to utils/evschutils.cpp index b5a339a276b..3c195ff7b05 100644 --- a/utils/evschutils.c +++ b/utils/evschutils.cpp @@ -724,7 +724,7 @@ float EVScb1Error(EVSCH *EvSch) EVScostId() - converts from a string indicating a cost function to a numeric id that can be used in a case statement. ----------------------------------------------------------------*/ -int EVScostId(char *CostString) +int EVScostId(const char *CostString) { if (!strcmp("eff", CostString)) return (EVS_COST_EFF); if (!strcmp("effinv", CostString)) return (EVS_COST_EFF_INV); @@ -740,7 +740,7 @@ int EVScostId(char *CostString) statement) indicating a cost function to a human-readable string. ----------------------------------------------------------------*/ -char *EVScostString(int CostId) +const char *EVScostString(int CostId) { switch (CostId) { case EVS_COST_UNKNOWN: diff --git a/utils/fcd.c b/utils/fcd.cpp similarity index 100% rename from utils/fcd.c rename to utils/fcd.cpp diff --git a/utils/fftutils.c b/utils/fftutils.cpp similarity index 99% rename from utils/fftutils.c rename to utils/fftutils.cpp index 9818f8dbdd0..a06193661b3 100644 --- a/utils/fftutils.c +++ b/utils/fftutils.cpp @@ -64,13 +64,13 @@ static complexF **_uILookupF = NULL; static float *uRLookup = NULL; static float *uILookup = NULL; -static void FFTerror(char *string) +static void FFTerror(const char *string) { fprintf(stdout, "\nFFT Error: %s\n", string); exit(1); } -void FFTdebugAssert(int b, char *string) +void FFTdebugAssert(int b, const char *string) { if (!b) FFTerror(string); } diff --git a/utils/field_code.c b/utils/field_code.cpp similarity index 98% rename from utils/field_code.c rename to utils/field_code.cpp index fcf0fe5654e..30fb6a555e0 100644 --- a/utils/field_code.c +++ b/utils/field_code.cpp @@ -32,7 +32,7 @@ #include "field_code.h" -char *ReturnFieldName(int which_field) +const char *ReturnFieldName(int which_field) { switch (which_field) { case OVERLAY_FRAME: diff --git a/utils/filter.c b/utils/filter.cpp similarity index 99% rename from utils/filter.c rename to utils/filter.cpp index 8a0abdadd58..93be6ee6bdc 100644 --- a/utils/filter.c +++ b/utils/filter.cpp @@ -42,10 +42,7 @@ #include #include -#include - #include "hips.h" - #include "diag.h" #include "error.h" #include "filter.h" @@ -1499,7 +1496,7 @@ static float weights[] = {ONE_EIGHTH, ONE_EIGHTH, -0.5f, ONE_EIGHTH, ONE_EIGHTH} IMAGE *ImageLaplacian(IMAGE *Isrc, IMAGE *outImage) { - int rows, cols, x, y, xi, yi, i; + int rows, cols, x, y, xi, yi; float *fkpix, sum, *fopix, fival; rows = Isrc->rows; @@ -1513,7 +1510,8 @@ IMAGE *ImageLaplacian(IMAGE *Isrc, IMAGE *outImage) for (y = 0; y < rows; y++) { for (x = 0; x < cols; x++, fopix++) { fkpix = weights; - for (sum = 0.0f, i = 0; i < LAPLACIAN_POINTS; i++) { + sum = 0.0f; + for (unsigned int i = 0; i < LAPLACIAN_POINTS; i++) { yi = y + yoffsets[i]; /* image coordinate */ if (yi < 0) yi = 0; diff --git a/utils/fio.c b/utils/fio.cpp similarity index 100% rename from utils/fio.c rename to utils/fio.cpp diff --git a/utils/flash.c b/utils/flash.cpp similarity index 100% rename from utils/flash.c rename to utils/flash.cpp diff --git a/utils/fmarchmesh.c b/utils/fmarchmesh.c deleted file mode 100644 index fe67934925c..00000000000 --- a/utils/fmarchmesh.c +++ /dev/null @@ -1,454 +0,0 @@ -/** - * @file fmarchmesh.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:43 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/* Program: fmarchmesh.c - * Compute geodesic distance on a surface mesh using the fast-marching method - * Author: Xiao Han - */ - -/* The following function uses HEAP, which uses the LIST data structure */ -#include "fmarchmesh.h" -#include "macros.h" -#include "mrisurf.h" -#define DEBUG 0 - -float ReCompute(int vIDc, int vIDa, int vIDb, MRI_SURFACE *mesh, float *T, unsigned char *label); -float ComputeTInAcute(float, float, float, float, float); - -float *FastMarchMesh(MRI_SURFACE *mesh, int *contour, int numinitvert, float thred) -{ - /* Compute the geodesic distance of surface vertices to the initial contour*/ - /* vector 'contour' contains the indices of the vertice at the initial - contour, i.e., vertices with zero distance. numinitvert is the size of - contour. - To save time, the distance computation stops when vertices with distance - less than thred are all computed - */ - /* The program assumes that the neighborhood structure of the surface mesh - is already built, e.g., using function mrisCompleteTopology, which seems - to be always performed during surface-file-reading - Thus, the total number of neighors of vertex i is mesh->vertices[i].vnum, - and the j-th neighbor of i is mesh->vertices[i].v[j]. - It also assumes the neighbors are stored in correct order, i.e., - two consecutive neighbors j and j+1 form a face with vertex i. - Maybe a separate function need be written to make sure the neighborhood - construction is correct! - I think I may just use every face sharing the vertex directly, since the - current program assumes the mesh is closed and simple, which may not be - true. I think I need to use both, i.e., use face when need to compute - distance from each shared face, and use v->v when need to enumerate - every neighbors! - */ - - float *T; /* final distances of each vertex to the contour */ - float tempvalue, newvalue; - unsigned char *label; /* "Alive" => 1; "Narrow Band" => 2; "Far Away" => 3; */ - int *BackPointer; /* backpointer to the narrowband heap */ - Xheap H; /* Narrrow band heap */ - XheapElement he; - // int heapindex; - - FACE *face; - - int i, j, k, index, VN, VId, neighVId, n0, n1; - - VN = mesh->nvertices; /* total number of surface vertices */ - - T = (float *)malloc(sizeof(float) * VN); - - for (i = 0; i < VN; i++) { - T[i] = INFINITY; /*All distance initialized to a large value */ - } - - if (numinitvert <= 0) { - printf("Warning, the initial contour is empty, no geodesic distance can be computed\n"); - - return T; - } - - label = (unsigned char *)malloc(sizeof(unsigned char) * VN); - BackPointer = (int *)malloc(sizeof(int) * VN); - - /* Initialize heap structure */ - H = xhInitEmpty(); - - /* Initialization for marching inwards and outwards simultaneously */ - for (i = 0; i < VN; i++) { - label[i] = (unsigned char)FAWAY; /*All points are labelled as FAR AWAY */ - } - - for (i = 0; i < numinitvert; i++) { - label[contour[i]] = (unsigned char)ALIVE; /* all vertices on contour are alive */ - T[contour[i]] = 0; /* all vertices on contour have distance zero */ - } - - /* Initialize NarrowBand Heap */ - for (i = 0; i < VN; i++) { - if (label[i] == (unsigned char)ALIVE) { - /* put its neighbors into the NarrowBand */ - if (DEBUG) printf("mesh->vertices[i].vnum = %d\n", mesh->vertices_topology[i].vnum); - for (j = 0; j < mesh->vertices_topology[i].vnum; j++) { - neighVId = mesh->vertices_topology[i].v[j]; - if (DEBUG) printf("neighVId = %d\n", neighVId); - if (label[neighVId] == (unsigned char)FAWAY) { - /* compute the distance to this point and add it to the heap */ - label[neighVId] = (unsigned char)NBAND; - /* Check all possible triangles surrounding vertex neighVId1 */ - /* Note: Only ALIVE points contribute to the distance computation */ - newvalue = INFINITY; - /* Compute distance from each face the vertex shares */ - /* k is the index of faces shared by the vertex neighVId */ - if (DEBUG) printf("mesh->vertices[neighVId].num = %d\n", mesh->vertices_topology[neighVId].num); - for (k = 0; k < mesh->vertices_topology[neighVId].num; k++) { - index = mesh->vertices_topology[neighVId].n[k]; /* # of vertex with ID - neighVId in the k-th face - that it is in */ - if (DEBUG) printf("index = %d\n", index); - face = &mesh->faces[mesh->vertices_topology[neighVId].f[k]]; /* ptr to the - k-th face */ - n0 = face->v[(index + VERTICES_PER_FACE - 1) % VERTICES_PER_FACE]; - n1 = face->v[(index + 1) % VERTICES_PER_FACE]; - if (DEBUG) printf("no = %d, n1 = %d\n", n0, n1); - tempvalue = ReCompute(neighVId, n0, n1, mesh, T, label); - if (tempvalue < newvalue) newvalue = tempvalue; - } /* end for-k */ - - T[neighVId] = newvalue; - xhInsert(newvalue, neighVId, &(BackPointer[neighVId]), H); - - } /* end if */ - } /* end for */ - } /* end if */ - } /* end for */ - - /* End of Initialization */ - - /* Begin Fast Marching to get the unsigned distance function inwords - * and outwards simultaneously - * since points inside and outside the contour won't interfere with - * each other - */ - while (!xhIsEmpty(H)) { /* There are still points not yet accepted */ - he = xhRemove(H); /* Label the point with smallest value among all - NarrowBand points as ALIVE */ - VId = he.id; - - T[VId] = he.value; - label[VId] = (unsigned char)ALIVE; - - if (he.value > thred) break; - - /* Update its neighbor */ - /* Put FARAWAY neighbors into NarrowBand, Recompute values at - * NarrowBand neighbors, - * Keep ALIVE (Accepted) neighbor unchanged - */ - for (i = 0; i < mesh->vertices_topology[VId].vnum; i++) { - neighVId = mesh->vertices_topology[VId].v[i]; - - /* Don't change ALIVE neighbors */ - if (label[neighVId] != (unsigned char)ALIVE) { - newvalue = INFINITY; - - /* Compute distance from each face the vertex shares */ - /* j is the index of faces shared by the vertex neighVId */ - for (j = 0; j < mesh->vertices_topology[neighVId].num; j++) { - face = &mesh->faces[mesh->vertices_topology[neighVId].f[j]]; /* ptr to the - j-th face */ - - index = mesh->vertices_topology[neighVId].n[j]; /* index of the vertex - (neighVId) in the j-th - face that it belongs to */ - /* Take the ID of the remaining two vertices of the j-th face */ - n0 = face->v[(index + VERTICES_PER_FACE - 1) % VERTICES_PER_FACE]; - n1 = face->v[(index + 1) % VERTICES_PER_FACE]; - tempvalue = ReCompute(neighVId, n0, n1, mesh, T, label); - if (tempvalue < newvalue) newvalue = tempvalue; - } /* end for-j */ - - /* If it was a FARAWAY point, add it to the NarrowBand Heap; - * otherwise, just update its value - * using the backpointer - */ - if (label[neighVId] == (unsigned char)NBAND) - xhChangeValue(BackPointer[neighVId], newvalue, H); - else { - xhInsert(newvalue, neighVId, &(BackPointer[neighVId]), H); - label[neighVId] = (unsigned char)NBAND; - } - - } /* end if ALIVE */ - } /* end updating neighbors */ - - } /* end of marching loop */ - - free(label); - free(BackPointer); - xhDestroy(H); - - return T; -} - -/* vIDa, vIDb & vIDc are the three vertices making up the triangle */ -/* mesh is the mesh to compute the distances on */ -/* T is the current transit time values */ -/* label is the label map */ -/* compute the new T for vIDc based on the current T values of vIDa & vIDb */ -/* Unfold the mesh around edge AB if C is an obtuse angle */ -/* see Kimmel and Sethian for derivation of these formulae */ -float ReCompute(int vIDc, int vIDa, int vIDb, MRI_SURFACE *mesh, float *T, unsigned char *label) -{ - float a, b, c; - VERTEX *Va, *Vb, *Vc; - unsigned char la, lb; - float Ta, Tb; - float t1, t2, t; - - int tmpvIDa; - float tmpa; - float tmpTa; - unsigned char tmpla; - - /* Define some auxillary variables */ - int i, index, n0, n1, UNotID, UID, P1ID, P2ID; - FACE *face; - - /* SQUARES of lengthes (Captital Letters) */ - float P1A, P1B, P1C, P2A, P2B, P2C, UA, UB, UC, P1P2, P1U, P2U; - float cos12A, sin12A, cos12B, sin12B, cos12C, sin12C, cos12U, sin12U; - float AC, BC, AB; - - VERTEX *P1, *P2, *U; - MyVector vP1U, vP2U; - - int iters; - - la = label[vIDa]; - lb = label[vIDb]; - - if ((la != (unsigned char)ALIVE) && (lb != (unsigned char)ALIVE)) return INFINITY; - - Ta = T[vIDa]; - Tb = T[vIDb]; - - Va = &mesh->vertices[vIDa]; - Vb = &mesh->vertices[vIDb]; - Vc = &mesh->vertices[vIDc]; - - a = sqrt((Vb->x - Vc->x) * (Vb->x - Vc->x) + (Vb->y - Vc->y) * (Vb->y - Vc->y) + (Vb->z - Vc->z) * (Vb->z - Vc->z)); - b = sqrt((Va->x - Vc->x) * (Va->x - Vc->x) + (Va->y - Vc->y) * (Va->y - Vc->y) + (Va->z - Vc->z) * (Va->z - Vc->z)); - - if (la != ALIVE) Ta = INFINITY; - if (lb != ALIVE) Tb = INFINITY; - - if (Ta > Tb) { - tmpTa = Ta; - Ta = Tb; - Tb = tmpTa; - - tmpla = la; - la = lb; - lb = tmpla; - - tmpa = a; - a = b; - b = tmpa; - - tmpvIDa = vIDa; - vIDa = vIDb; - vIDb = tmpvIDa; - - Va = &mesh->vertices[vIDa]; - Vb = &mesh->vertices[vIDb]; - } - - c = sqrt((Va->x - Vb->x) * (Va->x - Vb->x) + (Va->y - Vb->y) * (Va->y - Vb->y) + (Va->z - Vb->z) * (Va->z - Vb->z)); - - AC = b * b; - BC = a * a; - AB = c * c; - if (AB < AC + BC) { /* Acute Triangle */ - if (la == ALIVE && lb == ALIVE) { - t = ComputeTInAcute(Ta, Tb, a, b, c); - return t; - } - else - return (MIN(b + Ta, a + Tb)); /* Infinity + sth = Infinity */ - } - - /* Otherwise, perform unfolding */ - - /*Initialization */ - P1ID = vIDa; - P2ID = vIDb; - UNotID = vIDc; - - P1A = 0; - P1B = AB; - P1C = AC; - P2B = 0; - P2A = P1B; - P2C = BC; - P1P2 = P1B; - - cos12A = 1; - sin12A = 0; - cos12B = 1; - sin12B = 0; - cos12C = (P1P2 + P2C - P1C) / (2 * sqrt(P1P2 * P2C)); - sin12C = (1 - cos12C * cos12C); /* Notice: Square of sine */ - - /* Now iteratively unfolding */ - iters = 0; - while (iters < 10) { - /* Find the newly unfolded vertex ID */ - /* The following code assumes the neighbors form a circle, thus need be - modified. But how? */ - UID = -1; - for (i = 0; i < mesh->vertices_topology[P1ID].num; i++) { - index = mesh->vertices_topology[P1ID].n[i]; /* # of vertex with ID - P1ID in the i-th face - that it is in */ - face = &mesh->faces[mesh->vertices_topology[P1ID].f[i]]; /* ptr to the - i-th face */ - n0 = face->v[(index + VERTICES_PER_FACE - 1) % VERTICES_PER_FACE]; - n1 = face->v[(index + 1) % VERTICES_PER_FACE]; - if (n0 == P2ID && n1 != UNotID) { - UID = n1; - break; - } - else if (n1 == P2ID && n0 != UNotID) { - UID = n0; - break; - } - } /* end for-i */ - - if (UID < 0) /* i.e., a valid UID cannot be found */ - break; - - P1 = &mesh->vertices[P1ID]; - P2 = &mesh->vertices[P2ID]; - U = &mesh->vertices[UID]; - - vP1U.x = P1->x - U->x; - vP1U.y = P1->y - U->y; - vP1U.z = P1->z - U->z; - vP2U.x = P2->x - U->x; - vP2U.y = P2->y - U->y; - vP2U.z = P2->z - U->z; - - P1U = (vP1U.x * vP1U.x + vP1U.y * vP1U.y + vP1U.z * vP1U.z); - P2U = (vP2U.x * vP2U.x + vP2U.y * vP2U.y + vP2U.z * vP2U.z); - - cos12U = (P1P2 + P2U - P1U) / (2 * sqrt(P1P2 * P2U)); - sin12U = (1 - cos12U * cos12U); /* Notice: Square of sine */ - - /* Now compute three lengthes (squared) */ - UA = P2U + P2A - 2 * sqrt(P2U * P2A) * (cos12A * cos12U - sqrt(sin12A * sin12U)); - UB = P2U + P2B - 2 * sqrt(P2U * P2B) * (cos12B * cos12U - sqrt(sin12B * sin12U)); - UC = P2U + P2C - 2 * sqrt(P2U * P2C) * (cos12C * cos12U - sqrt(sin12C * sin12U)); - - /* Now Judge Which Side to continue unfolding */ - if (UA > (UC + AC)) { /* Unfold along P1U */ - UNotID = P2ID; - P2ID = UID; - P1P2 = P1U; - P2A = UA; - P2B = UB; - P2C = UC; - } - else if (UB > (UC + BC)) { /* Unfold along P2U */ - UNotID = P1ID; - P1ID = UID; - P1P2 = P2U; - P1A = UA; - P1B = UB; - P1C = UC; - } - else { /* Stop Unfolding and compute T*/ - /* Compute the actual lengthes */ - UC = sqrt(UC); - UA = sqrt(UA); - UB = sqrt(UB); - if (label[UID] == (unsigned char)ALIVE) { - if (la == ALIVE) { - t1 = ComputeTInAcute(Ta, T[UID], UC, b, UA); - } - else - t1 = INFINITY; - if (lb == ALIVE) { - t2 = ComputeTInAcute(Tb, T[UID], UC, a, UB); - } - else - t2 = INFINITY; - return MIN(t1, t2); - } - else - return (MIN(b + Ta, a + Tb)); - } - - /* Update angles */ - cos12A = (P1P2 + P2A - P1A) / (2 * sqrt(P1P2 * P2A)); - if (P2B != 0) cos12B = (P1P2 + P2B - P1B) / (2 * sqrt(P1P2 * P2B)); - cos12C = (P1P2 + P2C - P1C) / (2 * sqrt(P1P2 * P2C)); - - sin12A = 1 - cos12A * cos12A; - sin12B = 1 - cos12B * cos12B; - sin12C = 1 - cos12C * cos12C; - - iters++; - } /* End of while loop */ - - return (MIN(b + Ta, a + Tb)); -} - -float ComputeTInAcute(float Ta, float Tb, float a, float b, float c) -{ - float t1, t2, t, CD, costheta; - float aa, bb, cc, u, tmp; - - costheta = (a * a + b * b - c * c) / (2 * a * b); - - u = Tb - Ta; - - aa = a * a + b * b - 2 * a * b * costheta; - bb = 2 * b * u * (a * costheta - b); - cc = b * b * (u * u - a * a * (1 - costheta * costheta)); - - tmp = bb * bb - 4 * aa * cc; - - if (tmp < 0) return (MIN(b + Ta, a + Tb)); - tmp = sqrt(tmp); - - t1 = (-bb + tmp) / (2 * aa + 1e-15); - t2 = (-bb - tmp) / (2 * aa + 1e-15); - t = MAX(t1, t2); - CD = (b * (t - u)) / t; - - if ((u < t) && (a * costheta < CD) && (CD < (a / costheta))) - return (t + Ta); - else - return (MIN(b + Ta, a + Tb)); -} diff --git a/utils/fmriutils.c b/utils/fmriutils.cpp similarity index 100% rename from utils/fmriutils.c rename to utils/fmriutils.cpp diff --git a/utils/fnv_hash_test.c b/utils/fnv_hash_test.cpp similarity index 100% rename from utils/fnv_hash_test.c rename to utils/fnv_hash_test.cpp diff --git a/utils/fsPrintHelp.c b/utils/fsPrintHelp.cpp similarity index 94% rename from utils/fsPrintHelp.c rename to utils/fsPrintHelp.cpp index 9a0c612753e..4680d7862f5 100644 --- a/utils/fsPrintHelp.c +++ b/utils/fsPrintHelp.cpp @@ -34,7 +34,7 @@ static void printName(xmlNodePtr cur); static void printContents(xmlDocPtr doc, xmlNodePtr cur); -static int tagNameIs(char *c, xmlNodePtr cur); +static int tagNameIs(const char *c, xmlNodePtr cur); static int wrdLen(char *c); int outputHelpDoc(const xmlDocPtr doc) @@ -158,7 +158,7 @@ int outputHelp(const char *name) if (NULL == fshome) { return -1; } - char *fullname = malloc(strlen(name) + strlen(fshome) + strlen("/docs/xml/.help.xml") + 1); + char *fullname = (char *)malloc(strlen(name) + strlen(fshome) + strlen("/docs/xml/.help.xml") + 1); strcpy(fullname, fshome); strcat(fullname, "/docs/xml/"); strcat(fullname, name); @@ -224,7 +224,7 @@ static void replaceUnderscore(char *c) // Prints the name of a tag in the correct format static void printName(xmlNodePtr cur) { - char *n = malloc(strlen((char *)cur->name) + 1); + char *n = (char *)malloc(strlen((char *)cur->name) + 1); strcpy(n, (char *)cur->name); toUpperCase(n); replaceUnderscore(n); @@ -238,7 +238,7 @@ static void printContents(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *contents; contents = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1); - int i = 0, j; + unsigned int i = 0, j; while (i < strlen((char *)contents)) { int tabNum = 1; printf("\n\t"); @@ -251,7 +251,7 @@ static void printContents(xmlDocPtr doc, xmlNodePtr cur) } for (j = i; j < FSPRINT_MAX_CHARS - tabNum * 8 + i && j < strlen((char *)contents) && (wrdLen((char *)(contents + j)) > FSPRINT_MAX_CHARS - tabNum * 8 || - wrdLen((char *)(contents + j)) <= FSPRINT_MAX_CHARS - tabNum * 8 + i - j); + (unsigned)wrdLen((char *)(contents + j)) <= FSPRINT_MAX_CHARS - tabNum * 8 + i - j); j++) { if (*(contents + j) == '\n') { j++; @@ -272,14 +272,14 @@ static void printContents(xmlDocPtr doc, xmlNodePtr cur) } // Checks if the name of the tag is the same as the string parameter -static int tagNameIs(char *c, xmlNodePtr cur) { return !(xmlStrcasecmp(cur->name, (const xmlChar *)c)); } +static int tagNameIs(const char *c, xmlNodePtr cur) { return !(xmlStrcasecmp(cur->name, (const xmlChar *)c)); } // Counts the number of chars until the next space, dash, underscore, slash, // or end of the string // Used to keep a word from running on two lines static int wrdLen(char *c) { - int i; + unsigned int i; for (i = 0; i < strlen(c); i++) { if (*(c + i) == ' ' || *(c + i) == '_' || *(c + i) == '/') { return i; diff --git a/utils/fs_powell.cpp b/utils/fs_powell.cpp index eda5692130b..0ced6fddcc6 100644 --- a/utils/fs_powell.cpp +++ b/utils/fs_powell.cpp @@ -9,7 +9,7 @@ * Original Author: Dennis Jen * CVS Revision Info: * $Author$ - * $Date$ + * $Date$f * $Revision$ * * Copyright © 2011-2016 The General Hospital Corporation (Boston, MA) "MGH" @@ -30,14 +30,8 @@ #endif #include "fs_vnl/fs_powell.h" -#ifdef __cplusplus -extern "C" { -#endif #include // printf #include // calloc and free -#ifdef __cplusplus -} -#endif #include #include diff --git a/utils/fsenv.c b/utils/fsenv.cpp similarity index 100% rename from utils/fsenv.c rename to utils/fsenv.cpp diff --git a/utils/fsgdf.c b/utils/fsgdf.cpp similarity index 100% rename from utils/fsgdf.c rename to utils/fsgdf.cpp diff --git a/utils/fsglm.c b/utils/fsglm.cpp similarity index 99% rename from utils/fsglm.c rename to utils/fsglm.cpp index c3604cc7fce..bfd1e14d564 100644 --- a/utils/fsglm.c +++ b/utils/fsglm.cpp @@ -141,9 +141,9 @@ #include "diag.h" #include "fsglm.h" +#include "timer.h" #include "numerics.h" #include "randomfields.h" -#include "timer.h" #include "utils.h" #undef X @@ -655,9 +655,8 @@ int GLMprofile(int nrows, int ncols, int ncon, int niters) { int n, c, msec; GLMMAT *glm; - struct timeb then; + Timer then; - TimerStart(&then); for (n = 0; n < niters; n++) { glm = GLMalloc(); glm->y = MatrixDRand48(nrows, 1, NULL); @@ -673,7 +672,7 @@ int GLMprofile(int nrows, int ncols, int ncon, int niters) GLMtest(glm); GLMfree(&glm); } - msec = TimerStop(&then); + msec = then.milliseconds(); printf( "GLMprofile: nrows=%d, ncols=%d, ncon=%d, " diff --git a/utils/fsinit.c b/utils/fsinit.cpp similarity index 100% rename from utils/fsinit.c rename to utils/fsinit.cpp diff --git a/utils/gca.c b/utils/gca.cpp similarity index 99% rename from utils/gca.c rename to utils/gca.cpp index 6ec1b973e77..238b3ffe607 100644 --- a/utils/gca.c +++ b/utils/gca.cpp @@ -232,7 +232,6 @@ int GCApriorToNode(const GCA *gca, int xp, int yp, int zp, int *pxn, int *pyn, i static int xnbr_offset[] = {1, -1, 0, 0, 0, 0}; static int ynbr_offset[] = {0, 0, 1, -1, 0, 0}; static int znbr_offset[] = {0, 0, 0, 0, 1, -1}; -int check_finite(char *where, double what); static int boundsCheck(int *pix, int *piy, int *piz, MRI *mri); static void set_equilavent_classes(int *equivalent_classes); @@ -1741,7 +1740,7 @@ GCA *gcaAllocMax( GCA_PRIOR *gcap; int x, y, z; - gca = calloc(1, sizeof(GCA)); + gca = (GCA *)calloc(1, sizeof(GCA)); if (!gca) { ErrorExit(ERROR_NOMEMORY, "GCAalloc: could not allocate struct"); } @@ -5186,7 +5185,7 @@ GCA_SAMPLE *GCAfindStableSamplesByLabel(GCA *gca, int nsamples, float min_prior) memset(ordered_label_counts, 0, sizeof(ordered_label_counts)); memset(found, 0, sizeof(found)); memset(volume, 0, sizeof(volume)); - gcas = calloc(nsamples, sizeof(GCA_SAMPLE)); + gcas = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)); width = gca->prior_width; height = gca->prior_height; depth = gca->prior_depth; @@ -5230,7 +5229,7 @@ GCA_SAMPLE *GCAfindStableSamplesByLabel(GCA *gca, int nsamples, float min_prior) histo[n] = (float)nint(0.25 + histo[n] * (float)nsamples / total); } - for (n = 0; n < sizeof(exclude_classes) / sizeof(exclude_classes[0]); n++) { + for (n = 0; (unsigned)n < sizeof(exclude_classes) / sizeof(exclude_classes[0]); n++) { histo[exclude_classes[n]] = 0; } @@ -5772,7 +5771,7 @@ GCA_SAMPLE *GCAfindStableSamples(GCA *gca, depth = gca->prior_depth; // samples size allocated is prior voxel points - gcas = calloc(width * height * depth, sizeof(GCA_SAMPLE)); + gcas = (GCA_SAMPLE *)calloc(width * height * depth, sizeof(GCA_SAMPLE)); if (!gcas) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %dK x %d samples\n", @@ -6005,7 +6004,7 @@ GCA_SAMPLE *GCAfindExteriorSamples( depth = gca->prior_depth; // samples size allocated is prior voxel points - gcas = calloc(width * height * depth, sizeof(GCA_SAMPLE)); + gcas = (GCA_SAMPLE *)calloc(width * height * depth, sizeof(GCA_SAMPLE)); if (!gcas) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %dK x %d samples\n", @@ -13137,7 +13136,7 @@ int GCAlabelMode(GCA *gca, int label, float *modes) } return (NO_ERROR); } -int GCAclassMode(GCA *gca, int class, float *modes) +int GCAclassMode(GCA *gca, int classnum, float *modes) { int xn, yn, zn, n, r; GCA_NODE *gcan; @@ -13158,7 +13157,7 @@ int GCAclassMode(GCA *gca, int class, float *modes) gcan = &gca->nodes[xn][yn][zn]; for (n = 0; n < gcan->nlabels; n++) { label = gcan->labels[n]; - switch (class) // check to make sure it is + switch (classnum) // check to make sure it is // the specified class { case WM_CLASS: @@ -13199,7 +13198,7 @@ int GCAclassMode(GCA *gca, int class, float *modes) } if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { char fname[STRLEN]; - sprintf(fname, "gca_label%d.plt", class); + sprintf(fname, "gca_label%d.plt", classnum); HISTOplot(h, fname); } @@ -13295,7 +13294,7 @@ int GCAlabelVar(GCA *gca, int label, float *vars) } return (NO_ERROR); } -int GCAclassMean(GCA *gca, int class, float *means) +int GCAclassMean(GCA *gca, int classnum, float *means) { int xn, yn, zn, n, r, label; GCA_NODE *gcan; @@ -13311,7 +13310,7 @@ int GCAclassMean(GCA *gca, int class, float *means) gcan = &gca->nodes[xn][yn][zn]; for (n = 0; n < gcan->nlabels; n++) { label = gcan->labels[n]; - switch (class) // check to make sure it is + switch (classnum) // check to make sure it is // the specified class { case WM_CLASS: @@ -14578,7 +14577,7 @@ GCA_SAMPLE *GCAfindAllSamples(GCA *gca, int *pnsamples, int *exclude_list, int u // allocate nsamples worth GCA_SAMPLE // samples are non-unknowns and unknown with neighbor not unknown - gcas = calloc(nsamples, sizeof(GCA_SAMPLE)); + gcas = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)); badcount = 0; // get the values for gcas @@ -17961,7 +17960,7 @@ static int lhFree(LH **plh) return (NO_ERROR); } -static LABEL_HISTOS *lhRead(char *fname) +static LABEL_HISTOS *lhRead(const char *fname) { FILE *fp; int nsubjects, nlabels, s, n, cnt, i, label, ntypes; @@ -18286,7 +18285,8 @@ int GCAcomputeRenormalizationWithAlignment(GCA *gca, int *plabel_computed) { HISTOGRAM *h_mri, *h_gca, *h_mtl = NULL, *h_caudate; - int l, nbins, i, x, y, z, num, frame, bin, j, n, computed[MAX_CMA_LABELS], b, label, k, border = BORDER_SIZE, + unsigned int k, j; + int l, nbins, i, x, y, z, num, frame, bin, n, computed[MAX_CMA_LABELS], b, label, border = BORDER_SIZE, gca_peak, mri_peak; float fmin, fmax, label_scales[MAX_CMA_LABELS], overlap, mean_gm_scale, mean_wm_scale, mean_csf_scale, label_peaks[MAX_CMA_LABELS], label_offsets[MAX_CMA_LABELS], mean_wm_offset, mean_csf_offset, mean_gm_offset, @@ -18902,7 +18902,7 @@ int GCAcomputeRenormalizationWithAlignment(GCA *gca, } if (getenv("FS_USE_HISTO_COMBOS") != NULL) { - int j; + unsigned int j; HISTOmakePDF(h_caudate, h_caudate); mri_peak = HISTOfindHighestPeakInRegion(h_caudate, 0, h_caudate->nbins); for (j = 0; j <= 1; j++) { @@ -19635,7 +19635,8 @@ int GCAcomputeRenormalizationWithAlignmentLongitudinal(GCA *gca, int *plabel_computed) { HISTOGRAM *h_mri, *h_gca, *h_mtl = NULL, *h_caudate; - int l, nbins, i, x, y, z, num, frame, bin, j, computed[MAX_CMA_LABELS], label, k, gca_peak, mri_peak; + unsigned int k, j; + int l, nbins, i, x, y, z, num, frame, bin, computed[MAX_CMA_LABELS], label, gca_peak, mri_peak; float fmin, fmax, label_scales[MAX_CMA_LABELS], overlap, mean_gm_scale, mean_wm_scale, mean_csf_scale, label_peaks[MAX_CMA_LABELS], label_offsets[MAX_CMA_LABELS], mean_wm_offset, mean_csf_offset, mean_gm_offset, lower_thresh, upper_thresh; @@ -20007,7 +20008,7 @@ int GCAcomputeRenormalizationWithAlignmentLongitudinal(GCA *gca, } if (getenv("FS_USE_HISTO_COMBOS") != NULL) { - int j; + unsigned int j; HISTOmakePDF(h_caudate, h_caudate); mri_peak = HISTOfindHighestPeakInRegion(h_caudate, 0, h_caudate->nbins); for (j = 0; j <= 1; j++) { @@ -21915,7 +21916,7 @@ GCA_NODE *GCAbuildRegionalGCAN(const GCA *gca, int xn, int yn, int zn, int wsize MATRIX *m_cov[MAX_CMA_LABEL + 1], *m_tmp = NULL; VECTOR *v_means[MAX_CMA_LABEL + 1], *v_tmp = NULL; - gcan = calloc(1, sizeof(GCA_NODE)); + gcan = (GCA_NODE *)calloc(1, sizeof(GCA_NODE)); memset(label_priors, 0, sizeof(label_priors)); memset(total_training, 0, sizeof(total_training)); @@ -22000,7 +22001,7 @@ GCA_PRIOR *GCAbuildRegionalGCAP(const GCA *gca, int xp, int yp, int zp, int wsiz float label_priors[MAX_CMA_LABEL + 1], p; double total_p; - gcap = calloc(1, sizeof(GCA_PRIOR)); + gcap = (GCA_PRIOR *)calloc(1, sizeof(GCA_PRIOR)); memset(label_priors, 0, sizeof(label_priors)); memset(total_training, 0, sizeof(total_training)); @@ -24174,7 +24175,8 @@ int GCArenormalizeWithEntropyMinimization(GCA *gca, MRI *mri, TRANSFORM *transfo { float scales[NUM_ENTROPY_LABELS], ll, last_posterior, peaks[NUM_ENTROPY_LABELS], contra_peaks[NUM_CONTRA_LABELS], pct_change, last_scales[NUM_ENTROPY_LABELS]; - int i, done = 0, peak_bin; + unsigned int i; + int done = 0, peak_bin; HISTOGRAM *h_gca; MRI *mri_aseg; @@ -24207,8 +24209,7 @@ int GCArenormalizeWithEntropyMinimization(GCA *gca, MRI *mri, TRANSFORM *transfo gca, mri, mri_aseg, transform, entropy_labels, contra_entropy_labels, scales, NUM_ENTROPY_LABELS, .1); gcaScale(gca, entropy_labels, contra_entropy_labels, scales, NUM_ENTROPY_LABELS, 1); { - int n; - for (n = 0; n < NUM_ENTROPY_LABELS; n++) + for (unsigned int n = 0; n < NUM_ENTROPY_LABELS; n++) printf("scales[%s] = %2.3f, peak = %2.0f (rh=%2.0f)\n", cma_label_to_name(entropy_labels[n]), scales[n], @@ -24701,14 +24702,14 @@ int GCAstructureBoundingBox(GCA *gca, int label, MRI_REGION *box) box->dz = zmax - zmin + 1; return (NO_ERROR); } -int GCArenormalizeClass(GCA *gca, int class, float scale_to_wm) +int GCArenormalizeClass(GCA *gca, int classnum, float scale_to_wm) { float wm_mode, class_mode, scale; int x, y, z, n, same_class, r; GCA_NODE *gcan; GCAclassMode(gca, WM_CLASS, &wm_mode); - GCAclassMode(gca, class, &class_mode); + GCAclassMode(gca, classnum, &class_mode); scale = scale_to_wm * wm_mode / class_mode; printf("current wm/csf ratio = %2.2f (%2.0f/%2.0f), scaling by %2.3f\n", @@ -24721,7 +24722,7 @@ int GCArenormalizeClass(GCA *gca, int class, float scale_to_wm) for (z = 0; z < gca->node_depth; z++) { gcan = &gca->nodes[x][y][z]; for (n = 0; n < gcan->nlabels; n++) { - switch (class) { + switch (classnum) { #if 0 case LH_CLASS: same_class = IS_LH(gcan->labels[n]) ; diff --git a/utils/gcaboundary.c b/utils/gcaboundary.cpp similarity index 100% rename from utils/gcaboundary.c rename to utils/gcaboundary.cpp diff --git a/utils/gcamorph.c b/utils/gcamorph.cpp similarity index 99% rename from utils/gcamorph.c rename to utils/gcamorph.cpp index cb7d64fa9e5..6df8a78f0eb 100644 --- a/utils/gcamorph.c +++ b/utils/gcamorph.cpp @@ -6022,7 +6022,7 @@ int GCAMmorphSurf(MRIS *mris, GCA_MORPH *gcam) int vtxno; for (vtxno = 0; vtxno < mris->nvertices; vtxno++) { VERTEX *v = &mris->vertices[vtxno]; - float Mx, My, Mz; + float Mx = 0, My = 0, Mz = 0; int err = GCAMsampleInverseMorphRAS(gcam, v->x, v->y, v->z, &Mx, &My, &Mz); if (err) { printf("WARNING: GCAMmorphSurf(): error converting vertex %d\n", vtxno); @@ -9014,7 +9014,7 @@ int remove_label_outliers(GCA_MORPH *gcam, MRI *mri_dist, const int whalf, const MRI *mri_std, *mri_ctrl, *mri_tmp, *mri_ctrl_tmp; VOXEL_LIST *vl; float diff, val0, oval; - int delete, xv, yv, zv, xo, yo, zo, x, y, z; + int del, xv, yv, zv, xo, yo, zo, x, y, z; GCA_MORPH_NODE *gcamn, *gcamn_sup, *gcamn_inf; double max_change; @@ -9071,12 +9071,12 @@ int remove_label_outliers(GCA_MORPH *gcam, MRI *mri_dist, const int whalf, const } val0 = MRIgetVoxVal(mri_dist, x, y, z, 0); - delete = 0; - for (xo = -whalf; xo <= whalf && !delete; xo++) { + del = 0; + for (xo = -whalf; xo <= whalf && !del; xo++) { xv = mri_dist->xi[x + xo]; - for (yo = -whalf; yo <= whalf && !delete; yo++) { + for (yo = -whalf; yo <= whalf && !del; yo++) { yv = mri_dist->yi[y + yo]; - for (zo = -whalf; zo <= whalf && !delete; zo++) { + for (zo = -whalf; zo <= whalf && !del; zo++) { zv = mri_dist->zi[z + zo]; oval = MRIgetVoxVal(mri_dist, xv, yv, zv, 0); if (!FZERO(oval)) { @@ -9086,14 +9086,14 @@ int remove_label_outliers(GCA_MORPH *gcam, MRI *mri_dist, const int whalf, const if (fabs(val0) > fabs(oval) && (val0 * oval < 0)) /*if their signs are different and difference is big */ { - delete = 1; + del = 1; } } } } } } - if (delete) { + if (del) { nremoved++; MRIFvox(mri_dist, x, y, z) = 0; MRIsetVoxVal(mri_ctrl, x, y, z, 0, CONTROL_NONE); diff --git a/utils/gcarray.c b/utils/gcarray.c deleted file mode 100644 index 2fe1ec2dba2..00000000000 --- a/utils/gcarray.c +++ /dev/null @@ -1,1087 +0,0 @@ -/** - * @file gcarray.c - * @brief utils for MRI classification using an array of Gaussian classifiers - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:44 $ - * $Revision: 1.8 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/*----------------------------------------------------- - INCLUDE FILES --------------------------------------------------------*/ -#include -#include -#include -#include -#include - -#include "diag.h" -#include "error.h" -#include "gcarray.h" -#include "macros.h" -#include "matrix.h" -#include "mri.h" -#include "proto.h" - -/*----------------------------------------------------- - MACROS AND CONSTANTS --------------------------------------------------------*/ - -#define NCLASSES 4 -#define BACKGROUND 0 -#define GREY_MATTER 1 -#define WHITE_MATTER 2 -#define BRIGHT_MATTER 3 - -/*----------------------------------------------------- - STATIC DATA --------------------------------------------------------*/ - -static char *class_names[NCLASSES] = {"BACKGROUND", "GREY MATTER", "WHITE MATTER", "BRIGHT MATTER"}; - -/*----------------------------------------------------- - STATIC PROTOTYPES --------------------------------------------------------*/ - -/*----------------------------------------------------- - GLOBAL FUNCTIONS --------------------------------------------------------*/ -int GCarrayUpdate(GCARRAY *gcarray, MRI *mri_src, MRI *mri_norm, MRI *mri_target); -int GCarrayFinish(GCARRAY *gcarray); -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - Allocate an MRI structure, spacing the classifiers every - scale pixels, with scale/2 at the left margin. - -------------------------------------------------------*/ -GCARRAY *GCarrayAlloc(MRI *mri_template, int scale, int nvars) -{ - GCARRAY *gcarray; - int x, y, z, width, height, depth; - double xw, yw, zw; - - width = mri_template->width; - height = mri_template->height; - depth = mri_template->depth; - gcarray = (GCARRAY *)calloc(1, sizeof(GCARRAY)); - if (!gcarray) ErrorReturn(NULL, (ERROR_NO_MEMORY, "GCarrayAlloc: could not alloc struct")); - - MRIvoxelToWorld(mri_template, 0, 0, 0, &xw, &yw, &zw); - gcarray->xstart = xw; - gcarray->ystart = yw; - gcarray->zstart = zw; - gcarray->swidth = width; - gcarray->sheight = height; - gcarray->sdepth = depth; - - width = nint((float)(width - scale / 2) / (float)scale + 0.99f); - height = nint((float)(height - scale / 2) / (float)scale + 0.99f); - depth = nint((float)(depth - scale / 2) / (float)scale + 0.99f); - - gcarray->scale = scale; - gcarray->width = width; - gcarray->height = height; - gcarray->depth = depth; - gcarray->nvars = nvars; - - gcarray->gcs = (GCLASSIFY ****)calloc(height, sizeof(GCLASSIFY ***)); - if (!gcarray->gcs) ErrorExit(ERROR_NO_MEMORY, "GCarrayAlloc: could not allocate gcs"); - - for (z = 0; z < depth; z++) { - gcarray->gcs[z] = (GCLASSIFY ***)calloc(height, sizeof(GCLASSIFY **)); - if (!gcarray->gcs[z]) ErrorExit(ERROR_NO_MEMORY, "GCarrayAlloc: could not allocate gcs[%d]", z); - - for (y = 0; y < height; y++) { - gcarray->gcs[z][y] = (GCLASSIFY **)calloc(width, sizeof(GCLASSIFY *)); - if (!gcarray->gcs[z][y]) - ErrorExit( - ERROR_NO_MEMORY, "GCalloc(%d,%d,%d,%d): could not allocate gc[%d][%d]", width, height, depth, scale, y, z); - - for (x = 0; x < width; x++) { - gcarray->gcs[z][y][x] = GCalloc(NCLASSES, nvars, class_names); - if (!gcarray->gcs[z][y][x]) - ErrorExit(ERROR_NO_MEMORY, - "GCalloc(%d,%d,%d,%d): could not allocate gc[%d][%d][%d]", - width, - height, - depth, - scale, - x, - y, - z); - } - } - } - - return (gcarray); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -int GCarrayFree(GCARRAY **pgcarray) -{ - GCARRAY *gcarray; - int x, y, z; - - gcarray = *pgcarray; - *pgcarray = NULL; - - for (z = 0; z < gcarray->depth; z++) { - if (gcarray->gcs[z]) { - for (y = 0; y < gcarray->height; y++) { - if (gcarray->gcs[z][y]) { - for (x = 0; x < gcarray->width; x++) { - if (gcarray->gcs[z][y][x]) GCfree(&gcarray->gcs[z][y][x]); - } - free(gcarray->gcs[z][y]); - } - } - free(gcarray->gcs[z]); - } - } - - free(gcarray->gcs); - free(gcarray); - return (NO_ERROR); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - Do iterative training of a classifier. First go through each - training pair and compute the means for the inputs, then - go through again and compute the covariance matrices. - -------------------------------------------------------*/ -GCARRAY *GCarrayTrainAll(GCARRAY *gcarray, char *training_file_name, int scale, int ninputs) -{ - char source_fname[100], target_fname[100], line[300], *cp; - FILE *fp; - int fno, nfiles; - MRI *mri_src, *mri_target, *mri_std, *mri_zscore, *mri_mean, *mris[10]; - - /* first figure out the total # of files */ - fp = fopen(training_file_name, "r"); - if (!fp) ErrorReturn(NULL, (ERROR_NO_FILE, "GCarrayTrainAll(%s): could not open file", training_file_name)); - - nfiles = 0; - while ((cp = fgetl(line, 299, fp)) != NULL) nfiles++; - fprintf(stderr, "processing %d files\n", nfiles); - rewind(fp); - - /* now calculate means */ - fprintf(stderr, "computing means...\n"); - fno = 0; - while ((cp = fgetl(line, 299, fp)) != NULL) { - sscanf(cp, "%s %s", source_fname, target_fname); - fprintf(stderr, "file[%d]: %s --> %s\n", fno, source_fname, target_fname); - mri_src = MRIread(source_fname); - if (!mri_src) { - fprintf(stderr, "could not read MR image %s\n", source_fname); - continue; - } - - if (!fno && !gcarray) /* allocate the GCARRAY */ - gcarray = GCarrayAlloc(mri_src, scale, ninputs); - - mri_mean = MRImean(mri_src, NULL, 3); - mri_std = MRIstd(mri_src, NULL, mri_mean, 3); - mri_zscore = MRIzScore(mri_src, NULL, mri_mean, mri_std); - - mris[0] = mri_src; - mris[1] = mri_zscore; - - MRIfree(&mri_mean); - MRIfree(&mri_std); - - mri_target = MRIread(target_fname); - if (!mri_target) { - fprintf(stderr, "could not read MR image %s\n", target_fname); - MRIfree(&mri_src); - MRIfree(&mri_zscore); - continue; - } - - GCarrayUpdateMeans(gcarray, mris, mri_target, 2); - - MRIfree(&mri_src); - MRIfree(&mri_target); - MRIfree(&mri_zscore); - fno++; - } - - GCarrayComputeMeans(gcarray); /* divide by # of observations */ - rewind(fp); - - /* now calculate covariances */ - fprintf(stderr, "computing covariance matrices...\n"); - fno = 0; - while ((cp = fgetl(line, 299, fp)) != NULL) { - sscanf(cp, "%s %s", source_fname, target_fname); - fprintf(stderr, "file[%d]: %s --> %s\n", fno, source_fname, target_fname); - mri_src = MRIread(source_fname); - if (!mri_src) { - fprintf(stderr, "could not read MR image %s\n", source_fname); - continue; - } - - mri_mean = MRImean(mri_src, NULL, 3); - mri_std = MRIstd(mri_src, NULL, mri_mean, 3); - mri_zscore = MRIzScore(mri_src, NULL, mri_mean, mri_std); - mris[0] = mri_src; - mris[1] = mri_zscore; - MRIfree(&mri_mean); - MRIfree(&mri_std); - - mri_target = MRIread(target_fname); - if (!mri_target) { - fprintf(stderr, "could not read MR image %s\n", target_fname); - MRIfree(&mri_zscore); - MRIfree(&mri_src); - continue; - } - - GCarrayUpdateCovariances(gcarray, mris, mri_target, 2); - - MRIfree(&mri_src); - MRIfree(&mri_target); - MRIfree(&mri_zscore); - fno++; - } - - GCarrayComputeCovariances(gcarray); - - fclose(fp); - return (gcarray); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - Do iterative training of a classifier. First go through - - allow each classifier to be trained on a part of - the space that it's neighbor is responsible (i.e. - use overlapping training regions). The overlap is - defined to be MAX(1, scale/4) on each side of the - region. -------------------------------------------------------*/ -int GCarrayUpdate(GCARRAY *gcarray, MRI *mri_src, MRI *mri_norm, MRI *mri_target) { return (NO_ERROR); } -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - allow each classifier to be trained on a part of - the space that it's neighbor is responsible (i.e. - use overlapping training regions). The overlap is - defined to be MAX(1, scale/4) on each side of the - region. -------------------------------------------------------*/ -int GCarrayFinish(GCARRAY *gcarray) { return (NO_ERROR); } -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - allow each classifier to be trained on a part of - the space that it's neighbor is responsible (i.e. - use overlapping training regions). The overlap is - defined to be MAX(1, scale/4) on each side of the - region. -------------------------------------------------------*/ -#define LO_LIM 60 -#define HI_LIM 150 - -int GCarrayTrain(GCARRAY *gcarray, MRI *mri_src, MRI *mri_zscore, MRI *mri_target) -{ - MATRIX *m_inputs[NCLASSES]; - GCLASSIFY *gc, **pgc; - int x, y, z, x0, y0, z0, x1, y1, z1, xm, ym, zm, xv, yv, zv, width, depth, height, scale, classno, nclasses, - nobs[NCLASSES], swidth, sheight, sdepth, overlap, ninputs; - BUFTYPE src, target; - double xrv, yrv, zrv, xt, yt, zt; - - scale = gcarray->scale; - overlap = MAX(1, scale / 4); - ninputs = scale + 2 * overlap + 1; - ninputs = ninputs * ninputs * ninputs; - for (classno = 0; classno < NCLASSES; classno++) - m_inputs[classno] = MatrixAlloc(ninputs, gcarray->nvars, MATRIX_REAL); - - width = gcarray->width; - height = gcarray->height; - depth = gcarray->depth; - nclasses = NCLASSES; - - swidth = mri_src->width; - sheight = mri_src->height; - sdepth = mri_src->depth; - - /* - the classifiers are distributed in Talairach space, whereas the - input MR images are not (necessarily). Therefore we have to - transform the voxel coordinates into Tal. space before selecting - the training values. - - train each classifier, x,y,z are in classifier space, xm, ym, and - zm are pixel coordinates in Talairach space - */ - for (z = 0; z < depth; z++) { - z0 = MAX(0, z * scale - overlap); - z1 = MIN(sdepth - 1, (z + 1) * scale + overlap); - for (y = 0; y < height; y++) { - y0 = MAX(0, y * scale - overlap); - y1 = MIN(sheight - 1, (y + 1) * scale + overlap); - pgc = gcarray->gcs[z][y]; - for (x = 0; x < width; x++) { - gc = *pgc++; - x0 = MAX(0, x * scale - overlap); - x1 = MIN(swidth - 1, (x + 1) * scale + overlap); - - memset(nobs, 0, NCLASSES * sizeof(nobs[0])); - for (zm = z0; zm <= z1; zm++) { - for (ym = y0; ym <= y1; ym++) { - for (xm = x0; xm <= x1; xm++) { - /* convert to Talairach coords, then to voxel coords of src */ - /* convert from natural axes of coronal slices Talairach axes */ - xt = (double)xm + gcarray->xstart; /* voxel to world */ - yt = (double)zm + gcarray->ystart; - zt = (double)-ym + gcarray->zstart; - MRItalairachToVoxel(mri_src, xt, yt, zt, &xrv, &yrv, &zrv); - xv = nint(xrv); - yv = nint(yrv); - zv = nint(zrv); - if (xv < 0 || xv >= swidth || yv < 0 || yv >= sheight || zv < 0 || zv >= sdepth) continue; - - src = MRIvox(mri_src, xv, yv, zv); - target = MRIvox(mri_target, xv, yv, zv); - - /* decide what class it is */ - if (target) - classno = WHITE_MATTER; - else { - if (src < LO_LIM) - classno = BACKGROUND; - else if (src > HI_LIM) - classno = BRIGHT_MATTER; - else - classno = GREY_MATTER; - } - - m_inputs[classno]->rptr[nobs[classno] + 1][1] = src; - m_inputs[classno]->rptr[nobs[classno] + 1][2] = MRIFvox(mri_zscore, xv, yv, zv); - if (gcarray->nvars > 2) { - m_inputs[classno]->rptr[nobs[classno] + 1][3] = xt; - m_inputs[classno]->rptr[nobs[classno] + 1][4] = yt; - m_inputs[classno]->rptr[nobs[classno] + 1][5] = zt; - } - nobs[classno]++; - } - } - } - - /* now apply training vectors */ - for (classno = 0; classno < nclasses; classno++) { - m_inputs[classno]->rows = nobs[classno]; - GCtrain(gc, classno, m_inputs[classno]); - m_inputs[classno]->rows = scale * scale * scale; - } - } - } - } - - for (classno = 0; classno < NCLASSES; classno++) MatrixFree(&m_inputs[classno]); - - return (ERROR_NONE); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -#define PRETTY_SURE .90f - -MRI *GCarrayClassify(GCARRAY *gcarray, MRI *mri_src, MRI *mri_dst, float conf, MRI *mri_probs, MRI *mri_classes) -{ - MATRIX *m_inputs; - GCLASSIFY *gc; - int x, y, z, xc, yc, zc, width, depth, height, scale, classno, swidth, sheight, sdepth; - // int nclasses; - BUFTYPE *psrc, src, *pdst, *pclasses; - float *pzscore, prob, *pprobs = NULL; - double xt, yt, zt, xv, yv, zv; - MRI *mri_std, *mri_zscore, *mri_mean; - - mri_mean = MRImean(mri_src, NULL, 3); - mri_std = MRIstd(mri_src, mri_std, NULL, 3); - mri_zscore = MRIzScore(mri_src, NULL, mri_mean, mri_std); - MRIfree(&mri_std); - MRIfree(&mri_mean); - if (conf < 0.0f || conf >= 1.0f) conf = PRETTY_SURE; - - if (!mri_dst) mri_dst = MRIclone(mri_src, NULL); - - m_inputs = MatrixAlloc(gcarray->nvars, 1, MATRIX_REAL); - - width = gcarray->width; - height = gcarray->height; - depth = gcarray->depth; - swidth = mri_src->width; - sheight = mri_src->height; - sdepth = mri_src->depth; - scale = gcarray->scale; - // nclasses = NCLASSES; - - /* - x, y, and z are in the MR image space. To get the appropriate classifier - for each spatial location we must convert to Talairach voxel coords., - then find the classifier assigned to that location in Talairach space. - - xc, yc, and zc are in classifier space, while xvt, yvt and zvt are - in Talairach voxel coords. - */ - for (z = 0; z < sdepth; z++) { - for (y = 0; y < sheight; y++) { - psrc = &MRIvox(mri_src, 0, y, z); - pdst = &MRIvox(mri_dst, 0, y, z); - pzscore = &MRIFvox(mri_zscore, 0, y, z); - if (mri_probs) - pprobs = &MRIFvox(mri_probs, 0, y, z); - else - pprobs = NULL; - if (mri_classes) - pclasses = &MRIvox(mri_classes, 0, y, z); - else - pclasses = NULL; - for (x = 0; x < swidth; x++) { - /* find the appropriate classifier for this location */ - MRIvoxelToTalairach(mri_src, (double)x, (double)y, (double)z, &xt, &yt, &zt); - - /* convert from Talairach axes to natural axes of coronal slice data */ - xv = (xt - (double)gcarray->xstart); - zv = (yt - (double)gcarray->ystart); - yv = (-zt + (double)gcarray->zstart); - xc = nint(((xv)-scale / 2) / scale); - if (xc < 0) - xc = 0; - else if (xc >= width) - xc = width - 1; - yc = nint(((yv)-scale / 2) / scale); - if (yc < 0) - yc = 0; - else if (yc >= height) - yc = height - 1; - zc = nint(((zv)-scale / 2) / scale); - if (zc < 0) - zc = 0; - else if (zc >= depth) - zc = depth - 1; - gc = gcarray->gcs[zc][yc][xc]; - src = *psrc++; - m_inputs->rptr[1][1] = src; - m_inputs->rptr[2][1] = *pzscore++; - if (gcarray->nvars > 2) { - m_inputs->rptr[3][1] = xt; - m_inputs->rptr[4][1] = yt; - m_inputs->rptr[5][1] = zt; - } - - /* now classify this observation */ - classno = GCclassify(gc, m_inputs, NULL, &prob); - - if (pclasses) *pclasses++ = (BUFTYPE)classno; - if (pprobs) *pprobs++ = prob; - if (classno == WHITE_MATTER && prob > conf) - *pdst++ = 255; - else - *pdst++ = src; - } - } - } - - MatrixFree(&m_inputs); - MRIfree(&mri_zscore); - - return (mri_dst); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -int GCarrayToVoxel(GCARRAY *gcarray, int xc, int yc, int zc, int *pxv, int *pyv, int *pzv) -{ - int scale; - - scale = gcarray->scale; - *pxv = xc * scale + scale / 2; - *pyv = yc * scale + scale / 2; - *pzv = zc * scale + scale / 2; - return (NO_ERROR); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -int GCarrayVoxelToClass(GCARRAY *gcarray, int xv, int yv, int zv, int *pxc, int *pyc, int *pzc) -{ - int scale; - - scale = gcarray->scale; - *pxc = nint((float)(xv - scale / 2) / (float)scale + .99f); - *pyc = nint((float)(yv - scale / 2) / (float)scale + .99f); - *pzc = nint((float)(zv - scale / 2) / (float)scale + .99f); - return (NO_ERROR); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -int GCarraySetTransform(GCARRAY *gcarray, Transform *transform, Transform *inverse_transform) -{ - gcarray->transform = transform; - gcarray->inverse_transform = inverse_transform; - return (NO_ERROR); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -GCARRAY *GCarrayRead(char *fname) -{ - GCARRAY *gcarray; - FILE *fp; - int width, height, depth, nvars, scale, x, y, z; - MRI mri; - - fp = fopen(fname, "r"); - if (!fp) ErrorReturn(NULL, (ERROR_NO_FILE, "GCarrayRead(%s): could not open file", fname)); - - if (fscanf(fp, - "%d %d %d %d %d %d %d %d %f %f %f\n", - &scale, - &width, - &height, - &depth, - &mri.width, - &mri.height, - &mri.depth, - &nvars, - &mri.xstart, - &mri.ystart, - &mri.zstart) != 11) { - fclose(fp); - ErrorReturn(NULL, (ERROR_BADFILE, "GCarrayRead(%s): could scanf parms from file", fname)); - } - setDirectionCosine(&mri, MRI_CORONAL); - mri.xsize = mri.ysize = mri.zsize = 1; - gcarray = GCarrayAlloc(&mri, scale, nvars); - if (!gcarray) { - fclose(fp); - ErrorReturn(NULL, (ERROR_BADPARM, "GCarrayRead(%s): gcarray allocation failed", fname)); - } - gcarray->xstart = mri.xstart; /* a hack, I know, but what the hell... */ - gcarray->ystart = mri.ystart; - gcarray->zstart = mri.zstart; - - for (z = 0; z < gcarray->depth; z++) { - for (y = 0; y < gcarray->height; y++) { - for (x = 0; x < gcarray->width; x++) { - GCasciiReadFrom(fp, gcarray->gcs[z][y][x]); - } - } - } - fclose(fp); - return (gcarray); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -int GCarrayWrite(GCARRAY *gcarray, char *fname) -{ - FILE *fp; - int x, y, z; - - fp = fopen(fname, "wb"); - if (!fp) ErrorReturn(ERROR_NO_FILE, (ERROR_NO_FILE, "GCarrayWrite(%s): could not open file", fname)); - - fprintf(fp, - "%d %d %d %d %d %d %d %d %2.3f %2.3f %2.3f\n", - gcarray->scale, - gcarray->width, - gcarray->height, - gcarray->depth, - gcarray->swidth, - gcarray->sheight, - gcarray->sdepth, - gcarray->nvars, - gcarray->xstart, - gcarray->ystart, - gcarray->zstart); - - for (z = 0; z < gcarray->depth; z++) { - for (y = 0; y < gcarray->height; y++) { - for (x = 0; x < gcarray->width; x++) { - GCasciiWriteInto(fp, gcarray->gcs[z][y][x]); - } - } - } - fclose(fp); - return (NO_ERROR); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -MRI *GCarrayThreshold(GCARRAY *gcarray, MRI *mri_probs, MRI *mri_classes, MRI *mri_dst, float threshold) -{ - int x, y, z, width, height, depth, class; - float *pprobs, prob; - BUFTYPE *pclasses, *pdst; - - if (!mri_dst) mri_dst = MRIclone(mri_classes, NULL); - - width = mri_classes->width; - height = mri_classes->height; - depth = mri_classes->depth; - - for (z = 0; z < depth; z++) { - for (y = 0; y < height; y++) { - pprobs = &MRIFvox(mri_probs, 0, y, z); - pclasses = &MRIvox(mri_classes, 0, y, z); - pdst = &MRIvox(mri_dst, 0, y, z); - for (x = 0; x < width; x++) { - prob = *pprobs++; - class = (int)*pclasses++; - if (prob >= threshold && class == WHITE_MATTER) *pdst++ = 255; -#if 0 - else if (class == WHITE_MATTER) - *pdst++ = 128 ; -#endif - else - *pdst++ = 0; - } - } - } - return (mri_dst); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - -------------------------------------------------------*/ -GCLASSIFY *MRIgetClassifier(GCARRAY *gcarray, MRI *mri, int x, int y, int z) -{ - GCLASSIFY *gc; - double xt, yt, zt; - int width, depth, height, scale, xc, yc, zc, xv, yv, zv; - - width = gcarray->width; - height = gcarray->height; - depth = gcarray->depth; - scale = gcarray->scale; - - /* find the appropriate classifier for this location */ - MRIvoxelToTalairach(mri, (double)x, (double)y, (double)z, &xt, &yt, &zt); - - /* convert from Talairach axes to natural axes of coronal slice data */ - xv = (xt - (double)gcarray->xstart); - zv = (yt - (double)gcarray->ystart); - yv = (-zt + (double)gcarray->zstart); - xc = nint(((xv)-scale / 2) / scale); - if (xc < 0) - xc = 0; - else if (xc >= width) - xc = width - 1; - yc = nint(((yv)-scale / 2) / scale); - if (yc < 0) - yc = 0; - else if (yc >= height) - yc = height - 1; - zc = nint(((zv)-scale / 2) / scale); - if (zc < 0) - zc = 0; - else if (zc >= depth) - zc = depth - 1; - gc = gcarray->gcs[zc][yc][xc]; -#if 1 - fprintf(stderr, - "classifier at (%d, %d, %d) --> (%d, %d, %d) is (%d, %d, %d)\n", - xv, - yv, - zv, - (int)xt, - (int)yt, - (int)zt, - xc, - yc, - zc); -#endif - - return (gc); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - update the means using this set of images -------------------------------------------------------*/ -int GCarrayUpdateMeans(GCARRAY *gcarray, MRI *mris[], MRI *mri_target, int nimages) -{ - GCLASSIFY *gc; - GCLASS *gcl; - int x, y, z, xc, yc, zc, width, depth, height, scale, classno, swidth, sheight, sdepth; - // int nclasses, overlap; - BUFTYPE *psrc, *ptarget, src, target; - float *pzscore; - double xt, yt, zt, xv, yv, zv; - MRI *mri_src; - - mri_src = mris[0]; - - scale = gcarray->scale; - // overlap = MAX(1, scale / 4); - - width = gcarray->width; - height = gcarray->height; - depth = gcarray->depth; - // nclasses = NCLASSES; - - swidth = mri_src->width; - sheight = mri_src->height; - sdepth = mri_src->depth; - - /* - the classifiers are distributed in Talairach space, whereas the - input MR images are not (necessarily). Therefore we have to - transform the voxel coordinates into Tal. space before selecting - the training values. - */ - - /* - for each point in the image, find the its Talairach coordinates and - therefore the classifier responsible for it, and update it's mean. - */ - for (z = 0; z < sdepth; z++) { - for (y = 0; y < sheight; y++) { - psrc = &MRIvox(mris[0], 0, y, z); - ptarget = &MRIvox(mri_target, 0, y, z); - pzscore = &MRIFvox(mris[1], 0, y, z); - for (x = 0; x < swidth; x++) { - /* find the appropriate classifier for this location */ - MRIvoxelToTalairach(mri_src, (double)x, (double)y, (double)z, &xt, &yt, &zt); - xv = (xt - (double)gcarray->xstart); - zv = (yt - (double)gcarray->ystart); - yv = (-zt + (double)gcarray->zstart); - xc = nint(((xv)-scale / 2) / scale); - if (xc < 0) - xc = 0; - else if (xc >= width) - xc = width - 1; - yc = nint(((yv)-scale / 2) / scale); - if (yc < 0) - yc = 0; - else if (yc >= height) - yc = height - 1; - zc = nint(((zv)-scale / 2) / scale); - if (zc < 0) - zc = 0; - else if (zc >= depth) - zc = depth - 1; - - src = *psrc++; - target = *ptarget++; - /* decide what class it is */ - if (target) - classno = WHITE_MATTER; - else { - if (src < LO_LIM) - classno = BACKGROUND; - else if (src > HI_LIM) - classno = BRIGHT_MATTER; - else - classno = GREY_MATTER; - } - - gc = gcarray->gcs[zc][yc][xc]; - gcl = &gc->classes[classno]; - gcl->nobs++; - gcl->m_u->rptr[1][1] += (float)src; - gcl->m_u->rptr[2][1] += *pzscore++; - if (gcarray->nvars > 2) { - gcl->m_u->rptr[3][1] += (float)xt; - gcl->m_u->rptr[4][1] += (float)yt; - gcl->m_u->rptr[5][1] += (float)zt; - } - } - } - } - - return (ERROR_NONE); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - update the covariance estimates based on new observations -------------------------------------------------------*/ -int GCarrayUpdateCovariances(GCARRAY *gcarray, MRI *mris[], MRI *mri_target, int nimages) -{ - GCLASSIFY *gc; - GCLASS *gcl; - int x, y, z, xc, yc, zc, width, depth, height, scale, classno, swidth, sheight, sdepth, col, row; - // int nclasses, overlap; - BUFTYPE *psrc, *ptarget, src, target; - float *pzscore, obs[6], covariance; - double xt, yt, zt, xv, yv, zv; - MRI *mri_src; - - mri_src = mris[0]; - - scale = gcarray->scale; - // overlap = MAX(1, scale / 4); - - width = gcarray->width; - height = gcarray->height; - depth = gcarray->depth; - // nclasses = NCLASSES; - - swidth = mri_src->width; - sheight = mri_src->height; - sdepth = mri_src->depth; - - /* - the classifiers are distributed in Talairach space, whereas the - input MR images are not (necessarily). Therefore we have to - transform the voxel coordinates into Tal. space before selecting - the training values. - */ - - /* - for each point in the image, find the its Talairach coordinates and - therefore the classifier responsible for it, and update it's mean. - */ - for (z = 0; z < sdepth; z++) { - for (y = 0; y < sheight; y++) { - psrc = &MRIvox(mris[0], 0, y, z); - ptarget = &MRIvox(mri_target, 0, y, z); - pzscore = &MRIFvox(mris[1], 0, y, z); - for (x = 0; x < swidth; x++) { - /* find the appropriate classifier for this location */ - MRIvoxelToTalairach(mri_src, (double)x, (double)y, (double)z, &xt, &yt, &zt); - xv = (xt - (double)gcarray->xstart); - zv = (yt - (double)gcarray->ystart); - yv = (-zt + (double)gcarray->zstart); - xc = nint(((xv)-scale / 2) / scale); - if (xc < 0) - xc = 0; - else if (xc >= width) - xc = width - 1; - yc = nint(((yv)-scale / 2) / scale); - if (yc < 0) - yc = 0; - else if (yc >= height) - yc = height - 1; - zc = nint(((zv)-scale / 2) / scale); - if (zc < 0) - zc = 0; - else if (zc >= depth) - zc = depth - 1; - - src = *psrc++; - target = *ptarget++; - /* decide what class it is */ - if (target) - classno = WHITE_MATTER; - else { - if (src < LO_LIM) - classno = BACKGROUND; - else if (src > HI_LIM) - classno = BRIGHT_MATTER; - else - classno = GREY_MATTER; - } - - gc = gcarray->gcs[zc][yc][xc]; - gcl = &gc->classes[classno]; - obs[1] = (float)src - gcl->m_u->rptr[1][1]; - obs[2] = *pzscore++ - gcl->m_u->rptr[2][1]; - if (gcarray->nvars > 2) { - obs[3] = (float)xt - gcl->m_u->rptr[3][1]; - obs[4] = (float)yt - gcl->m_u->rptr[4][1]; - obs[5] = (float)zt - gcl->m_u->rptr[5][1]; - } - for (row = 1; row <= gcl->m_covariance->rows; row++) { - for (col = 1; col <= row; col++) { - covariance = obs[row] * obs[col]; - gcl->m_covariance->rptr[row][col] += covariance; - gcl->m_covariance->rptr[col][row] += covariance; - } - } - } - } - } - - return (ERROR_NONE); -} -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - compute the means for each class -------------------------------------------------------*/ -int GCarrayComputeMeans(GCARRAY *gcarray) -{ - GCLASSIFY *gc, **pgc; - GCLASS *gcl; - int x, y, z, width, depth, height, classno, nclasses, nobs, row; - - width = gcarray->width; - height = gcarray->height; - depth = gcarray->depth; - - /* - the classifiers are distributed in Talairach space, whereas the - input MR images are not (necessarily). Therefore we have to - transform the voxel coordinates into Tal. space before selecting - the training values. - */ - /* train each classifier, x,y,z are in classifier space */ - for (z = 0; z < depth; z++) { - for (y = 0; y < height; y++) { - pgc = gcarray->gcs[z][y]; - for (x = 0; x < width; x++) { - gc = *pgc++; - nclasses = gc->nclasses; - for (classno = 0; classno < nclasses; classno++) { - gcl = &gc->classes[classno]; - nobs = gcl->nobs; - if (nobs) { - for (row = 1; row <= gcl->m_u->rows; row++) gcl->m_u->rptr[row][1] /= (float)nobs; - } - } - } - } - } - return (NO_ERROR); -} - -/*----------------------------------------------------- - Parameters: - - Returns value: - - Description - compute the means for each class -------------------------------------------------------*/ -int GCarrayComputeCovariances(GCARRAY *gcarray) -{ - GCLASSIFY *gc, **pgc; - GCLASS *gcl; - int x, y, z, width, depth, height, classno, nclasses, row, col; - float nobs, covariance; - - width = gcarray->width; - height = gcarray->height; - depth = gcarray->depth; - - /* - the classifiers are distributed in Talairach space, whereas the - input MR images are not (necessarily). Therefore we have to - transform the voxel coordinates into Tal. space before selecting - the training values. - */ - /* train each classifier, x,y,z are in classifier space */ - for (z = 0; z < depth; z++) { - for (y = 0; y < height; y++) { - pgc = gcarray->gcs[z][y]; - for (x = 0; x < width; x++) { - gc = *pgc++; - nclasses = gc->nclasses; - for (classno = 0; classno < nclasses; classno++) { - gcl = &gc->classes[classno]; - nobs = (float)(gcl->nobs - 1); /* ML estimate of covariance */ - if (nobs > 0.0f) { - for (row = 1; row <= gcl->m_covariance->rows; row++) { - for (col = 1; col <= row; col++) { - covariance = gcl->m_covariance->rptr[row][col] / nobs; - gcl->m_covariance->rptr[row][col] = covariance; - gcl->m_covariance->rptr[col][row] = covariance; - } - } - } - GCinit(gc, classno); - } - } - } - } - return (NO_ERROR); -} diff --git a/utils/gclass.c b/utils/gclass.cpp similarity index 96% rename from utils/gclass.c rename to utils/gclass.cpp index 0d5a517efc1..5cb0aabc0e4 100644 --- a/utils/gclass.c +++ b/utils/gclass.cpp @@ -66,7 +66,7 @@ Description ------------------------------------------------------*/ -GCLASSIFY *GCalloc(int nclasses, int nvars, char *class_names[]) +GCLASSIFY *GCalloc(int nclasses, int nvars, const char *class_names[]) { GCLASSIFY *gc; GCLASS *gcl; @@ -157,11 +157,11 @@ GCLASSIFY *GCalloc(int nclasses, int nvars, char *class_names[]) is the # of observations, and the # of cols is the # of variables. ------------------------------------------------------*/ -int GCtrain(GCLASSIFY *gc, int class, MATRIX *m_inputs) +int GCtrain(GCLASSIFY *gc, int classnum, MATRIX *m_inputs) { GCLASS *gcl; - gcl = &gc->classes[class]; + gcl = &gc->classes[classnum]; gcl->nobs = m_inputs->rows; if (gcl->nobs == 0) /* no training data */ { @@ -174,7 +174,7 @@ int GCtrain(GCLASSIFY *gc, int class, MATRIX *m_inputs) #endif else MatrixCovariance(m_inputs, gcl->m_covariance, gcl->m_u); - return (GCinit(gc, class)); + return (GCinit(gc, classnum)); } /*----------------------------------------------------- Parameters: @@ -217,7 +217,7 @@ int GCfree(GCLASSIFY **pgc) ------------------------------------------------------*/ int GCclassify(GCLASSIFY *gc, MATRIX *m_x, MATRIX *m_priors, float *prisk) { - int cno, class = -1; + int cno, classnum = -1; GCLASS *gcl; static MATRIX *m_xT = NULL, *m_tmp, *m_tmp2, *m_tmp3; float log_p, max_p, sum_p, prior; @@ -235,7 +235,7 @@ int GCclassify(GCLASSIFY *gc, MATRIX *m_x, MATRIX *m_priors, float *prisk) } m_xT = MatrixTranspose(m_x, m_xT); max_p = -100000.0f; - class = -1; + classnum = -1; sum_p = 0.0f; for (cno = 0; cno < gc->nclasses; cno++) { gcl = &gc->classes[cno]; @@ -265,13 +265,13 @@ int GCclassify(GCLASSIFY *gc, MATRIX *m_x, MATRIX *m_priors, float *prisk) if (log_p > max_p) /* tentatively set this as the most probable class */ { max_p = log_p; - class = cno; + classnum = cno; } } - if (prisk && class >= 0 && !FZERO(sum_p)) *prisk = exp(max_p) / sum_p; + if (prisk && classnum >= 0 && !FZERO(sum_p)) *prisk = exp(max_p) / sum_p; - return (class); + return (classnum); } /*----------------------------------------------------- Parameters: @@ -371,13 +371,13 @@ GCLASS *GCasciiReadClassFrom(FILE *fp, GCLASS *gcl) static components. After this call, the classifier should be ready for use. ------------------------------------------------------*/ -int GCinit(GCLASSIFY *gc, int class) +int GCinit(GCLASSIFY *gc, int classnum) { GCLASS *gcl; MATRIX *m_sigma_inverse, *m_uT, *m_tmp, *m_tmp2; float det; - gcl = &gc->classes[class]; + gcl = &gc->classes[classnum]; if (gcl->nobs <= gc->nvars) /* not enough training data */ MatrixMakeDiagonal(gcl->m_covariance, gcl->m_covariance); diff --git a/utils/gcsa.c b/utils/gcsa.cpp similarity index 99% rename from utils/gcsa.c rename to utils/gcsa.cpp index 931b44edefc..6b97255c81d 100644 --- a/utils/gcsa.c +++ b/utils/gcsa.cpp @@ -622,7 +622,7 @@ GCSA *GCSAread(char *fname) else if (trace) fprintf(stdout, "GCSAread(%s): opened file", fname); magic = freadInt(fp); - if (magic != GCSA_MAGIC) + if ((unsigned)magic != GCSA_MAGIC) ErrorReturn(NULL, (ERROR_BADFILE, "GCSAread(%s): file magic #%x != GCSA_MAGIC (%x)", fname, magic, GCSA_MAGIC)); ninputs = freadInt(fp); icno_classifiers = freadInt(fp); @@ -637,7 +637,7 @@ GCSA *GCSAread(char *fname) for (i = 0; i < ninputs; i++) { gcsa->inputs[i].type = freadInt(fp); j = freadInt(fp); - if (fread(gcsa->inputs[i].fname, sizeof(char), j, fp) != j) { + if (fread(gcsa->inputs[i].fname, sizeof(char), j, fp) != (unsigned)j) { ErrorPrintf(ERROR_BADFILE, "afniRead(): error reading from file %s", gcsa->inputs[i].fname); } gcsa->inputs[i].navgs = freadInt(fp); @@ -906,7 +906,6 @@ int dump_gcsan(GCSA_NODE *gcsan, CP_NODE *cpn, FILE *fp, int verbose) { int n, index, i, j; GCS *gcs; - char *name; CP *cp; if (!cpn) return (NO_ERROR); @@ -914,7 +913,7 @@ int dump_gcsan(GCSA_NODE *gcsan, CP_NODE *cpn, FILE *fp, int verbose) fprintf(fp, "GCSAN with %d labels (%d training examples)\n", cpn->nlabels, cpn->total_training); for (n = 0; n < cpn->nlabels; n++) { cp = &cpn->cps[n]; - name = annotation_to_name(cpn->labels[n], &index); + const char *name = annotation_to_name(cpn->labels[n], &index); fprintf(fp, " %d: label %s (%d, %d)\n", n, name, index, cpn->labels[n]); gcs = getGC(gcsan, cpn->labels[n], NULL); if (!gcs) ErrorPrintf(ERROR_BADPARM, "dump_gcsan: could not find GCS for node %d!", n); diff --git a/utils/geodesics.cpp b/utils/geodesics.cpp index b5a47569bbf..52f6eaa12fe 100644 --- a/utils/geodesics.cpp +++ b/utils/geodesics.cpp @@ -12,14 +12,13 @@ #include "geodesics.h" -extern "C" { #include "macros.h" #include "mrisurf.h" #include "timer.h" + #ifdef _OPENMP #include "romp_support.h" #endif -} // Vertex struct Vertex @@ -53,11 +52,10 @@ static Vertex extendedPoint(Vertex A, Vertex B, float dA, float dB, float dAB); static std::pair< int, int > makeKey(int a, int b); static void progressBar(float progress); -extern "C" Geodesics *computeGeodesics(MRIS *surf, float maxdist) +Geodesics *computeGeodesics(MRIS *surf, float maxdist) { int msec; - struct timeb mytimer; - TimerStart(&mytimer); + Timer mytimer; printf("computeGeodesics(): maxdist = %g, nvertices = %d\n", maxdist, surf->nvertices); fflush(stdout); @@ -80,7 +78,7 @@ extern "C" Geodesics *computeGeodesics(MRIS *surf, float maxdist) triangle->inChain = false; } - msec = TimerStop(&mytimer); + msec = mytimer.milliseconds(); printf("precompute t = %g min\n", msec / (1000.0 * 60)); fflush(stdout); @@ -255,7 +253,7 @@ extern "C" Geodesics *computeGeodesics(MRIS *surf, float maxdist) } progressBar(1.0); std::cout << std::endl; - msec = TimerStop(&mytimer); + msec = mytimer.milliseconds(); printf("step 1 t = %g min\n", msec / (1000.0 * 60)); fflush(stdout); @@ -333,27 +331,27 @@ extern "C" Geodesics *computeGeodesics(MRIS *surf, float maxdist) progressBar(1.0); std::cout << std::endl; - msec = TimerStop(&mytimer); + msec = mytimer.milliseconds(); printf("t = %g min\n", msec / (1000.0 * 60)); fflush(stdout); return geo; } -extern "C" void geodesicsWrite(Geodesics *geo, int nvertices, char *fname) +void geodesicsWrite(Geodesics *geo, int nvertices, char *fname) { int vtxno; FILE *fp; int msec; - struct timeb mytimer; printf("geodesicsWrite(): uniquifying\n"); - TimerStart(&mytimer); + Timer mytimer; + #ifdef _OPENMP #pragma omp parallel for #endif for (vtxno = 0; vtxno < nvertices; vtxno++) geodesicsUniquify(&geo[vtxno]); - msec = TimerStop(&mytimer); + msec = mytimer.milliseconds(); printf(" uniquification took %g min\n", msec / (1000.0 * 60)); fp = fopen(fname, "wb"); @@ -368,7 +366,7 @@ extern "C" void geodesicsWrite(Geodesics *geo, int nvertices, char *fname) fclose(fp); } -extern "C" Geodesics *geodesicsRead(char *fname, int *pnvertices) +Geodesics *geodesicsRead(char *fname, int *pnvertices) { int magic, nthvtx; char tmpstr[1000]; @@ -422,7 +420,7 @@ extern "C" Geodesics *geodesicsRead(char *fname, int *pnvertices) \fn int geodesicsUniquify(Geodesics *geod) \brief Removes relicants from the v (and dist) lists; vnum is updated. */ -extern "C" int geodesicsUniquify(Geodesics *geod) +int geodesicsUniquify(Geodesics *geod) { int nthnbr, *vlist, nunique, k, *vuniq; float *dist; @@ -677,7 +675,6 @@ Geodesics* geodesicsReadV2(char* fname, int *pnvertices) FILE *fp; int vtxno,*vnum,*vlist,nth,nthnbr,nnbrstot; float *dist; - struct timeb mytimer; int msec; fp = fopen(fname, "rb"); @@ -702,30 +699,24 @@ Geodesics* geodesicsReadV2(char* fname, int *pnvertices) printf(" alloc vnum \n");fflush(stdout); vnum = (int *) calloc(sizeof(int),*pnvertices); printf(" reading in vnum %d \n",*pnvertices);fflush(stdout); - TimerStart(&mytimer) ; + Timer mytimer; fread(vnum,sizeof(int), *pnvertices, fp); - msec = TimerStop(&mytimer) ; + msec = mytimer.milliseconds() ; printf(" t = %g min\n",msec/(1000.0*60)); - //printf(" setting vnum %d\n",*pnvertices); - //for(vtxno = 0; vtxno < *pnvertices; vtxno++) - // geo[vtxno].vnum = vnum[vtxno]; - //free(vnum); - //msec = TimerStop(&mytimer) ; - //printf(" t = %g min\n",msec/(1000.0*60)); - - TimerStart(&mytimer) ; + + mytimer.reset(); printf(" allocing vlist and dlist %d\n",nnbrstot);fflush(stdout); vlist = (int *) calloc(sizeof(int), nnbrstot); dist = (float *) calloc(sizeof(float),nnbrstot); printf(" reading in vlist %d\n",nnbrstot);fflush(stdout); fread(vlist,sizeof(int), nnbrstot, fp); - msec = TimerStop(&mytimer); printf(" t = %g min\n",msec/(1000.0*60)); + msec = mytimer.milliseconds(); printf(" t = %g min\n",msec/(1000.0*60)); printf(" reading in dist %d\n",nnbrstot);fflush(stdout); fread(dist, sizeof(float), nnbrstot, fp); - msec = TimerStop(&mytimer); printf(" t = %g min\n",msec/(1000.0*60)); + msec = mytimer.milliseconds(); printf(" t = %g min\n",msec/(1000.0*60)); printf("Alloc geo\n"); Geodesics *geo = (Geodesics*) calloc(*pnvertices, sizeof(Geodesics)); - msec = TimerStop(&mytimer); printf(" t = %g min\n",msec/(1000.0*60)); + msec = mytimer.milliseconds(); printf(" t = %g min\n",msec/(1000.0*60)); printf("Setting\n"); nth = 0; for(vtxno = 0; vtxno < *pnvertices; vtxno++){ @@ -739,7 +730,7 @@ Geodesics* geodesicsReadV2(char* fname, int *pnvertices) free(vlist); free(dist); free(vnum); - msec = TimerStop(&mytimer); printf(" t = %g min\n",msec/(1000.0*60)); + msec = mytimer.milliseconds(); printf(" t = %g min\n",msec/(1000.0*60)); fclose(fp); diff --git a/utils/geos.c b/utils/geos.cpp similarity index 100% rename from utils/geos.c rename to utils/geos.cpp diff --git a/utils/getdelim.c b/utils/getdelim.cpp similarity index 100% rename from utils/getdelim.c rename to utils/getdelim.cpp diff --git a/utils/getline.c b/utils/getline.cpp similarity index 100% rename from utils/getline.c rename to utils/getline.cpp diff --git a/utils/gifti_local.c b/utils/gifti.cpp similarity index 99% rename from utils/gifti_local.c rename to utils/gifti.cpp index e449813c6a3..7fd22a21dc2 100644 --- a/utils/gifti_local.c +++ b/utils/gifti.cpp @@ -1,6 +1,6 @@ #define COMPILING_MRISURF_TOPOLOGY_FRIEND_CHECKED /** - * @file gifti_local.c + * @file gifti.c * @brief local utilities for GIFTI library * * This file has some some extra functions for use with the GIFTI @@ -35,7 +35,7 @@ #include #include "error.h" // return codes -#include "gifti_local.h" +#include "gifti.h" #include "nifti1.h" #include "timer.h" #include "utils.h" // strcpyalloc @@ -898,7 +898,7 @@ MRIS *mrisReadGIFTIdanum(const char *fname, MRIS *mris, int daNum) gifti_free_image(image); return NULL; } - unsigned int *label_data = darray->data; + unsigned int *label_data = (unsigned int *)darray->data; int nindex = 0; // index into node_index (if sparse data storage is used) int da_index = 0; // index into the data array at hand int vno = 0; // index into the mris struct (vertex number) @@ -1215,7 +1215,7 @@ static void insertCommonMetaData(giiMetaData *md) gifti_add_to_meta(md, "UserName", pw->pw_name, 1); } - gifti_add_to_meta(md, "Date", current_date_time(), 1); + gifti_add_to_meta(md, "Date", currentDateTime().c_str(), 1); } /*------------------------------------------------------------------------- @@ -1412,7 +1412,6 @@ int MRISwriteGIFTI(MRIS *mris, int intent_code, const char *out_fname, const cha if (mris->fname) { const char *primary = NULL, *secondary = NULL, *geotype = NULL; char *name = mris->fname; - char *topotype = "Closed"; if (strstr(name, "lh.")) { primary = "CortexLeft"; } @@ -1467,9 +1466,12 @@ int MRISwriteGIFTI(MRIS *mris, int intent_code, const char *out_fname, const cha if (strstr(name, "pial-outer")) { geotype = "Hull"; } + const char *topotype; if (mris->patch) { geotype = "Flat"; topotype = "Cut"; + } else { + topotype = "Closed"; } if (primary) gifti_add_to_meta(&coords->meta, "AnatomicalStructurePrimary", primary, 1); @@ -1571,7 +1573,7 @@ int MRISwriteGIFTI(MRIS *mris, int intent_code, const char *out_fname, const cha /* include some metadata describing this shape */ gifti_add_to_meta(&shape->meta, "Name", curv_fname, 1); - char *meta = NULL; + const char *meta = NULL; if (strstr(curv_fname, ".thickness")) { meta = "Thickness"; } @@ -1747,7 +1749,7 @@ int MRISwriteGIFTI(MRIS *mris, int intent_code, const char *out_fname, const cha } /* Copy our 'annotation' data for each vertex (actually an index) */ - unsigned int *label_data = labels->data; + unsigned int *label_data = (unsigned int *)labels->data; int label_index, theIdx, result; for (label_index = 0; label_index < mris->nvertices; label_index++) { if (mris->vertices[label_index].ripflag) { diff --git a/utils/gifti_test.c b/utils/gifti_test.c deleted file mode 100644 index 627004471f9..00000000000 --- a/utils/gifti_test.c +++ /dev/null @@ -1,448 +0,0 @@ -#include -#include -#include - -#include "gifti_io.h" - -#include "gifti_test.h" - -int show_help() -{ - fprintf(stderr, - "------------------------------------------------------------\n" - "gifti_test - test reading/writing a GIFTI dataset\n" - "\n" - " examples:\n" - " 1. read in a GIFTI dataset (verbose, show output?)\n" - "\n" - " gifti_test -infile dset.gii\n" - " gifti_test -infile dset.gii -verb 3\n" - " gifti_test -infile dset.gii -show\n" - "\n" - " 2. copy a GIFTI dataset (check differences?)\n" - "\n" - " gifti_test -infile dset.gii -gfile copy.gii\n" - " diff dset.gii copy.gii\n" - "\n" - " 3. copy a GIFTI data, but write out only 3 surf indices: 0,4,5\n" - "\n" - " gifti_test -infile time_series.gii -gfile ts3.gii \\\n" - " -slist 3 0 4 5\n" - "\n" - " options:\n" - " -help : show this help\n" - " -gifti_hist : show giftilib history\n" - " -gifti_ver : show giftilib version\n" - "\n" - " -encoding TYPE : set the data encoding for any output file\n" - " TYPE = ASCII : ASCII encoding\n" - " TYPE = BASE64 : base64 binary\n" - " TYPE = BASE64GZIP : base64 compressed binary\n" - " -gfile OUTPUT : write out dataset as gifti image\n" - " -infile INPUT : specify INPUT as the GIFTI dataset to read\n" - " -no_data : do not write out data\n" - " -show : show final gifti image\n" - " -slist LEN s0...: restrict output to list of length LEN\n" - " -verb VERB : set verbose level\n" - "------------------------------------------------------------\n"); - return 0; -} - -int main(int argc, char *argv[]) -{ - gifti_image *gim; - char *infile = NULL, *gfile = NULL; - int *slist = NULL, slen = 0; - int c, ac, show = 0, data = 1; - int encoding = 0; /* no change, else 1,2,3 */ - - if (argc <= 1) { - show_help(); - return 1; - } - - for (ac = 1; ac < argc; ac++) { - if (!strcmp(argv[ac], "-encoding")) { - ac++; - CHECK_NEXT_OPT(ac, argc, "-encoding"); - if (!strcmp(argv[ac], "ASCII")) - encoding = GIFTI_ENCODING_ASCII; - else if (!strcmp(argv[ac], "BASE64")) - encoding = GIFTI_ENCODING_B64BIN; - else if (!strcmp(argv[ac], "BASE64GZIP")) - encoding = GIFTI_ENCODING_B64GZ; - else { - fprintf(stderr, "** invalid parm to -encoding: %s\n", argv[ac]); - return 1; - } - } - else if (!strcmp(argv[ac], "-gifti_hist")) { - gifti_disp_lib_hist(); - return 0; - } - else if (!strcmp(argv[ac], "-gifti_ver")) { - gifti_disp_lib_version(); - return 0; - } - else if (!strcmp(argv[ac], "-gfile")) { - ac++; - CHECK_NEXT_OPT(ac, argc, "-gfile"); - gfile = argv[ac]; - } - else if (!strcmp(argv[ac], "-help")) { - show_help(); - return 1; - } - else if (!strcmp(argv[ac], "-infile")) { - ac++; - CHECK_NEXT_OPT(ac, argc, "-infile"); - infile = argv[ac]; - } - else if (!strcmp(argv[ac], "-no_data")) { - data = 0; - } - else if (!strcmp(argv[ac], "-show")) { - show = 1; - } - else if (!strcmp(argv[ac], "-slist")) { - ac++; - CHECK_NEXT_OPT(ac, argc, "-slist"); - slen = atol(argv[ac]); - if (slen <= 0) { - fprintf(stderr, "** bad -slist length, '%s'\n", argv[ac]); - return 1; - } - - slist = (int *)malloc(slen * sizeof(int)); - if (!slist) { - fprintf(stderr, "** failed alloc of len %d slist\n", slen); - return 1; - } - for (c = 0; c < slen; c++) { - ac++; - if (ac >= argc) { - fprintf(stderr, "** have only %d of %d -slist files\n", c, slen); - return 1; - } - slist[c] = atol(argv[ac]); - if (slist[c] < 0) { - fprintf(stderr, "** bad slist index[%d], '%s'\n", c, argv[ac]); - return 1; - } - } - } - else if (!strcmp(argv[ac], "-verb")) { - ac++; - CHECK_NEXT_OPT(ac, argc, "-verb"); - gifti_set_verb(atoi(argv[ac])); - } - else { - fprintf(stderr, "** unknown option: '%s'\n", argv[ac]); - return 1; - } - } - - /* be sure we have something to read */ - if (!infile) { - fprintf(stderr, "** missing option: -infile\n"); - return 1; - } - - /* actually read the dataset */ - gim = gifti_read_da_list(infile, 1, slist, slen); - if (!gim) { - fprintf(stderr, "** failed gifti_read_da_list()\n"); - return 1; - } - - if (show) gifti_disp_gifti_image("FINAL IMAGE", gim, 1); - - /* possibly adjust encoding */ - if (encoding > GIFTI_ENCODING_UNDEF && encoding <= GIFTI_ENCODING_MAX) - for (c = 0; c < gim->numDA; c++) - if (gim->darray[c]->encoding) gim->darray[c]->encoding = encoding; - - if (gfile) gifti_write_image(gim, gfile, data); - - /* clean up */ - gifti_free_image(gim); - gim = NULL; - - if (slist) { - free(slist); - slist = NULL; - slen = 0; - } - - return 0; -} - -int write_surf_file(giiDataArray *dc, giiDataArray *dt, char *prefix, int add_suf) -{ - giiDataArray *da; - FILE *fp; - char *name = prefix; - char *nbuf = NULL; - long long crows, ccols, trows, tcols, rows, cols, c; - - if (add_suf) { /* create a new name */ - nbuf = (char *)malloc(strlen(prefix) + strlen(".asc") + 1); - strcpy(nbuf, prefix); - strcat(nbuf, ".asc"); - name = nbuf; - } - - if (!(fp = fopen(name, "w"))) { - fprintf(stderr, "** failed to open '%s' for 'w'\n", name); - if (nbuf) free(nbuf); - return 1; - } - - /* note the number of rows and columns */ - if (gifti_DA_rows_cols(dc, &crows, &ccols)) { - fclose(fp); - if (nbuf) free(nbuf); - return 1; - } - else if (gifti_DA_rows_cols(dt, &trows, &tcols)) { - fclose(fp); - if (nbuf) free(nbuf); - return 1; - } - - fprintf(fp, - "#!ascii version of surface\n" - "%lld %lld\n", - crows, - trows); - - /* write out the coordinates */ - - da = dc; - rows = crows; - cols = ccols; - - if (da->ind_ord == GIFTI_IND_ORD_COL_MAJOR) { - fprintf(stderr, "-- writing coord rows in reverse order\n"); - for (c = rows - 1; c >= 0; c--) ewrite_data_line(da->data, da->datatype, c, cols, 0, 1, fp); - } - else { - fprintf(stderr, "-- writing coord rows in normal order\n"); - for (c = 0; c < rows; c++) ewrite_data_line(da->data, da->datatype, c, cols, 0, 1, fp); - } - - /* write out the triangles */ - - da = dt; - rows = trows; - cols = tcols; - - if (da->ind_ord == GIFTI_IND_ORD_COL_MAJOR) { - fprintf(stderr, "-- writing triangle rows in reverse order\n"); - for (c = rows - 1; c >= 0; c--) ewrite_data_line(da->data, da->datatype, c, cols, 0, 1, fp); - } - else { - fprintf(stderr, "-- writing triangle rows in normal order\n"); - for (c = 0; c < rows; c++) ewrite_data_line(da->data, da->datatype, c, cols, 0, 1, fp); - } - - fclose(fp); - - return 0; -} - -int ewrite_data_line(void *data, int type, int row, int cols, int spaces, int trail0, FILE *fp) -{ - int c; - if (!data || row < 0 || cols <= 0 || !fp) return 1; - - fprintf(fp, "%*s", spaces, " "); - switch (type) { - default: - fprintf(stderr, "** write_data_line, unknown type %d\n", type); - return -1; - case 2: { /* NIFTI_TYPE_UINT8 */ - unsigned char *ptr = (unsigned char *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%u ", ptr[c]); - break; - } - case 4: { /* NIFTI_TYPE_INT16 */ - short *ptr = (short *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%d ", ptr[c]); - break; - } - case 8: { /* NIFTI_TYPE_INT32 */ - int *ptr = (int *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%d ", ptr[c]); - break; - } - case 16: { /* NIFTI_TYPE_FLOAT32 */ - float *ptr = (float *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%f ", ptr[c]); - break; - } - case 32: { /* NIFTI_TYPE_COMPLEX64 */ - float *ptr = (float *)data + row * cols; - for (c = 0; c < 2 * cols; c += 2) fprintf(fp, "%f %f ", ptr[c], ptr[c + 1]); - break; - } - case 64: { /* NIFTI_TYPE_FLOAT64 */ - double *ptr = (double *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%f ", ptr[c]); - break; - } - case 128: { /* NIFTI_TYPE_RGB24 */ - unsigned char *ptr = (unsigned char *)data + row * cols; - for (c = 0; c < 3 * cols; c += 3) fprintf(fp, "%u %u %u ", ptr[c], ptr[c + 1], ptr[c + 2]); - break; - } - case 256: { /* NIFTI_TYPE_INT8 */ - char *ptr = (char *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%d ", ptr[c]); - break; - } - case 512: { /* NIFTI_TYPE_UINT16 */ - unsigned short *ptr = (unsigned short *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%u ", ptr[c]); - break; - } - case 768: { /* NIFTI_TYPE_UINT32 */ - unsigned int *ptr = (unsigned int *)data + row * cols; - for (c = 0; c < cols; c++) fprintf(fp, "%u ", ptr[c]); - break; - } - case 1024: { /* NIFTI_TYPE_INT64 */ - /* rcr - do we need to check #defines? */ - break; - } - case 1280: { /* NIFTI_TYPE_UINT64 */ - /* rcr - do we need to check #defines? */ - break; - } - case 1536: { /* NIFTI_TYPE_FLOAT128 */ - /* rcr - do we need to check #defines? */ - break; - } - case 1792: { /* NIFTI_TYPE_COMPLEX128 */ - double *ptr = (double *)data + row * cols; - for (c = 0; c < 2 * cols; c += 2) fprintf(fp, "%f %f ", ptr[c], ptr[c + 1]); - break; - } - case 2048: { /* NIFTI_TYPE_COMPLEX256 */ - /* rcr - do we need to check #defines? */ - break; - } - } - - if (trail0) fputs(" 0", fp); /* maybe write trailing zero */ - - fputc('\n', fp); - - return 0; -} - -/* write out as cols by rows (else we'd use ewrite_data_line) */ -int ewrite_many_lines(void **data, int type, long long cols, long long rows, int spaces, FILE *fp) -{ - long long r, c; - - if (!data || rows == 0 || cols == 0 || !fp) return 1; - - fprintf(fp, "%*s", spaces, " "); - switch (type) { - default: - fprintf(stderr, "** write_data_line, unknown type %d\n", type); - return -1; - case 2: { /* NIFTI_TYPE_UINT8 */ - unsigned char **ptr = (unsigned char **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%u ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 4: { /* NIFTI_TYPE_INT16 */ - short **ptr = (short **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%d ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 8: { /* NIFTI_TYPE_INT32 */ - int **ptr = (int **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%d ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 16: { /* NIFTI_TYPE_FLOAT32 */ - float **ptr = (float **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%f ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 32: { /* NIFTI_TYPE_COMPLEX64 */ - break; - } - case 64: { /* NIFTI_TYPE_FLOAT64 */ - double **ptr = (double **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%f ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 128: { /* NIFTI_TYPE_RGB24 */ - break; - } - case 256: { /* NIFTI_TYPE_INT8 */ - char **ptr = (char **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%d ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 512: { /* NIFTI_TYPE_UINT16 */ - unsigned short **ptr = (unsigned short **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%u ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 768: { /* NIFTI_TYPE_UINT32 */ - unsigned int **ptr = (unsigned int **)data; - for (r = 0; r < rows; r++) { - for (c = 0; c < cols; c++) fprintf(fp, "%u ", ptr[c][r]); - fputc('\n', fp); - } - break; - } - case 1024: { /* NIFTI_TYPE_INT64 */ - /* rcr - do we need to check #defines? */ - break; - } - case 1280: { /* NIFTI_TYPE_UINT64 */ - /* rcr - do we need to check #defines? */ - break; - } - case 1536: { /* NIFTI_TYPE_FLOAT128 */ - /* rcr - do we need to check #defines? */ - break; - } - case 1792: { /* NIFTI_TYPE_COMPLEX128 */ - break; - } - case 2048: { /* NIFTI_TYPE_COMPLEX256 */ - /* rcr - do we need to check #defines? */ - break; - } - } - - return 0; -} diff --git a/utils/gifti_test.h b/utils/gifti_test.h deleted file mode 100644 index 7b79d635d47..00000000000 --- a/utils/gifti_test.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef GIFTI_TEST_H -#define GIFTI_TEST_H - -#define CHECK_NEXT_OPT(n, m, str) \ - do { \ - if ((n) >= (m)) { \ - fprintf(stderr, "** option '%s': missing parameter\n", str); \ - fprintf(stderr, " consider: 'prog -help'\n"); \ - return 1; \ - } \ - } while (0) -#define CHECK_NEXT_OPT2(n, m, s1, s2) \ - do { \ - if ((n) >= (m)) { \ - fprintf(stderr, "** option '%s': missing parameter '%s'\n", s1, s2); \ - fprintf(stderr, " consider: 'prog -help'\n"); \ - return 1; \ - } \ - } while (0) - -int ewrite_data_line(void *, int, int, int, int, int, FILE *); -int ewrite_many_lines(void **, int, long long, long long, int, FILE *); -int write_surf_file(giiDataArray *, giiDataArray *, char *, int); - -#endif /* GIFTI_TEST_H */ diff --git a/utils/gtm.c b/utils/gtm.cpp similarity index 98% rename from utils/gtm.c rename to utils/gtm.cpp index 7357e1341f2..23a8e3089d8 100644 --- a/utils/gtm.c +++ b/utils/gtm.cpp @@ -92,8 +92,7 @@ int MRIgtmSeg(GTMSEG *gtmseg) int err, *segidlist, nsegs, n; char *SUBJECTS_DIR, tmpstr[5000]; MRI *apas, *aseg, *hrseg, *ctxseg; - struct timeb timer; - TimerStart(&timer); + Timer timer; printf("Starting MRIgtmSeg() USF=%d\n", gtmseg->USF); @@ -111,7 +110,7 @@ int MRIgtmSeg(GTMSEG *gtmseg) MRIfree(&apas); printf("Loading surfaces "); - printf(" t = %6.4f\n", TimerStop(&timer) / 1000.0); + printf(" t = %6.4f\n", timer.seconds()); fflush(stdout); sprintf(tmpstr, "%s/%s/surf/lh.white", SUBJECTS_DIR, gtmseg->subject); gtmseg->lhw = MRISread(tmpstr); @@ -130,7 +129,7 @@ int MRIgtmSeg(GTMSEG *gtmseg) if (gtmseg->rhp == NULL) return (1); printf("Loading annotations "); - printf(" t = %6.4f\n", TimerStop(&timer) / 1000.0); + printf(" t = %6.4f\n", timer.seconds()); fflush(stdout); if (gtmseg->wmannotfile != NULL) { sprintf(tmpstr, "%s/%s/label/lh.%s", SUBJECTS_DIR, gtmseg->subject, gtmseg->wmannotfile); @@ -203,7 +202,7 @@ int MRIgtmSeg(GTMSEG *gtmseg) // Upsample the segmentation printf("Upsampling segmentation USF = %d", gtmseg->USF); fflush(stdout); - printf(" t = %6.4f\n", TimerStop(&timer) / 1000.0); + printf(" t = %6.4f\n", timer.seconds()); fflush(stdout); hrseg = MRIhiresSeg(aseg, gtmseg->lhw, gtmseg->lhp, gtmseg->rhw, gtmseg->rhp, gtmseg->USF, >mseg->anat2seg); if (hrseg == NULL) return (1); @@ -213,7 +212,7 @@ int MRIgtmSeg(GTMSEG *gtmseg) // Label cortex (like aparc+aseg) printf("Beginning cortical segmentation using %s", gtmseg->ctxannotfile); fflush(stdout); - printf(" t = %6.4f\n", TimerStop(&timer) / 1000.0); + printf(" t = %6.4f\n", timer.seconds()); fflush(stdout); ctxseg = MRIannot2CorticalSeg(hrseg, gtmseg->lhw, gtmseg->lhp, gtmseg->rhw, gtmseg->rhp, NULL, NULL); MRIfree(&hrseg); @@ -222,7 +221,7 @@ int MRIgtmSeg(GTMSEG *gtmseg) if (gtmseg->wmannotfile != NULL) { printf("Beginning WM segmentation using %s", gtmseg->wmannotfile); fflush(stdout); - printf(" t = %6.4f\n", TimerStop(&timer) / 1000.0); + printf(" t = %6.4f\n", timer.seconds()); fflush(stdout); ctxseg = MRIannot2CerebralWMSeg(ctxseg, gtmseg->lhw, gtmseg->rhw, gtmseg->dmax, NULL, ctxseg); } @@ -263,7 +262,7 @@ int MRIgtmSeg(GTMSEG *gtmseg) gtmseg->segidlist = segidlist; gtmseg->nsegs = nsegs; - printf("MRIgtmSeg() done, t = %6.4f\n", TimerStop(&timer) / 1000.0); + printf("MRIgtmSeg() done, t = %6.4f\n", timer.seconds()); fflush(stdout); return (0); } @@ -975,7 +974,6 @@ int GTMnPad(GTM *gtm) */ int GTMsolve(GTM *gtm) { - struct timeb timer; int n, f; double sum; @@ -986,9 +984,9 @@ int GTMsolve(GTM *gtm) if (!gtm->Optimizing) printf("Computing XtX ... "); fflush(stdout); - TimerStart(&timer); + Timer timer; gtm->XtX = MatrixMtM(gtm->X, gtm->XtX); - if (!gtm->Optimizing) printf(" %4.1f sec\n", TimerStop(&timer) / 1000.0); + if (!gtm->Optimizing) printf(" %4.1f sec\n", timer.seconds()); fflush(stdout); gtm->iXtX = MatrixInverse(gtm->XtX, gtm->iXtX); @@ -1162,7 +1160,6 @@ int GTMrbv(GTM *gtm) int c, r, s, f, nthseg, segid; double val, v, vhat0, vhat, v2; LTA *lta; - struct timeb mytimer; MATRIX *nhits; MRI *yframe = NULL; MRI_REGION *region = NULL; @@ -1172,7 +1169,7 @@ int GTMrbv(GTM *gtm) if (gtm->rbv) MRIfree(>m->rbv); - TimerStart(&mytimer); + Timer mytimer; PrintMemUsage(stdout); if (gtm->mask_rbv_to_brain) { @@ -1235,14 +1232,14 @@ int GTMrbv(GTM *gtm) // Keep track of segmeans in RBV for QA gtm->rbvsegmean = MRIallocSequence(gtm->nsegs, 1, 1, MRI_FLOAT, gtm->nframes); - printf("RBV looping over %d frames, t = %4.2f min \n", gtm->nframes, TimerStop(&mytimer) / 60000.0); + printf("RBV looping over %d frames, t = %4.2f min \n", gtm->nframes, mytimer.minutes()); fflush(stdout); for (f = 0; f < gtm->nframes; f++) { - printf(" f=%d t = %4.2f\n", f, TimerStop(&mytimer) / 60000.0); + printf(" f=%d t = %4.2f\n", f, mytimer.minutes()); fflush(stdout); yframe = fMRIframe(gtm->yvol, f, yframe); - printf(" Synthesizing unsmoothed input in seg space %4.2f \n", TimerStop(&mytimer) / 60000.0); + printf(" Synthesizing unsmoothed input in seg space %4.2f \n", mytimer.minutes()); fflush(stdout); if (Gdiag_no > 0) PrintMemUsage(stdout); yhat0seg = GTMsegSynth(gtm, f, yhat0seg); @@ -1251,7 +1248,7 @@ int GTMrbv(GTM *gtm) return (1); } - printf(" Smoothing synthesized in seg space %4.2f \n", TimerStop(&mytimer) / 60000.0); + printf(" Smoothing synthesized in seg space %4.2f \n", mytimer.minutes()); fflush(stdout); if (Gdiag_no > 0) PrintMemUsage(stdout); yhatseg = MRIgaussianSmoothNI(yhat0seg, gtm->cStd, gtm->rStd, gtm->sStd, yhatseg); @@ -1260,7 +1257,7 @@ int GTMrbv(GTM *gtm) return (1); } - printf(" Sampling input to seg space with trilin %4.2f \n", TimerStop(&mytimer) / 60000.0); + printf(" Sampling input to seg space with trilin %4.2f \n", mytimer.minutes()); fflush(stdout); if (Gdiag_no > 0) PrintMemUsage(stdout); lta = LTAcopy(gtm->rbvseg2pet, NULL); @@ -1268,7 +1265,7 @@ int GTMrbv(GTM *gtm) MRIvol2Vol(yframe, yseg, (lta->xforms[0].m_L), SAMPLE_TRILINEAR, 0.0); LTAfree(<a); - printf(" Computing RBV %4.2f \n", TimerStop(&mytimer) / 60000.0); + printf(" Computing RBV %4.2f \n", mytimer.minutes()); fflush(stdout); if (Gdiag_no > 0) PrintMemUsage(stdout); nhits = MatrixAlloc(gtm->beta->rows, 1, MATRIX_REAL); @@ -1305,7 +1302,7 @@ int GTMrbv(GTM *gtm) } } if (Gdiag_no > 0) PrintMemUsage(stdout); - printf(" t = %4.2f min\n", TimerStop(&mytimer) / 60000.0); + printf(" t = %4.2f min\n", mytimer.minutes()); fflush(stdout); MRIfree(&yseg); MRIfree(&yhat0seg); @@ -1323,7 +1320,7 @@ int GTMrbv(GTM *gtm) MatrixFree(&nhits); PrintMemUsage(stdout); - printf(" RBV took %4.2f min\n", TimerStop(&mytimer) / 60000.0); + printf(" RBV took %4.2f min\n", mytimer.minutes()); return (0); } @@ -1375,13 +1372,12 @@ int GTMrbv0(GTM *gtm) int c, r, s, f, nthseg, segid; double val, v, vhat0, vhat, v2; LTA *lta; - struct timeb mytimer; MATRIX *nhits; MRI *yseg; // source volume trilin resampled to seg space (used with RBV) MRI *yhat0seg; // unsmoothed yhat created in seg space (used with RBV) MRI *yhatseg; // smoothed yhat in seg space (used with RBV) - TimerStart(&mytimer); + Timer mytimer; printf(" Synthesizing unsmoothed input in seg space... "); fflush(stdout); @@ -1391,7 +1387,7 @@ int GTMrbv0(GTM *gtm) printf("ERROR: GTMrbv0() could not synthesize yhat0seg\n"); return (1); } - printf(" t = %4.2f min\n", TimerStop(&mytimer) / 60000.0); + printf(" t = %4.2f min\n", mytimer.minutes()); fflush(stdout); printf(" Smoothing synthesized in seg space... "); @@ -1402,7 +1398,7 @@ int GTMrbv0(GTM *gtm) printf("ERROR: GTMrbv0() could not smooth yhatseg\n"); return (1); } - printf(" t = %4.2f min\n", TimerStop(&mytimer) / 60000.0); + printf(" t = %4.2f min\n", mytimer.minutes()); fflush(stdout); printf(" Sampling input to seg space with trilin... "); @@ -1416,7 +1412,7 @@ int GTMrbv0(GTM *gtm) } MRIcopyHeader(gtm->anatseg, yseg); MRIcopyPulseParameters(gtm->yvol, yseg); - printf(" t = %4.2f min\n", TimerStop(&mytimer) / 60000.0); + printf(" t = %4.2f min\n", mytimer.minutes()); fflush(stdout); lta = LTAcopy(gtm->rbvseg2pet, NULL); @@ -1464,7 +1460,7 @@ int GTMrbv0(GTM *gtm) MRIfree(&yseg); MRIfree(&yhat0seg); MRIfree(&yhatseg); - printf(" t = %4.2f min\n", TimerStop(&mytimer) / 60000.0); + printf(" t = %4.2f min\n", mytimer.minutes()); fflush(stdout); // track seg means for QA @@ -1507,7 +1503,7 @@ int GTMrbv0(GTM *gtm) gtm->rbv = rbvtmp; } PrintMemUsage(stdout); - printf(" RBV took %4.2f min\n", TimerStop(&mytimer) / 60000.0); + printf(" RBV took %4.2f min\n", mytimer.minutes()); return (0); } @@ -1867,7 +1863,6 @@ int GTMcheckX(MATRIX *X) int GTMbuildX(GTM *gtm) { int nthseg, err; - struct timeb timer; if (gtm->X == NULL || gtm->X->rows != gtm->nmask || gtm->X->cols != gtm->nsegs) { // Alloc or realloc X @@ -1888,7 +1883,7 @@ int GTMbuildX(GTM *gtm) } gtm->dof = gtm->X->rows - gtm->X->cols; - TimerStart(&timer); + Timer timer; err = 0; ROMP_PF_begin @@ -1903,7 +1898,6 @@ int GTMbuildX(GTM *gtm) MRI_REGION *region; MB2D *mb; segid = gtm->segidlist[nthseg]; - // printf("nthseg = %d, %d %6.4f\n",nthseg,segid,TimerStop(&timer)/1000.0);fflush(stdout); if (gtm->DoVoxFracCor) nthsegpvf = fMRIframe(gtm->segpvf, nthseg, NULL); // extract PVF for this seg else @@ -1978,7 +1972,7 @@ int GTMbuildX(GTM *gtm) } ROMP_PF_end - if (!gtm->Optimizing) printf(" Build time %6.4f, err = %d\n", TimerStop(&timer) / 1000.0, err); + if (!gtm->Optimizing) printf(" Build time %6.4f, err = %d\n", timer.seconds(), err); fflush(stdout); if (err) gtm->X = NULL; @@ -2594,7 +2588,6 @@ int GTMrvarGM(GTM *gtm) */ MRI **GTMlocal(GTM *gtm, MRI **pvc) { - struct timeb timer; int const nTT = gtm->ttpvf->nframes; MRI * const pvfpsf = MRIgaussianSmoothNI(gtm->ttpvf, gtm->cStd, gtm->rStd, gtm->sStd, NULL); @@ -2642,7 +2635,7 @@ MRI **GTMlocal(GTM *gtm, MRI **pvc) int const nvmax = (2 * gtm->lgtm->nrad + 1) * (2 * gtm->lgtm->nrad + 1) * (2 * gtm->lgtm->nrad + 1); printf("GTMlocal(): nrad = %d, nvmax = %d, nTT=%d, Xthresh %f\n", gtm->lgtm->nrad, nvmax, nTT, gtm->lgtm->Xthresh); - TimerStart(&timer); + Timer timer; int c; ROMP_PF_begin @@ -2782,7 +2775,7 @@ MRI **GTMlocal(GTM *gtm, MRI **pvc) printf("\n"); // printf("nNull=%d\n",nNull); - printf("t=%6.4f\n", TimerStop(&timer) / 1000.0); + printf("t=%6.4f\n", timer.seconds()); printf("GTMlocal(); done\n"); fflush(stdout); diff --git a/utils/gw_ic2562.c b/utils/gw_ic2562.cpp similarity index 100% rename from utils/gw_ic2562.c rename to utils/gw_ic2562.cpp diff --git a/utils/gw_utils.c b/utils/gw_utils.cpp similarity index 99% rename from utils/gw_utils.c rename to utils/gw_utils.cpp index fcfc1b69fe3..22b0474edf5 100644 --- a/utils/gw_utils.c +++ b/utils/gw_utils.cpp @@ -292,7 +292,7 @@ static void nowstr(char *buf) } //------------------------------ -void gw_log_timestamp(char *label) +void gw_log_timestamp(const char *label) { //------------------------------ char datestr[100]; diff --git a/utils/handle.c b/utils/handle.c deleted file mode 100644 index ca7353b9e65..00000000000 --- a/utils/handle.c +++ /dev/null @@ -1,220 +0,0 @@ -/** - * @file handle.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.8 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/*---------------------------------------------------------------------- - - File Name: handle.c - - Description: control access to pointers through handles. - -----------------------------------------------------------------------*/ - -/*----------------------------------------------------------------- - INCLUDE FILES ------------------------------------------------------------------*/ - -#ifndef Linux -int not_used_000(void); - -int not_used_000(void) -{ - int i; - i = 0; - return (i); -} - -#else - -#include -#include -#include - -#include "error.h" -#include "handle.h" -#include "machine.h" - -/*----------------------------------------------------------------- -MACROS AND CONSTANTS ------------------------------------------------------------------*/ - -#define DEFAULT_MAX_HANDLES 100 -#define MAX_HANDLES (0x7fff) -#define HANDLE_FREE 0 -#define HANDLE_ALLOCATED 1 - -#ifndef ULONG -#define ULONG unsigned long -#endif - -/*---------------------------------------------------------------------- -STRUCTURES -----------------------------------------------------------------------*/ - -typedef struct -{ - void *ptr; - int status; -} HandleInfo; - -/*----------------------------------------------------------------- -PROTOTYPES ------------------------------------------------------------------*/ - -static void growHandleTable(void); - -/*----------------------------------------------------------------- -STATIC DATA ------------------------------------------------------------------*/ - -static HandleInfo *handleTable; -static int maxHandles = 0L; -static int nhandles = 0L; -static int freeHandles = 0L; - -/*----------------------------------------------------------------- -FUNCTIONS ------------------------------------------------------------------*/ - -/*---------------------------------------------------------------------- -Parameters: - -Description: -Allocate a new handle and assign the given pointer to it. -If the current handle space is used up, grow the handle table. - -Returns: -the newly allocated handle. -----------------------------------------------------------------------*/ -PTR_HANDLE -HandleAlloc(void *ptr) -{ - HandleInfo *handleInfo; - PTR_HANDLE handle; - - if (nhandles >= maxHandles) growHandleTable(); - - handle = ++nhandles; - handleInfo = handleTable + (handle - 1); - handleInfo->ptr = ptr; - handleInfo->status = HANDLE_ALLOCATED; - - return (handle); -} -/*---------------------------------------------------------------------- -Parameters: - -Description: -Free a previously allocated handle. - -Returns: -nothing. -----------------------------------------------------------------------*/ -void HandleFree(PTR_HANDLE handle) -{ - HandleInfo *handleInfo; - - if (HandleOk(handle) <= 0) ESCAPE(ERROR_BADPARM, "HandleFree: bad handle %d", handle); - - handleInfo = handleTable + (handle - 1); - - freeHandles++; - handleInfo->status = HANDLE_FREE; - handleInfo->ptr = NULL; -} -/*---------------------------------------------------------------------- -Parameters: - -Description: -turn a handle into the pointer which it reprents. - -Returns: -the pointer which the handle represents. -----------------------------------------------------------------------*/ -void *HandleToPtr(PTR_HANDLE handle) -{ - HandleInfo *handleInfo; - - if (HandleOk(handle) <= 0) ESCAPE(ERROR_BADPARM, "HandleToPtr: bad handle %d", handle); - - handleInfo = handleTable + (handle - 1); - - return (handleInfo->ptr); -} -/*---------------------------------------------------------------------- -Parameters: - -Description: -determine whether a handle is a valid one. - -Returns: -1 if the handle is ok and allocated. --1 if the handle is ok and not allocated -0 if the handle is out of range. -----------------------------------------------------------------------*/ -int HandleOk(PTR_HANDLE handle) -{ - HandleInfo *handleInfo; - - if ((handle <= (PTR_HANDLE)0) || (handle > nhandles)) return (0); - - handleInfo = handleTable + (handle - 1); - if (handleInfo->status == HANDLE_FREE) return (-1); - - return (1); -} -/*---------------------------------------------------------------------- -Parameters: - -Description: -We have run out of room for more handles. Free the current -handle table, and allocate one twice as large, moving all -the current information into it. - -Returns: -nothing. -----------------------------------------------------------------------*/ -static void growHandleTable(void) -{ - HandleInfo *newTable; - int newMaxHandles = 0; - - if (!maxHandles) - newMaxHandles = DEFAULT_MAX_HANDLES; - else if (maxHandles < MAX_HANDLES) - newMaxHandles = maxHandles << 1; - - if (newMaxHandles <= 0) ESCAPE(ERROR_NO_MEMORY, "growHandleTable: too many handles"); - - newTable = (HandleInfo *)calloc((long)newMaxHandles, sizeof(HandleInfo)); - if (maxHandles > 0) /* not the first time */ - { - hmemmove((long huge *)newTable, (long huge *)handleTable, (ULONG)maxHandles * sizeof(HandleInfo)); - free(handleTable); - } - maxHandles = newMaxHandles; - handleTable = newTable; -} - -#endif diff --git a/utils/heap.c b/utils/heap.c deleted file mode 100644 index 4dafce636aa..00000000000 --- a/utils/heap.c +++ /dev/null @@ -1,528 +0,0 @@ -/** - * @file heap.c - * @brief list utils - * - */ -/* - * Original Author: Xaio Han - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2008/03/10 13:35:25 $ - * $Revision: 1.3 $ - * - * General inquiries: freesurfer@nmr.mgh.harvard.edu - * Bug reports: analysis-bugs@nmr.mgh.harvard.edu - * - */ - -#include "heap.h" -#include -#include -#include - -#define INCREMENT 1000 - -/*--------------------------------------------------------------------------- -// Construct an empty PGlist with specified capacity and capacity increment -//-------------------------------------------------------------------------*/ -PGlist pgList2(int elementSize, int capacity, int capacityIncrement) -{ - PGlist list; - void *data; - - if (elementSize < 1) { - fprintf(stderr, "pgList(): elementSize must be a postive integer!\n"); - exit(1); - } - if (capacity < 0) { - fprintf(stderr, "pgList(): capacity must not be negative!\n"); - exit(1); - } - - list = (PGlist)malloc(sizeof(PGlistStruct)); - - pgListSetElementSize(list, elementSize); - pgListSetSize(list, 0); - pgListSetCapacity(list, capacity); - pgListSetCapacityIncrement(list, capacityIncrement); - if (capacity == 0) - pgListSetData(list, NULL); - else { - data = (void *)malloc(elementSize * capacity); - pgListSetData(list, data); - } - - return (list); -} - -/*--------------------------------------------------------------------------- -// Construct an empty PGlist with specified capacity and default -// capacity increment as 100 -//-------------------------------------------------------------------------*/ -PGlist pgList1(int elementSize, int capacity) -{ - PGlist list; - - list = pgList2(elementSize, capacity, 100); - - return (list); -} - -/*--------------------------------------------------------------------------- -// Construct an empty PGlist with default capacity as 0 and -// capacity increment as 100 -//-------------------------------------------------------------------------*/ -PGlist pgList(int elementSize) -{ - PGlist list; - - list = pgList2(elementSize, 0, 100); - - return (list); -} - -/*--------------------------------------------------------------------------- -// Construct an empty PGlist with specified size, all the elements are set to -// zero -//-------------------------------------------------------------------------*/ -PGlist pgListOfSize(int size, int elementSize) -{ - PGlist list; - char *data; - int i; - int capacity, capacityIncrement; - - if (size < 0) { - fprintf(stderr, "pgListOfSize(): size must not be negative!\n"); - exit(1); - } - - capacity = size; - capacityIncrement = 100; - list = pgList2(elementSize, capacity, capacityIncrement); - pgListSetSize(list, size); - data = (char *)pgListData(list); - for (i = 0; i < elementSize * size; i++) data[i] = 0; - - return (list); -} - -/*--------------------------------------------------------------------------- -// Delete this list -//-------------------------------------------------------------------------*/ -void pgListDelete(PGlist list) -{ - void *data; - - data = pgListData(list); - free(data); - free(list); -} - -/*--------------------------------------------------------------------------- -// Add an element to this list -//-------------------------------------------------------------------------*/ -void pgListAddElement(PGlist list, void *element) -{ - int size, capacity, elementSize, capacityIncrement; - void *data; - - size = pgListSize(list); - capacity = pgListCapacity(list); - elementSize = pgListElementSize(list); - data = pgListData(list); - if (size >= capacity) { - capacityIncrement = pgListCapacityIncrement(list); - if (data == NULL) { - /* initial list */ - capacity += capacityIncrement; - pgListSetCapacity(list, capacity); - data = (void *)malloc(elementSize * capacity); - } - else { - /* allocate a larger list */ - capacity += capacityIncrement; - pgListSetCapacity(list, capacity); - data = (void *)realloc(data, elementSize * capacity); - } - pgListSetData(list, data); - } - - memmove((char *)data + size * elementSize, (char *)element, elementSize); - pgListSetSize(list, size + 1); -} - -/*--------------------------------------------------------------------------- -// Insert an element into the list at the specified index -//-------------------------------------------------------------------------*/ -int pgListInsertElementAt(PGlist list, int index, void *element) -{ - int size, elementSize; - void *data; - void *tempPtr; - char *currentPtr, *nextPtr; - int i; - - size = pgListSize(list); - elementSize = pgListElementSize(list); - - if (index < 0 || index > size - 1) { - return (-1); /* out of bound error */ - } - - tempPtr = (void *)malloc(elementSize); - pgListAddElement(list, tempPtr); - - data = pgListData(list); - - for (i = size - 1; i >= index; i--) { - currentPtr = (char *)data + i * elementSize; - nextPtr = (char *)currentPtr + elementSize; - memmove(nextPtr, currentPtr, elementSize); - } - - memmove((char *)data + index * elementSize, (char *)element, elementSize); - - return (0); -} - -/*--------------------------------------------------------------------------- -// Retrieve an element from this list at a given index -//-------------------------------------------------------------------------*/ -int pgListElementAt(PGlist list, int index, void *element) -{ - int size, elementSize; - void *data; - - size = pgListSize(list); - elementSize = pgListElementSize(list); - data = pgListData(list); - - if (index < 0 || index > size - 1) { - return (-1); /* out of bound error */ - } - memmove((char *)element, (char *)data + index * elementSize, elementSize); - - return (0); -} - -/*--------------------------------------------------------------------------- -// Sets a list element at a given index -//-------------------------------------------------------------------------*/ -int pgListSetElementAt(PGlist list, int index, void *element) -{ - int size, elementSize; - void *data; - - size = pgListSize(list); - elementSize = pgListElementSize(list); - data = pgListData(list); - - if (index < 0 || index > size - 1) { - return (-1); /* out of bound error */ - } - - memmove((char *)data + index * elementSize, (char *)element, elementSize); - - return (0); -} - -/*--------------------------------------------------------------------------- -// Removes all elements from this list and sets its size to zero -//-------------------------------------------------------------------------*/ -int pgListRemoveElementAt(PGlist list, int index) -{ - int size, elementSize; - void *data; - char *currentPtr, *nextPtr; - int i; - - size = pgListSize(list); - elementSize = pgListElementSize(list); - data = pgListData(list); - - if (index < 0 || index > size - 1) { - return (-1); /* out of bound error */ - } - - for (i = index; i < size - 1; i++) { - currentPtr = (char *)data + i * elementSize; - nextPtr = (char *)currentPtr + elementSize; - memmove(currentPtr, nextPtr, elementSize); - } - - pgListSetSize(list, size - 1); - - return (0); -} - -/*--------------------------------------------------------------------------- -// Removes all elements from this list and sets its size to zero -//-------------------------------------------------------------------------*/ -void pgListRemoveAllElements(PGlist list) { pgListSetSize(list, 0); } - -/*--------------------------------------------------------------------------- -// Trim this list to current size -//-------------------------------------------------------------------------*/ -void pgListTrim(PGlist list) -{ - void *data; - int size, elementSize; - - size = pgListSize(list); - elementSize = pgListElementSize(list); - data = pgListData(list); - - data = (void *)realloc(data, elementSize * size); - pgListSetData(list, data); - pgListSetCapacity(list, size); -} - -void pgListInfo(PGlist list) -{ - int elementSize, size, capacity, capacityIncrement; - - elementSize = pgListElementSize(list); - size = pgListSize(list); - capacity = pgListCapacity(list); - capacityIncrement = pgListCapacityIncrement(list); - - printf(" elementSize = %d\n", elementSize); - printf(" size = %d\n", size); - printf(" capacity = %d\n", capacity); - printf(" capacityIncrement = %d\n", capacityIncrement); - printf("\n"); -} - -Xheap xhInitEmpty() -{ - Xheap H; - XheapElement he; - - H = (Xheap)pgList2(sizeof(XheapElement), 0, INCREMENT); - - /* assume that a[0] = smallest floating point such as -1e33 - serve as sentinel for stopping condition. - heap starts from 1 */ - he.value = 1e-34; /* not used in UpHeap anymore */ - he.id = -1; - - pgListAddElement(H, &he); - - return (H); -} - -Xheap xhInit(XheapElement *array, int N) -{ - Xheap H; - XheapElement *data, he; - int i, *p; - - H = (Xheap)pgList2(sizeof(XheapElement), 0, INCREMENT); - - he.value = 1e-34; - he.id = -1; - - pgListAddElement(H, &he); - pgListSetSize(H, N + 1); - - data = (XheapElement *)pgListData(H); - for (i = 1; i <= N; i++) { - data[i] = array[i - 1]; - p = data[i].p; - *p = i; - } - /* down build */ - for (i = N / 2; i >= 1; i--) xhDownHeap(i, H); - - return (H); -} - -/* destroy the heap and free the memory */ -void xhDestroy(Xheap H) { pgListDelete(H); } - -int xhUpHeap(int k, Xheap H) -{ - XheapElement *a, v; - int k_father; - int *p; - - a = (XheapElement *)pgListData(H); - - v = a[k]; - k_father = k / 2; /* integer divsion to retrieve its parent */ - while (k_father > 0 && a[k_father].value > v.value) { - a[k] = a[k_father]; - p = a[k].p; - *p = k; - k = k_father; - k_father = k / 2; - } - a[k] = v; - p = a[k].p; - *p = k; - - return (k); -} - -int xhDownHeap(int k, Xheap H) -{ - XheapElement *a, v; - int N, k_minson; - int *p; - - a = (XheapElement *)pgListData(H); - N = xhSize(H); - - v = a[k]; - while (k <= N / 2) { - k_minson = k + k; - if (k_minson < N) { - if (a[k_minson].value > a[k_minson + 1].value) k_minson = k_minson + 1; /* always locate the smallest son */ - } - if (v.value <= a[k_minson].value) break; /* break out the loop */ - a[k] = a[k_minson]; - p = a[k].p; - *p = k; - k = k_minson; /* go down one level */ - } - a[k] = v; - p = a[k].p; - *p = k; - - return (k); -} - -int xhInsert(double value, int id, int *p, Xheap H) -{ - // XheapElement *a; - XheapElement v; - int N, k; - - // a = (XheapElement *)pgListData(H); - - v.value = value; - v.id = id; - v.p = p; - - pgListAddElement(H, &v); - N = xhSize(H); - k = xhUpHeap(N, H); - - return (k); -} - -/* remove the smallest element */ -XheapElement xhRemove(Xheap H) -{ - XheapElement v, *a; - int N; - - N = xhSize(H); - a = (XheapElement *)pgListData(H); - - v = a[1]; - a[1] = a[N]; - pgListSetSize(H, N); - /* the size of list is always 1 more than the size of heap - since the heap starts at 1 */ - - xhDownHeap(1, H); - - return (v); -} - -/* replace the smallest value with a new value if the new value is smaller - otherwise the new value is returned and the heap is unchanged */ -XheapElement xhReplace(double value, int id, int *p, Xheap H) -{ - XheapElement *a, v; - - a = (XheapElement *)pgListData(H); - - if (value < a[1].value) { - v = a[1]; - a[1].value = value; - a[1].id = id; - a[1].p = p; - xhDownHeap(1, H); - } - else { - v.value = value; - v.id = id; - v.p = p; - } - return (v); -} - -/* delete an item in the heap and its value is returned */ -XheapElement xhDelete(int k, Xheap H) -{ - XheapElement *a, v; - int N; - - N = xhSize(H); - a = (XheapElement *)pgListData(H); - - v = a[k]; - - a[k] = a[N]; - pgListSetSize(H, N); - /* the size of list is always 1 more than the size of heap - since the heap starts at 1 */ - - xhDownHeap(k, H); - - return (v); -} - -/* change the value of an item and its original value is returned */ -XheapElement xhChange(int k, double value, int id, int *p, Xheap H) -{ - XheapElement *a, v; - - a = (XheapElement *)pgListData(H); - v = a[k]; - - if (value != a[k].value) { - a[k].value = value; - a[k].id = id; - a[k].p = p; - if (value < v.value) - xhUpHeap(k, H); - else - xhDownHeap(k, H); - } - - return (v); -} - -/* change the value of an item and its original value is returned */ -XheapElement xhChangeValue(int k, double value, Xheap H) -{ - XheapElement *a, v; - - a = (XheapElement *)pgListData(H); - v = a[k]; - - if (value != a[k].value) { - a[k].value = value; - if (value < v.value) - xhUpHeap(k, H); - else - xhDownHeap(k, H); - } - - return (v); -} - -XheapElement xhGet(int k, Xheap H) -{ - XheapElement v; - - pgListElementAt(H, k, &v); - - return (v); -} - -int xhSize(Xheap H) { return (pgListSize(H) - 1); } diff --git a/utils/hippo.c b/utils/hippo.cpp similarity index 99% rename from utils/hippo.c rename to utils/hippo.cpp index cddeb5cd5de..d81ebc1a2ff 100644 --- a/utils/hippo.c +++ b/utils/hippo.cpp @@ -34,11 +34,11 @@ static int non_hippo_labels[] = { MRI *HIPPOremoveNonHippoLabels(MRI *mri_src, MRI *mri_dst) { - int i, label; + int label; mri_dst = MRIcopy(mri_src, mri_dst); - for (i = 0; i < NUM_NON_HIPPO_LABELS; i++) { + for (unsigned i = 0; i < NUM_NON_HIPPO_LABELS; i++) { label = non_hippo_labels[i]; MRIreplaceValues(mri_dst, mri_dst, label, 0); } diff --git a/utils/hips.cpp b/utils/hips.cpp new file mode 100644 index 00000000000..3e02f9f4749 --- /dev/null +++ b/utils/hips.cpp @@ -0,0 +1,60 @@ +#include +#include "hips.h" + +int hips_cplxtor = 0; +int hips_rtocplx = 0; + +#define HIPS_DEP_ERROR { std::cerr << "error: hips is not supported" << std::endl; return 0; } +#define HIPS_DEP_ERROR_VOID { std::cerr << "error: hips is not supported" << std::endl; } + +double h_entropy(int *table,int count,int pairflag) HIPS_DEP_ERROR +int alloc_histo(struct hips_histo *histo,union pixelval *min,union pixelval *max,int nbins,int format) HIPS_DEP_ERROR +int alloc_histobins(struct hips_histo *histo) HIPS_DEP_ERROR +int clearparam(struct header *hd, const char *name) HIPS_DEP_ERROR +int fread_header(FILE *fp,struct header *hd,const char *fname) HIPS_DEP_ERROR +int fread_image(FILE *fp,struct header *hd,int fr,const char *fname) HIPS_DEP_ERROR +int free_hdrcon(struct header *hd) HIPS_DEP_ERROR +int fwrite_header(FILE *fp,struct header *hd,const char *fname) HIPS_DEP_ERROR +int fwrite_image(FILE *fp,struct header *hd,int fr,const char *fname) HIPS_DEP_ERROR +int getparam(struct header *hda,...) HIPS_DEP_ERROR +int h_add(struct header *hdi1,struct header *hdi2,struct header *hdo) HIPS_DEP_ERROR +int h_clearhisto(struct hips_histo *histogram) HIPS_DEP_ERROR +int h_diff(struct header *hdi1,struct header *hdi2,struct header *hdo) HIPS_DEP_ERROR +int h_div(struct header *hdi1,struct header *hdi2,struct header *hdo) HIPS_DEP_ERROR +int h_divscale(struct header *hdi,struct header *hdo,union pixelval *b) HIPS_DEP_ERROR +int h_enlarge(struct header *hdi,struct header *hdo,int xf,int yf) HIPS_DEP_ERROR +int h_entropycnt(struct header *hd,int *table,int pairflag) HIPS_DEP_ERROR +int h_flipquad(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int h_fourtr(struct header *hd) HIPS_DEP_ERROR +int h_histo(struct header *hd,struct hips_histo *histogram,int nzflag,int *count) HIPS_DEP_ERROR +int h_histoeq(struct hips_histo *histogram,int count,unsigned char *map) HIPS_DEP_ERROR +int h_invert(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int h_invfourtr(struct header *hd) HIPS_DEP_ERROR +int h_linscale(struct header *hdi,struct header *hdo,float b,float c) HIPS_DEP_ERROR +int h_median(struct header *hdi,struct header *hdo,int size) HIPS_DEP_ERROR +int h_minmax(struct header *hd,union pixelval *minval,union pixelval *maxval,int nzflag) HIPS_DEP_ERROR +int h_morphdil(struct header *hdi,struct header *hde,struct header *hdo,int centerr,int centerc,int gray) HIPS_DEP_ERROR +int h_mul(struct header *hdi1,struct header *hdi2,struct header *hdo) HIPS_DEP_ERROR +int h_mulscale(struct header *hdi,struct header *hdo,union pixelval *b) HIPS_DEP_ERROR +int h_pixmap(struct header *hdi,struct header *hdo,unsigned char *map) HIPS_DEP_ERROR +int h_reduce(struct header *hdi,struct header *hdo,int xf,int yf) HIPS_DEP_ERROR +int h_softthresh(struct header *hdi,struct header *hdo,union pixelval *thresh) HIPS_DEP_ERROR +int h_tob(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int h_toc(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int h_tod(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int h_todc(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int h_tof(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int h_toi(struct header *hdi,struct header *hdo) HIPS_DEP_ERROR +int setparam(struct header *hda,...) HIPS_DEP_ERROR +int update_header(struct header *hd,int argc,char **argv ) HIPS_DEP_ERROR +struct extpar *findparam(struct header *hd, const char *name) HIPS_DEP_ERROR +void canny(int *magmax, int *hthresh, int *lthresh, int *image, int *xsize, int *ysize, short *shortim, int *windowsize, double *sigma, int *bordermode, double *hfrac, double *lfrac, int *pflag, + short *gx, short *gy, short *mag, int *hist, int *histsize, unsigned char *nms, unsigned char *edgemap, float *gm, float *gmp,short *temp) HIPS_DEP_ERROR_VOID +void cleanup(unsigned char *map, int xsize, int ysize) HIPS_DEP_ERROR_VOID +void find_edges(unsigned char *map, short *mag, int xsize, int ysize, int maxmag, float hpixel_fraction, float lpixel_fraction, int *hgram, int hsize, int *actual_hthresh, int *actual_lthresh) HIPS_DEP_ERROR_VOID +void follow_edges(unsigned char *edgemapptr, short *edgemagptr) HIPS_DEP_ERROR_VOID +void clear_borders(unsigned char *charimage, int xsize, int ysize) HIPS_DEP_ERROR_VOID +void gauss_filter(short *inimage, int inx, int iny, int direction, int boundary, int masksize, float sigma, short *grad, int *outx, int *outy, float *gmask, float *gprimemask, short *tempimage) HIPS_DEP_ERROR_VOID +void copyimage(int *charimage, int ncols, int nrows, short *shortimage) HIPS_DEP_ERROR_VOID +void thin(unsigned char *edges, int height, int width) HIPS_DEP_ERROR_VOID +int h_canny(struct header *Isrc, struct header *Idst, double sigma, int mask_size,double lfrac,double hfrac,int dothin) HIPS_DEP_ERROR \ No newline at end of file diff --git a/utils/histo.c b/utils/histo.cpp similarity index 99% rename from utils/histo.c rename to utils/histo.cpp index ffb4df9c2c9..bddf04ee299 100644 --- a/utils/histo.c +++ b/utils/histo.cpp @@ -926,7 +926,7 @@ int HISTOfindHighestPeakInRegion(HISTOGRAM *h, int b0, int b1) Description ------------------------------------------------------*/ -int HISTOplot(HISTOGRAM *histo, char *fname) +int HISTOplot(HISTOGRAM *histo, const char *fname) { FILE *fp; int bin_no, bmin, bmax; @@ -2990,7 +2990,7 @@ int HISTOwrite(HISTOGRAM *histo, char *fname) \fn int HISTOwriteTxt(HISTOGRAM *histo, char *fname) \brief Writes histogram into the given filename in ascii format. */ -int HISTOwriteTxt(HISTOGRAM *histo, char *fname) +int HISTOwriteTxt(HISTOGRAM *histo, const char *fname) { int n; FILE *fp; diff --git a/utils/ic12.c b/utils/ic12.cpp similarity index 100% rename from utils/ic12.c rename to utils/ic12.cpp diff --git a/utils/ic163842.c b/utils/ic163842.cpp similarity index 100% rename from utils/ic163842.c rename to utils/ic163842.cpp diff --git a/utils/ic2562.c b/utils/ic2562.cpp similarity index 100% rename from utils/ic2562.c rename to utils/ic2562.cpp diff --git a/utils/ic42.c b/utils/ic42.cpp similarity index 100% rename from utils/ic42.c rename to utils/ic42.cpp diff --git a/utils/ic642.c b/utils/ic642.cpp similarity index 100% rename from utils/ic642.c rename to utils/ic642.cpp diff --git a/utils/icosahedron.c b/utils/icosahedron.cpp similarity index 100% rename from utils/icosahedron.c rename to utils/icosahedron.cpp diff --git a/utils/image.c b/utils/image.cpp similarity index 98% rename from utils/image.c rename to utils/image.cpp index 0b37cefc7cd..0575c10b2ed 100644 --- a/utils/image.c +++ b/utils/image.cpp @@ -33,12 +33,9 @@ #include #include /* for SEEK_ constants */ -#include #include "hmem.h" - #include "hips.h" -#include "canny.h" #include "diag.h" #include "error.h" #include "image.h" @@ -123,7 +120,7 @@ int ImageAllocBuffer(IMAGE *I) if (I->image) free(I->image); // init_header might have calloc'd already, // so this free prevents memory leakage - if ((I->image = hcalloc(npix, sizeof(byte))) == (byte *)NULL) return (ERROR_NO_MEMORY); + if ((I->image = (byte *)hcalloc(npix, sizeof(byte))) == (byte *)NULL) return (ERROR_NO_MEMORY); if (I->pixel_format == PFMSBF || I->pixel_format == PFLSBF) { fcb = I->fcol / 8; cb = (I->ocols + 7) / 8; @@ -3248,7 +3245,7 @@ IMAGE *ImageShrink(IMAGE *Isrc, IMAGE *Idst) /*---------------------------------------------------------------------- Parameters: - Description: + Description: @ATH perform histogram equalization on an image ----------------------------------------------------------------------*/ IMAGE *ImageHistoEqualize(IMAGE *Isrc, IMAGE *Idst) @@ -3261,7 +3258,7 @@ IMAGE *ImageHistoEqualize(IMAGE *Isrc, IMAGE *Idst) byte map[256]; if (Isrc->pixel_format != PFBYTE) - Iin = ImageConvertToByte(Isrc, NULL); + Iin = ImageAlloc(Isrc->rows, Isrc->cols, PFBYTE, 1); else Iin = Isrc; @@ -3292,25 +3289,7 @@ IMAGE *ImageHistoEqualize(IMAGE *Isrc, IMAGE *Idst) } return (Idst); } -/*---------------------------------------------------------------------- - Parameters: - - Description: - convert an image to byte format, scaling its intensity values to - 0-255 -----------------------------------------------------------------------*/ -#include "rescale.h" -IMAGE *ImageConvertToByte(IMAGE *Isrc, IMAGE *Idst) -{ - int MinPoint[2], MaxPoint[2], ecode; - if (!Idst) Idst = ImageAlloc(Isrc->rows, Isrc->cols, PFBYTE, 1); - - ecode = h_rescale(Isrc, 0.0f, 255.0f, MinPoint, MaxPoint, Idst); - if (ecode != HIPS_OK) ErrorReturn(NULL, (ecode, "ImageConvert: h_rescale failed\n")); - - return (Idst); -} /*---------------------------------------------------------------------- Parameters: @@ -3771,3 +3750,76 @@ float ImageRMSDifference(IMAGE *I1_in, IMAGE *I2_in) if (I2 != I2_in) ImageFree(&I2); return (rms); } + +int init_header(IMAGE *I,char *onm,char *snm,int nfr,char *odt,int rw,int cl,int pfmt,int nc,const char *desc) { + int bytes ; + + I->num_frame = nfr ; + I->orows = I->rows = rw ; + I->ocols = I->cols = cl ; + I->pixel_format = pfmt ; + bytes = rw*cl*nfr ; + switch (pfmt) { + default: + case PFBYTE: + I->sizepix = sizeof(char) ; + break ; + case PFFLOAT: + I->sizepix = sizeof(float) ; + break ; + case PFDOUBLE: + I->sizepix = sizeof(double) ; + break ; + case PFINT: + I->sizepix = sizeof(int) ; + break ; + case PFSHORT: + I->sizepix = sizeof(short) ; + break ; + case PFRGB: + case PFBGR: + I->sizepix = 3*sizeof(byte); + break; + case PFRGBZ: + case PFZRGB: + case PFBGRZ: + case PFZBGR: + I->sizepix = 4*sizeof(byte); + break; + case PFSTEREO: + I->sizepix = sizeof(byte); + break; + case PFINTPYR: + I->sizepix = sizeof(int); + break; + case PFFLOATPYR: + I->sizepix = sizeof(float); + break; + } + bytes *= I->sizepix ; + I->numpix = I->rows * I->cols ; + I->sizeimage = I->numpix * I->sizepix ; + I->firstpix = I->image ; + I->image = (byte *)calloc(bytes, sizeof(char)) ; + if (!I->image) + ErrorExit(ERROR_NOMEMORY, "init_header: could not allocate %d bytes", + bytes) ; + + return(NO_ERROR) ; +} + +int h_copy(IMAGE *Isrc, IMAGE *Idst) { + int bytes; + bytes = Isrc->numpix * Isrc->sizepix ; + memmove(Idst->image, Isrc->image, bytes) ; + return(NO_ERROR) ; +} + +int free_header(IMAGE *I) { + if (I->image) { + free(I->image) ; + } + free(I) ; + return(0) ; +} + diff --git a/utils/imageio.c b/utils/imageio.cpp similarity index 93% rename from utils/imageio.c rename to utils/imageio.cpp index d354050cd4e..6bde12370cc 100644 --- a/utils/imageio.c +++ b/utils/imageio.cpp @@ -37,30 +37,20 @@ #include #include /* for SEEK_ constants */ -#include #include "hmem.h" - #include "hips.h" -#include "canny.h" #include "diag.h" #include "error.h" #include "image.h" -#include "jpeglib.h" #include "machine.h" #include "macros.h" #include "matfile.h" #include "matrix.h" #include "proto.h" -#include "rgb_image.h" -#include "rgb_utils.h" +#include "rgb.h" #include "tiffio.h" #include "utils.h" -#ifndef IRIX -#include "pbm.h" -#include "pgm.h" -#include "ppm.h" -#endif /*----------------------------------------------------- MACROS AND CONSTANTS @@ -76,6 +66,9 @@ static int TiffWriteImage(IMAGE *I, const char *fname, int frame); static IMAGE *JPEGReadImage(const char *fname); static IMAGE *JPEGReadHeader(FILE *fp, IMAGE *); static int JPEGWriteImage(IMAGE *I, const char *fname, int frame); +static int RGBwrite(IMAGE *I, char *fname, int frame); +static IMAGE *RGBReadImage(char *fname); +static IMAGE *RGBReadHeader(char *fname, IMAGE *I); static IMAGE *PGMReadImage(const char *fname); static IMAGE *PGMReadHeader(FILE *fp, IMAGE *); static int PGMWriteImage(IMAGE *I, const char *fname, int frame); @@ -746,7 +739,7 @@ static IMAGE *TiffReadImage(const char *fname, int frame0) float r, g, b, y; float *pf; #endif - int scanlinesize; //, extra_samples; + unsigned int scanlinesize; //, extra_samples; int index = 0; float xres, yres, res; @@ -978,7 +971,7 @@ static IMAGE *TiffReadImage(const char *fname, int frame0) if (byte_ > 0) DiagBreak(); if (fillorder == FILLORDER_LSB2MSB) { for (bitmask = 0x01, bit = 0; bit < 8; bit++) { - if (col + bit == Gx && index == Gy) DiagBreak(); + if (col + bit == (unsigned)Gx && index == Gy) DiagBreak(); *IMAGEpix(I, col + bit, index) = ((byte_ & bitmask) > 0); bitmask = bitmask << 1; } @@ -986,7 +979,7 @@ static IMAGE *TiffReadImage(const char *fname, int frame0) else // fillorder == FILLORDER_MSB2LSB { for (bitmask = 0x01 << 7, bit = 0; bit < 8; bit++) { - if (col + bit == Gx && index == Gy) DiagBreak(); + if (col + bit == (unsigned)Gx && index == Gy) DiagBreak(); *IMAGEpix(I, col + bit, index) = ((byte_ & bitmask) > 0); bitmask = bitmask >> 1; } @@ -1256,41 +1249,23 @@ static int TiffWriteImage(IMAGE *I, const char *fname, int frame) return (NO_ERROR); } -#if 0 -static IMAGE *JPEGReadImage(const char*fname) -{ - ErrorReturn(NULL, (ERROR_UNSUPPORTED, "jpeg not supported on IRIX")) ; -} -static IMAGE *JPEGReadHeader(FILE *fp, IMAGE *I) -{ - ErrorReturn(NULL, (ERROR_UNSUPPORTED, "jpeg not supported on IRIX")) ; -} -static int JPEGWriteImage(IMAGE *I, const char*fname, int frame) -{ - ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, - "jpeg not supported on IRIX")) ; -} -#endif +#ifndef HAVE_NETPBM + +static IMAGE *PGMReadImage(const char *fname) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pgm not supported")); } +static IMAGE *PGMReadHeader(FILE *fp, IMAGE *I) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pgm not supported")); } +static int PGMWriteImage(IMAGE *I, const char *fname, int frame) { ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "pgm not supported")); } +static IMAGE *PPMReadImage(const char *fname) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "ppm not supported")); } +static IMAGE *PPMReadHeader(FILE *fp, IMAGE *I) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "ppm not supported")); } +static IMAGE *PBMReadImage(const char *fname) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pbm not supported")); } +static IMAGE *PBMReadHeader(FILE *fp, IMAGE *I) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pbm not supported")); } +static int PPMWriteImage(IMAGE *I, const char *fname, int frame) { ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "ppm not supported")); } + +#else // HAVE_NETPBM + +#include +#include +#include -#ifdef IRIX -static IMAGE *JPEGReadImage(const char *fname) { return (NULL); } -static IMAGE *JPEGReadHeader(FILE *fp, IMAGE *I) { return (NULL); } -static int JPEGWriteImage(IMAGE *I, const char *fname, int frame) { return (0); } -static IMAGE *PGMReadImage(const char *fname) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pgm not supported on IRIX")); } -static IMAGE *PGMReadHeader(FILE *fp, IMAGE *I) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pgm not supported on IRIX")); } -static int PGMWriteImage(IMAGE *I, const char *fname, int frame) -{ - ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pgm not supported on IRIX")); -} -static IMAGE *PPMReadImage(const char *fname) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "ppm not supported on IRIX")); } -static IMAGE *PPMReadHeader(FILE *fp, IMAGE *I) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "ppm not supported on IRIX")); } -static IMAGE *PBMReadImage(const char *fname) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pbm not supported on IRIX")); } -static IMAGE *PBMReadHeader(FILE *fp, IMAGE *I) { ErrorReturn(NULL, (ERROR_UNSUPPORTED, "pbm not supported on IRIX")); } -static int PPMWriteImage(IMAGE *I, const char *fname, int frame) -{ - ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "ppm not supported on IRIX")); -} -#else static IMAGE *PGMReadHeader(FILE *fp, IMAGE *I) { int rows, cols, format; @@ -1456,10 +1431,15 @@ static IMAGE *PPMReadHeader(FILE *fp, IMAGE *I) return I; } +#endif // HAVE_NETPBM + #define JPEG_INTERNALS + +extern "C" { #include "jinclude.h" #include "jpeglib.h" #include "jmorecfg.h" +} static IMAGE *JPEGReadImage(const char *fname) { @@ -1557,4 +1537,94 @@ static int JPEGWriteImage(IMAGE *I, const char *fname, int frame) return NO_ERROR; } +static IMAGE *RGBReadHeader(char *fname, IMAGE *I) { + RGB_IMAGE *rgb; + + rgb = iopen(fname, "r", 0, 0, 0, 0, 0); + + if (!I) + I = ImageAlloc(rgb->ysize, rgb->xsize, PFRGB, 1) ; + else + init_header(I, "orig", "seq", 1, "today", rgb->ysize, + rgb->xsize, PFRGB, 1, "temp"); + + iclose(rgb); + + return(I) ; +} + +static IMAGE *RGBReadImage(char *fname) { + IMAGE *I; + RGB_IMAGE *rgb; + unsigned short rows,cols,*r,*g,*b,i,j,*tr,*tg,*tb; + byte *iptr; + + rgb = iopen(fname, "r", 0, 0, 0, 0, 0); + rows = rgb->ysize; + cols = rgb->xsize; + + if (rgb->zsize>3) + ErrorReturn(NULL, (ERROR_BAD_PARM, + "Too many color planes in RGBReadImage (%s)\n",fname)); + + I = ImageAlloc(rows, cols, PFRGB, 1); + + if ((r = (unsigned short *)malloc(sizeof(unsigned short)*cols)) == NULL) + ErrorExit(ERROR_NO_MEMORY,"Failed to allocate color buffer\n"); + + if ((g = (unsigned short *)malloc(sizeof(unsigned short)*cols)) == NULL) + ErrorExit(ERROR_NO_MEMORY,"Failed to allocate color buffer\n"); + + if ((b = (unsigned short *)malloc(sizeof(unsigned short)*cols)) == NULL) + ErrorExit(ERROR_NO_MEMORY,"Failed to allocate color buffer\n"); + + iptr = I->image; + + for (i=0;icols, I->rows, 1); +#else + image = iopen(fname,"w",UNCOMPRESSED(1), 2, I->cols, I->rows, 1); #endif + r = (unsigned short *)calloc(I->cols, sizeof(unsigned short)) ; + for (y = 0 ; y < I->rows; y++) { + for (x = 0 ; x < I->cols ; x++) + r[x] = (unsigned short)(*IMAGEpix(I, x, y)) ; + + /* fill rbuf, gbuf, and bbuf with pixel values */ + putrow(image, r, y, 0); /* red row */ + putrow(image, r, y, 1); /* green row */ + putrow(image, r, y, 2); /* blue row */ + } + iclose(image); + free(r) ; + return(NO_ERROR) ; +} diff --git a/utils/imautils.c b/utils/imautils.cpp similarity index 99% rename from utils/imautils.c rename to utils/imautils.cpp index 37ccfafedef..5c624a1fe8f 100644 --- a/utils/imautils.c +++ b/utils/imautils.cpp @@ -33,10 +33,10 @@ IMA_DICTIONARY_ENTRY ImaDictionary[NMAX_IMA_DICTIONARY] = {}; int nImaDictionary = 0, ImaDictionaryGood = 0; -char *imaTypeString[6] = {"short", "int", "long", "float", "double", "string"}; +const char *imaTypeString[6] = {"short", "int", "long", "float", "double", "string"}; int imaTypeSize[6] = {sizeof(short), sizeof(int), sizeof(long), sizeof(float), sizeof(double), sizeof(char)}; -static int imaSetDictEntry(int nthEntry, char *key, int offset, char *typestring, int nitems); +static int imaSetDictEntry(int nthEntry, const char *key, int offset, const char *typestring, int nitems); static int imaGetKeyEntryNo(const char *key); /*-------------------------------------------------------------------- @@ -170,7 +170,7 @@ void MkImaDictionary(void) } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ -static int imaSetDictEntry(int nthEntry, char *key, int offset, char *typestring, int nitems) +static int imaSetDictEntry(int nthEntry, const char *key, int offset, const char *typestring, int nitems) { int type; @@ -226,7 +226,7 @@ int DumpImaDictionaryVal(FILE *fp, const char *imafile) { // extern IMA_DICTIONARY_ENTRY ImaDictionary[NMAX_IMA_DICTIONARY]; // extern int nImaDictionary, ImaDictionaryGood; - char *key, *typestring; + const char *key, *typestring; int n, offset, type, typesize, nitems; FILE *imafp; short sval; @@ -441,8 +441,8 @@ IMAFILEINFO *imaLoadFileInfo(const char *imafile) ifi->NFilesInSeries = imaCountFilesInSeries(imafile, &FirstImageNo); - ifi->PatientName = imaLoadValFromKey(fp, "G10_Pat_PatientName", NULL); - ifi->PulseSequence = imaLoadValFromKey(fp, "G19_Acq4_CM_SequenceFileName", NULL); + ifi->PatientName = (char *)imaLoadValFromKey(fp, "G10_Pat_PatientName", NULL); + ifi->PulseSequence = (char *)imaLoadValFromKey(fp, "G19_Acq4_CM_SequenceFileName", NULL); imaLoadValFromKey(fp, "G10_Pat_PatientBirthdate_Year", &Year); imaLoadValFromKey(fp, "G10_Pat_PatientBirthdate_Month", &Month); diff --git a/utils/intensity_eig.c b/utils/intensity_eig.cpp similarity index 100% rename from utils/intensity_eig.c rename to utils/intensity_eig.cpp diff --git a/utils/ipmpar.c b/utils/ipmpar.cpp similarity index 100% rename from utils/ipmpar.c rename to utils/ipmpar.cpp diff --git a/utils/joint_histo.c b/utils/joint_histo.cpp similarity index 100% rename from utils/joint_histo.c rename to utils/joint_histo.cpp diff --git a/utils/kernel.c b/utils/kernel.cpp similarity index 99% rename from utils/kernel.c rename to utils/kernel.cpp index 5b064a84c2b..05f0aa5b939 100644 --- a/utils/kernel.c +++ b/utils/kernel.cpp @@ -26,14 +26,12 @@ /*---------------------------------------------------------------------- INCLUDE FILES ----------------------------------------------------------------------*/ -#include #include #include #include #include #include "diag.h" -#include "hipsu.h" #include "image.h" #include "kernel.h" #include "macros.h" diff --git a/utils/kinput.c b/utils/kinput.c deleted file mode 100644 index 05b118aad7b..00000000000 --- a/utils/kinput.c +++ /dev/null @@ -1,285 +0,0 @@ -/** - * @file kinput.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.8 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include - -#include "hips.h" -#include "kinput.h" -#include "macros.h" - -/* debugging stuff */ -#define TEST 0 - -#if USE_PYRAMID -static float kinputGetPoint(HIPSPyramid *pyr, int x, int y, int level); -#endif - -#define SIGMA_SCALE 1.5f - -/*---------------------------------------------------------------------- - Parameters: - - Description: -----------------------------------------------------------------------*/ -KINPUT *KinputAlloc( - int rows, int cols, int nscales, int input_size, float sigma, float sigma_scale_factor, int abs_gradient) -{ - KINPUT *kinput; - int scale; - - if (nscales > MAX_SCALES) nscales = MAX_SCALES; - - kinput = (KINPUT *)calloc(1, sizeof(KINPUT)); - kinput->nscales = nscales; - kinput->ninputs = nscales * input_size * input_size * 2; - kinput->parms.abs_gradient = abs_gradient; - if (FZERO(sigma_scale_factor)) - sigma_scale_factor = kinput->parms.sigma_scale_factor = SIGMA_SCALE_FACTOR; - else - kinput->parms.sigma_scale_factor = sigma_scale_factor; - -#if !USE_PYRAMID - kinput->xInputs = ImageAlloc(rows, cols, PFFLOAT, nscales); - kinput->yInputs = ImageAlloc(rows, cols, PFFLOAT, nscales); - for (scale = 1; scale < nscales; scale++) { - kinput->gImages[scale] = ImageGaussian1d(sigma * sigma_scale_factor * (float)(scale), 0); - kinput->parms.sigmas[scale] = (float)scale * sigma_scale_factor * sigma; - } -#endif - - kinput->inputs = (float *)calloc(kinput->ninputs, sizeof(float)); - - /* fill out parameter block */ - kinput->parms.nscales = nscales; - kinput->parms.input_size = input_size; - - return (kinput); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: -----------------------------------------------------------------------*/ -int KinputFree(KINPUT **pkinput) -{ - KINPUT *kinput; - int scale; - - kinput = *pkinput; - *pkinput = NULL; - -#if USE_PYRAMID - ImageFreePyramid(kinput->xpyr); - ImageFreePyramid(kinput->ypyr); - if (kinput->xImage) ImageFree(&kinput->xImage); - if (kinput->yImage) ImageFree(&kinput->yImage); -#else - ImageFree(&kinput->xInputs); - ImageFree(&kinput->yInputs); - for (scale = 1; scale < kinput->nscales; scale++) ImageFree(&kinput->gImages[scale]); -#endif - - free(kinput->inputs); - - free(kinput); - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: -----------------------------------------------------------------------*/ -int KinputInit(KINPUT *kinput, IMAGE *image) -{ - int scale; - -#if USE_PYRAMID - /* first compute derivatives */ - kinput->xImage = ImageXDerivative(image, kinput->xImage); - kinput->yImage = ImageYDerivative(image, kinput->yImage); - kinput->xpyr = ImagePyramid(kinput->xImage, kinput->xpyr, kinput->nscales); - kinput->ypyr = ImagePyramid(kinput->yImage, kinput->ypyr, kinput->nscales); -#else - - /* 1st image in inputs is derivative at inner scale */ - ImageXDerivative(image, kinput->xInputs); - ImageYDerivative(image, kinput->yInputs); - - /* now compute blurred derivates at different scales */ - for (scale = 1; scale < kinput->nscales; scale++) { - ImageConvolveGaussian(kinput->xInputs, kinput->gImages[scale], kinput->xInputs, scale); - ImageConvolveGaussian(kinput->yInputs, kinput->gImages[scale], kinput->yInputs, scale); - } -#if 0 - ImageWrite(image, "i.hipl") ; - ImageWriteFrames(kinput->xInputs, "xin.hipl", 0, kinput->xInputs->num_frame) ; - ImageWriteFrames(kinput->yInputs, "yin.hipl", 0, kinput->yInputs->num_frame) ; -#endif -#endif - return (0); -} -/*---------------------------------------------------------------------- - Parameters: - - Description: -----------------------------------------------------------------------*/ -int KinputVector(KINPUT *kinput, int x0, int y0) -{ - int x, y, x1, y1, rows, cols, scale, neg_half, half_in; - float *in, xval, yval; - - in = kinput->inputs; - neg_half = (kinput->parms.input_size - 1) / 2; - half_in = kinput->parms.input_size / 2; - -#if USE_PYRAMID - /* int index ; */ - rows = kinput->xImage->rows; - cols = kinput->xImage->cols; - - /* - the input vector consists of pairs of x and y derivative values at each - level of the pyramid at this point. - */ - for (index = scale = 0; scale < kinput->nscales; scale++) { - for (y = y0-(neg_half ; y <= y0+half_in ; y++) - { - for (x = x0-(neg_half ; x <= x0+half_in ; x++) - { - xval = kinputGetPoint(kinput->xpyr, x, y, scale); - if (kinput->parms.abs_gradient) xval = fabs(xval); - kinput->inputs[index++] = xval; - yval = kinputGetPoint(kinput->ypyr, x, y, scale); - if (kinput->parms.abs_gradient) yval = fabs(yval); - kinput->inputs[index++] = yval; - } - } - } -#else - /* - the input vector consists of pairs of x and y derivative values at each - level of blurring at this point. - */ - rows = kinput->xInputs->rows; - cols = kinput->xInputs->cols; - - for (scale = 0; scale < kinput->nscales; scale++) { - for (y1 = -neg_half; y1 <= half_in; y1++) { - for (x1 = -neg_half; x1 <= half_in; x1++) { - x = x0 + x1; - if (x < 0) x = 0; - if (x >= cols) x = cols - 1; - - y = y0 + y1; - if (y < 0) y = 0; - if (y >= rows) y = rows - 1; - - xval = *IMAGEFseq_pix(kinput->xInputs, x, y, scale); - yval = *IMAGEFseq_pix(kinput->yInputs, x, y, scale); - -#define DONT_USE_INNER_SCALE 0 -#if DONT_USE_INNER_SCALE - if (!scale) xval = yval = 0.0f; -#endif - - *in++ = xval; - *in++ = yval; - } - } - } -#endif - - return (0); -} -#if USE_PYRAMID - -static float kinputGetPoint(IMAGEPyramid *pyr, int x, int y, int level) -{ - float val; - - int x1, x2, y1, y2, cols, rows, cols0, rows0; - float dx, dy, xc, yc, *image, *f1p, *f2p, *f3p, *f4p, xpct, ypct; - - cols0 = pyr->images[0]->cols; - rows0 = pyr->images[0]->rows; - if (x < 0) x = 0; - if (y < 0) y = 0; - if (x >= cols0) x = cols0 - 1; - if (y >= rows0) y = rows0 - 1; - - image = IMAGEFpix(pyr->images[level], 0, 0); - cols = pyr->images[level]->cols; - rows = pyr->images[level]->rows; - - xpct = (float)x / (float)(cols0 - 1); - ypct = (float)y / (float)(rows0 - 1); - xc = xpct * (float)(cols - 1); - yc = ypct * (float)(rows - 1); - -#define BILINEAR 1 -#if BILINEAR - - /* do bilinear interpolation on 4 surrounding points */ - x1 = (int)floor(xc); - x2 = (int)ceil(xc); - y1 = (int)floor(yc); - y2 = (int)ceil(yc); - -#if 0 - if (x2 >= cols) - x2 = cols-1 ; - if (y2 >= rows) - y2 = rows - 1 ; -#endif - - if ((x1 < 0) || (y1 < 0) || (x2 >= cols) || (y2 >= pyr->images[level]->rows)) { - fprintf(stderr, "kinputGetPoint(%d, %d, %d): point (%d,%d,%d,%d) out of bounds\n", x, y, level, x1, y1, x2, y2); - return (0.0f); - } - - /* all other distances are 1-a or 1-b */ - dy = yc - (float)y1; - dx = xc - (float)x1; - - f1p = image + y1 * cols + x1; /* dy, dx */ - f2p = image + y2 * cols + x1; /* 1-dy, dx */ - f3p = image + y1 * cols + x2; /* dy, 1-dx */ - f4p = image + y2 * cols + x2; /* 1-dy, 1-dx */ - val = (1.0 - dy) * ((1.0 - dx) * *f1p + dx * *f3p) + dy * ((1.0 - dx) * *f2p + dx * *f4p); - -#else - x1 = nint(xc); - y1 = nint(yc); - val = *IMAGEFpix(pyr->images[level], x1, y1); -#endif -#if TEST - if (x == TCOL && y == TROW) fprintf(stderr, "inputs(%2.1f, %2.1f) = %2.4f\n", xc, yc, val); -#endif - return (val); -} -#endif diff --git a/utils/label.c b/utils/label.cpp similarity index 98% rename from utils/label.c rename to utils/label.cpp index 1c748562988..49c90042837 100644 --- a/utils/label.c +++ b/utils/label.cpp @@ -38,7 +38,7 @@ #include "error.h" #include "fio.h" #include "macros.h" -#include "minc_volume_io.h" +#include "minc.h" #include "proto.h" #include "utils.h" @@ -768,7 +768,7 @@ int LabelIntersect(LABEL *area1, LABEL *area2) Description ------------------------------------------------------*/ -LABEL *LabelAlloc(int max_points, char *subject_name, char *label_name) +LABEL *LabelAlloc(int max_points, const char *subject_name, const char *label_name) { LABEL *area; char *cp, subjects_dir[STRLEN]; @@ -2259,7 +2259,7 @@ int LabelDilate(LABEL *area, MRI_SURFACE *mris, int num_times, int coords) if (area->vertex_label_ind) area->vertex_label_ind[vno] = n; if (area->mris && area->mri_template) { double xv, yv, zv; - MRISsurfaceRASToVoxel(area->mris, area->mri_template, lv->x, lv->y, lv->z, &xv, &yv, &zv); + MRISsurfaceRASToVoxel((MRIS *)area->mris, area->mri_template, lv->x, lv->y, lv->z, &xv, &yv, &zv); lv->xv = nint(xv); lv->yv = nint(yv); lv->zv = nint(zv); @@ -2508,7 +2508,7 @@ LABEL *LabelRealloc(LABEL *lb, int max_points) return (lb); } - lvtmp = realloc(lb->lv, sizeof(LV) * max_points); + lvtmp = (LV *)realloc(lb->lv, sizeof(LV) * max_points); if (lvtmp == NULL) { return (lb); } @@ -3237,7 +3237,7 @@ LABEL *LabelVoxelToSurfaceRAS(LABEL *lsrc, MRI *mri, LABEL *ldst) for (i = 0; i < lsrc->n_points; i++) { if (lsrc->mris) - MRISsurfaceRASToVoxel(lsrc->mris, mri, lsrc->lv[i].x, lsrc->lv[i].y, lsrc->lv[i].z, &xs, &ys, &zs); + MRISsurfaceRASToVoxel((MRIS *)lsrc->mris, mri, lsrc->lv[i].x, lsrc->lv[i].y, lsrc->lv[i].z, &xs, &ys, &zs); else MRIvoxelToSurfaceRAS(mri, lsrc->lv[i].x, lsrc->lv[i].y, lsrc->lv[i].z, &xs, &ys, &zs); ldst->lv[i].x = xs; @@ -3540,7 +3540,7 @@ int LabelInit(LABEL *area, MRI *mri_template, MRI_SURFACE *mris, int coords) double vxl_spacing = (mri_template->xsize < mri_template->ysize ? mri_template->xsize : mri_template->ysize); vxl_spacing = (vxl_spacing < mri_template->zsize ? vxl_spacing : mri_template->zsize); - area->mht = (void *)MHTcreateVertexTable_Resolution(mris, coords, vxl_spacing); + area->mht = MHTcreateVertexTable_Resolution(mris, coords, vxl_spacing); // map unassigned vertices to surface locations for (n = 0; n < area->n_points; n++) { @@ -3581,13 +3581,13 @@ int LabelInit(LABEL *area, MRI *mri_template, MRI_SURFACE *mris, int coords) lv->zv = nint(zv); if (area->mris) - MRISsurfaceRASFromVoxel(area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! + MRISsurfaceRASFromVoxel((MRIS *)area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! else MRIvoxelToSurfaceRAS(area->mri_template, xv, yv, zv, &vx, &vy, &vz); // must use surface coords for finding vertex if (area->mris) - MRISsurfaceRASFromVoxel(area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! + MRISsurfaceRASFromVoxel((MRIS *)area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! else MRIvoxelToSurfaceRAS(area->mri_template, xv, yv, zv, &vx, &vy, &vz); x = y = z = -1; @@ -3598,7 +3598,7 @@ int LabelInit(LABEL *area, MRI *mri_template, MRI_SURFACE *mris, int coords) min_vno = -1; float distance; - min_vno = MHTfindClosestVertexNoXYZ( area->mht, area->mris, vx,vy,vz, &distance ); + min_vno = MHTfindClosestVertexNoXYZ( (MHT *)area->mht, (MRIS *)area->mris, vx,vy,vz, &distance ); lv->vno = min_vno; if (min_vno >= 0 && area->vertex_label_ind[min_vno] < 0) // found one that isn't in label @@ -3607,16 +3607,16 @@ int LabelInit(LABEL *area, MRI *mri_template, MRI_SURFACE *mris, int coords) // printf("LabelAddVoxel(%d, %d, %d): added min_dist vno %d at %d\n", xv, yv, zv, min_vno, n) ; // now add other vertices that also map to this voxel - VERTEX_TOPOLOGY const * const min_vt = &((MRI_SURFACE *)(area->mris))->vertices_topology[min_vno]; + VERTEX_TOPOLOGY const * const min_vt = &((MRI_SURFACE *)((MRIS *)area->mris))->vertices_topology[min_vno]; for (i = 0; i < min_vt->vnum; i++) // find min dist vertex { vno = min_vt->v[i]; if (area->vertex_label_ind[vno] >= 0) continue; // already in the label - v = &((MRI_SURFACE *)(area->mris))->vertices[vno]; + v = &((MRI_SURFACE *)((MRIS *)area->mris))->vertices[vno]; if (vno == Gdiag_no) DiagBreak(); MRISgetCoords(v, coords, &x, &y, &z); - MRISsurfaceRASToVoxel(area->mris, area->mri_template, x, y, z, &vx, &vy, &vz); + MRISsurfaceRASToVoxel((MRIS *)area->mris, area->mri_template, x, y, z, &vx, &vy, &vz); if ((xv == nint(vx)) && (yv == nint(vy)) && (zv == nint(vz))) { LabelAddVertex(area, vno, coords); } @@ -3648,8 +3648,7 @@ int LabelAddVoxel(LABEL *area, int xv, int yv, int zv, int coords, int *vertices switch (area->coords) { case LABEL_COORDS_TKREG_RAS: if (area->mris) - MRISsurfaceRASFromVoxel( - area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! + MRISsurfaceRASFromVoxel((MRIS *)area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! else MRIvoxelToSurfaceRAS(area->mri_template, xv, yv, zv, &vx, &vy, &vz); break; @@ -3668,7 +3667,7 @@ int LabelAddVoxel(LABEL *area, int xv, int yv, int zv, int coords, int *vertices // must use surface coords for finding vertex if (area->mris) - MRISsurfaceRASFromVoxel(area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! + MRISsurfaceRASFromVoxel((MRIS *)area->mris, area->mri_template, xv, yv, zv, &vx, &vy, &vz); // surfaceRASToVoxel BRF!! else MRIvoxelToSurfaceRAS(area->mri_template, xv, yv, zv, &vx, &vy, &vz); x = y = z = -1; @@ -3679,7 +3678,7 @@ int LabelAddVoxel(LABEL *area, int xv, int yv, int zv, int coords, int *vertices min_vno = -1; float distance; - min_vno = MHTfindClosestVertexNoXYZ( area->mht, area->mris, vx,vy,vz, &distance ); + min_vno = MHTfindClosestVertexNoXYZ( (MHT *)area->mht, (MRIS *)area->mris, vx,vy,vz, &distance ); lv->vno = min_vno; if (min_vno >= 0) @@ -3749,7 +3748,7 @@ int LabelAddVoxel(LABEL *area, int xv, int yv, int zv, int coords, int *vertices if (vno == Gdiag_no) DiagBreak(); MRISgetCoords(v, coords, &x, &y, &z); - MRISsurfaceRASToVoxel(area->mris, area->mri_template, x, y, z, &vx, &vy, &vz); + MRISsurfaceRASToVoxel((MRIS *)area->mris, area->mri_template, x, y, z, &vx, &vy, &vz); if ((xv == nint(vx)) && (yv == nint(vy)) && (zv == nint(vz))) { if (pnvertices) { int n = *pnvertices; @@ -3855,7 +3854,7 @@ int LabelAddVertex(LABEL *area, int vno, int coords) lv = &area->lv[n]; v = &((MRI_SURFACE *)(area->mris))->vertices[vno]; MRISgetCoords(v, coords, &x, &y, &z); - MRISsurfaceRASToVoxel(area->mris, area->mri_template, v->x, v->y, v->z, &xv, &yv, &zv); + MRISsurfaceRASToVoxel((MRIS *)area->mris, area->mri_template, v->x, v->y, v->z, &xv, &yv, &zv); if (area->mri_template && area->coords == LABEL_COORDS_SCANNER_RAS) MRIvoxelToWorld(area->mri_template, xv, yv, zv, &x, &y, &z); @@ -3933,7 +3932,7 @@ static int labelGetSurfaceRasCoords(LABEL *area, LABEL_VERTEX *lv, float *px, fl break; case LABEL_COORDS_SCANNER_RAS: MRIworldToVoxel(area->mri_template, lv->x, lv->y, lv->z, &xv, &yv, &zv); - MRISsurfaceRASFromVoxel(area->mris, area->mri_template, xv, yv, zv, &xw, &yw, &zw); + MRISsurfaceRASFromVoxel((MRIS *)area->mris, area->mri_template, xv, yv, zv, &xw, &yw, &zw); *px = (float)xw; *py = (float)yw; *pz = (float)zw; // double->float (uggh) @@ -3952,7 +3951,7 @@ static int labelGetVoxelCoords(LABEL *area, LABEL_VERTEX *lv, float *px, float * switch (area->coords) { case LABEL_COORDS_TKREG_RAS: if (area->mris) - MRISsurfaceRASToVoxel(area->mris, area->mri_template, lv->x, lv->y, lv->z, &xv, &yv, &zv); + MRISsurfaceRASToVoxel((MRIS *)area->mris, area->mri_template, lv->x, lv->y, lv->z, &xv, &yv, &zv); else MRIvoxelToSurfaceRAS(area->mri_template, lv->x, lv->y, lv->z, &xv, &yv, &zv); break; diff --git a/utils/log.cpp b/utils/log.cpp new file mode 100644 index 00000000000..2acd977fd2a --- /dev/null +++ b/utils/log.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include + +#include "log.h" + + +// destructor calls the print routine +StreamLogger::~StreamLogger() { + const char *content = ss.str().c_str(); + switch(status) { + case Warning : fprintf(stderr, "%swarning:%s %s\n", term::yellow(), term::reset(), content); break; + case Error : fprintf(stderr, "%serror:%s %s\n", term::red(), term::reset(), content); break; + case Debug : fprintf(stdout, "%s%s%s\n", term::dim(), content, term::reset()); break; + } + + if (exitout) exit(retcode); +} + + +// checks to make sure the output is a tty that accepts colors +static bool termAllowsColor() { + if (!isatty(fileno(stderr))) return false; + if (const char* term = getenv("TERM")) { + return 0 == strcmp(term, "cygwin") + || 0 == strcmp(term, "linux") + || 0 == strcmp(term, "rxvt-unicode-256color") + || 0 == strcmp(term, "screen") + || 0 == strcmp(term, "screen-256color") + || 0 == strcmp(term, "tmux-256color") + || 0 == strcmp(term, "xterm") + || 0 == strcmp(term, "xterm-256color") + || 0 == strcmp(term, "xterm-termite") + || 0 == strcmp(term, "xterm-color"); + } + else return false; +} + + +namespace term { + // colors + const char* black() { return termAllowsColor() ? "\e[30m" : ""; } + const char* red() { return termAllowsColor() ? "\e[31m" : ""; } + const char* green() { return termAllowsColor() ? "\e[32m" : ""; } + const char* yellow() { return termAllowsColor() ? "\e[33m" : ""; } + const char* blue() { return termAllowsColor() ? "\e[34m" : ""; } + const char* purple() { return termAllowsColor() ? "\e[35m" : ""; } + const char* cyan() { return termAllowsColor() ? "\e[36m" : ""; } + const char* light_gray() { return termAllowsColor() ? "\e[37m" : ""; } + const char* white() { return termAllowsColor() ? "\e[37m" : ""; } + const char* light_red() { return termAllowsColor() ? "\e[91m" : ""; } + const char* dim() { return termAllowsColor() ? "\e[2m" : ""; } + // formating + const char* bold() { return termAllowsColor() ? "\e[1m" : ""; } + const char* underline() { return termAllowsColor() ? "\e[4m" : ""; } + // reset + const char* reset() { return termAllowsColor() ? "\e[0m" : ""; } +} \ No newline at end of file diff --git a/utils/lpafile.c b/utils/lpafile.c deleted file mode 100644 index ab85931424f..00000000000 --- a/utils/lpafile.c +++ /dev/null @@ -1,481 +0,0 @@ -/** - * @file lpafile.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.11 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include -#include -#include - -#include "error.h" -#include "hipsu.h" -#include "image.h" -#include "machine.h" -#include "macros.h" -#include "proto.h" -#include "utils.h" - -#include "lpafile.h" - -static int lpafFillEntries(LP_ANSWER_FILE *lpaf, char *fname, int entryno); -static void lpafDump(FILE *fp, LP_ANSWER_FILE *lpaf); -static void lpafAllocParms(IMAGE *I); - -#define NFLUSH 10 /* flush after every 10th write */ -#define INIT_VAL 10000 /* initial value of parameters */ - -int LPAFreadImageAnswer(LPAF *lpaf, int current) -{ - char *fullname, fname[100]; - FILE *fp; - IMAGE Iheader; - int i, ecode, frame, current_frame; - LP_BOX *lpb; - struct extpar *xp; -#ifdef _MSDOS - long *parms; -#else - int *parms; -#endif - - fullname = lpaf->filelist[current]; - - ImageUnpackFileName(fullname, ¤t_frame, &i, fname); - - fp = fopen(fname, "rb"); - if (!fp) ErrorReturn(-1, (ERROR_NO_FILE, "LPAFreadImageAnswer(%d): could not open %s", current, fname)); - - ecode = fread_header(fp, &Iheader, fname); - fclose(fp); - if (ecode) ErrorReturn(-2, (ERROR_BADFILE, "LPAFreadImageAnswer(%s): could not read header", fname)); - - if (Iheader.numparam < Iheader.num_frame) return (0); - -/* read answer from header */ -#if 0 - fprintf(stderr, "reading lp values from %dth entry in image file\n", - current_frame); -#endif - lpb = &lpaf->coords[current]; - for (frame = 0, xp = Iheader.params; xp; xp = xp->nextp) - if (frame++ == current_frame) break; - -/* - if hips file created on Sun, then the parameters are actually longs. -*/ -#ifndef _MSDOS - parms = xp->val.v_pi; -#else - parms = (long *)xp->val.v_pi; -#endif - -#ifndef _MSDOS - if (parms[0] < 0 || parms[0] >= Iheader.cols) { - parms[0] = swapInt(parms[0]); - parms[1] = swapInt(parms[1]); - for (i = 0; i < NPOINTS; i++) { - parms[2 + 2 * i] = swapInt(parms[2 * i]); - parms[2 + 2 * i + 1] = swapInt(parms[2 * i + 1]); - } - } -#else - if (parms[0] < 0 || parms[0] >= (long)Iheader.cols) { - parms[0] = swapLong(parms[0]); - parms[1] = swapLong(parms[1]); - for (i = 0; i < NPOINTS; i++) { - parms[2 + 2 * i] = swapLong(parms[2 * i]); - parms[2 + 2 * i + 1] = swapLong(parms[2 * i + 1]); - } - } -#endif - - if ((int)parms[0] == INIT_VAL) /* not yet written with real value */ - return (0); - - lpb->xc = (int)parms[0]; - lpb->yc = (int)parms[1]; - for (i = 0; i < NPOINTS; i++) { - lpb->xp[i] = (int)parms[2 + 2 * i]; - lpb->yp[i] = (int)parms[2 + 2 * i + 1]; - } - - if (lpb->xc < 0 || lpb->xc >= Iheader.cols || lpb->yc < 0 || lpb->xc >= Iheader.rows) return (0); - - return (1); -} - -int LPAFresetImageAnswer(LPAF *lpaf, int current) -{ - char *fullname, tmpname[100], fname[100]; - IMAGE Iheader, *I; - FILE *infp, *outfp; - int ecode, frame, nframes, *parms, i, current_frame, type; - // LP_BOX *lpb; - struct extpar *xp; - - fullname = lpaf->filelist[current]; - - ImageUnpackFileName(fullname, ¤t_frame, &type, fname); - if (type != HIPS_IMAGE) return (0); - - infp = fopen(fname, "rb"); - if (!infp) ErrorReturn(-1, (ERROR_NO_FILE, "LPAFwriteImageAnswer(%d): could not open %s", current, fname)); - ecode = fread_header(infp, &Iheader, fname); - if (ecode) { - fclose(infp); - ErrorReturn(-2, (ERROR_BADFILE, "LPAFwriteImageAnswer(%d): could not read header", current)); - } - fclose(infp); - if (Iheader.numparam == 0) /* must make room for header in image file */ - { - lpafAllocParms(&Iheader); - - /* now copy the old image file to a new one which has room for parms */ - nframes = Iheader.num_frame; - strcpy(tmpname, FileTmpName(NULL)); - outfp = fopen(tmpname, "wb"); - Iheader.num_frame = 0; /* ImageAppend will bump num_frame on each call */ - ecode = fwrite_header(outfp, &Iheader, tmpname); - fclose(outfp); /* flush file */ - - fprintf(stderr, "rewriting image file to make room for parms...\n"); - for (frame = 0; frame < nframes; frame++) { - I = ImageReadFrames(fname, frame, 1); - if (!I) ErrorExit(ERROR_BADFILE, "LPwriteImageAnswer: could not read frame"); - ImageAppend(I, tmpname); - ImageFree(&I); - } - FileRename(tmpname, fname); - Iheader.num_frame = nframes; /* reset correct # of frames */ - } - - /* now put answer into header */ - // lpb = &lpaf->coords[current]; - - for (frame = 0, xp = Iheader.params; xp; xp = xp->nextp) - if (frame++ == current_frame) break; - - parms = xp->val.v_pi; - parms[0] = INIT_VAL; - parms[1] = INIT_VAL; - for (i = 0; i < NPOINTS; i++) { - parms[2 + 2 * i] = INIT_VAL; - parms[2 + 2 * i + 1] = INIT_VAL; - } - ImageUpdateHeader(&Iheader, fname); - free_hdrcon(&Iheader); - return (1); -} - -int LPAFwriteImageAnswer(LPAF *lpaf, int current) -{ - char *fullname, tmpname[100], fname[100]; - IMAGE Iheader, *I; - FILE *infp, *outfp; - int ecode, frame, nframes, *parms, i, current_frame, type; - LP_BOX *lpb; - struct extpar *xp; - - fullname = lpaf->filelist[current]; - - ImageUnpackFileName(fullname, ¤t_frame, &type, fname); - if (type != HIPS_IMAGE) return (0); - - infp = fopen(fname, "rb"); - if (!infp) ErrorReturn(-1, (ERROR_NO_FILE, "LPAFwriteImageAnswer(%d): could not open %s", current, fname)); - ecode = fread_header(infp, &Iheader, fname); - if (ecode) { - fclose(infp); - ErrorReturn(-2, (ERROR_BADFILE, "LPAFwriteImageAnswer(%d): could not read header", current)); - } - fclose(infp); - if (Iheader.numparam == 0) /* must make room for header in image file */ - { - lpafAllocParms(&Iheader); - - /* now copy the old image file to a new one which has room for parms */ - nframes = Iheader.num_frame; - strcpy(tmpname, FileTmpName(NULL)); - outfp = fopen(tmpname, "wb"); - Iheader.num_frame = 0; /* ImageAppend will bump num_frame on each call */ - ecode = fwrite_header(outfp, &Iheader, tmpname); - fclose(outfp); /* flush file */ - - fprintf(stderr, "rewriting image file to make room for parms...\n"); - for (frame = 0; frame < nframes; frame++) { - I = ImageReadFrames(fname, frame, 1); - if (!I) ErrorExit(ERROR_BADFILE, "LPwriteImageAnswer: could not read frame"); - ImageAppend(I, tmpname); - ImageFree(&I); - } - FileRename(tmpname, fname); - Iheader.num_frame = nframes; /* reset correct # of frames */ - } - - /* now put answer into header */ - lpb = &lpaf->coords[current]; - - for (frame = 0, xp = Iheader.params; xp; xp = xp->nextp) - if (frame++ == current_frame) break; - - parms = xp->val.v_pi; - parms[0] = lpb->xc; - parms[1] = lpb->yc; - for (i = 0; i < NPOINTS; i++) { - parms[2 + 2 * i] = lpb->xp[i]; - parms[2 + 2 * i + 1] = lpb->yp[i]; - } - ImageUpdateHeader(&Iheader, fname); - free_hdrcon(&Iheader); - return (1); -} - -LP_ANSWER_FILE *LPAFcreate(char *out_fname, int argc, char *argv[]) -{ - LP_ANSWER_FILE *lpaf; - int i, nentries, nfiles, entryno; - - nfiles = 0; - for (i = 0; i < argc; i++) { - nentries = FileNumberOfEntries(argv[i]); - nfiles += nentries; - } - - if (nfiles <= 0) ErrorReturn(NULL, (ERROR_NO_FILE, "LPAFcreate: no valid files specified")); - - lpaf = (LP_ANSWER_FILE *)calloc(1, sizeof(*lpaf)); - if (!lpaf) ErrorExit(ERROR_NO_MEMORY, "LPAFcreate: allocation failed"); - if (out_fname) /* write output to file as well as into image file */ - { - strcpy(lpaf->fname, out_fname); - unlink(lpaf->fname); - lpaf->fp = fopen(lpaf->fname, "a+b"); - if (!lpaf->fp) ErrorReturn(NULL, (ERROR_NO_FILE, "LPAFcreate: could not open %s", out_fname)); - } - else - lpaf->fp = NULL; - - lpaf->nfiles = nfiles; - lpaf->last_written = lpaf->current = 0; - lpaf->filelist = (char **)calloc(nfiles, sizeof(char *)); - if (!lpaf->filelist) ErrorExit(ERROR_NO_MEMORY, "LPAFcreate: allocation failed"); - lpaf->coords = (LP_BOX *)calloc(nfiles, sizeof(LP_BOX)); - if (!lpaf->coords) ErrorExit(ERROR_NO_MEMORY, "LPAFcreate: allocation failed"); - lpaf->last_written = 0; - - /* now fill out filelist array */ - entryno = 0; - for (i = 0; i < argc; i++) { - nentries = lpafFillEntries(lpaf, argv[i], entryno); - entryno += nentries; - } - - for (i = 0; i < lpaf->nfiles; i++) lpaf->coords[i].fpos = -1L; - - lpafDump(stderr, lpaf); - - return (lpaf); -} -static int lpafFillEntries(LP_ANSWER_FILE *lpaf, char *fname, int entryno) -{ - int nentries, type, i, num; - char buf[100], *base_name, line[200], *cp; - FILE *fp; - - nentries = FileNumberOfEntries(fname); - type = FileType(fname); - base_name = FileFullName(fname); - - for (i = 0; i < nentries; i++) { - switch (type) { - case LIST_FILE: - fp = fopen(base_name, "rb"); - if (!fp) ErrorReturn(0, (ERROR_NO_FILE, "lpafFillEntries: could not open %s\n", base_name)); - cp = fgetl(line, 199, fp); - nentries = 0; - while (cp) { - sscanf(cp, "%s", buf); - num = lpafFillEntries(lpaf, buf, entryno + nentries); - nentries += num; - cp = fgetl(line, 199, fp); - } - fclose(fp); - break; - default: - sprintf(buf, "%s#%d", base_name, i); - lpaf->filelist[entryno + i] = (char *)calloc(strlen(buf) + 1, sizeof(char)); - strcpy(lpaf->filelist[entryno + i], buf); - break; - } - } - return (nentries); -} - -static void lpafDump(FILE *fp, LP_ANSWER_FILE *lpaf) -{ - int i; - - if (strcmp(lpaf->fname, "test")) return; - fprintf(fp, "lpaf has %d entries:\n", lpaf->nfiles); - for (i = 0; i < lpaf->nfiles; i++) fprintf(fp, "%s\n", lpaf->filelist[i]); -} - -/* filename (centroid) (x, y) ... */ -#define FILE_FMT "%s (%3d, %3d) (%3d, %3d) (%3d, %3d) (%3d, %3d) (%3d, %3d)\n" - -int LPAFwrite(LPAF *lpaf, int current) -{ - LP_BOX *lpb; - - LPAFwriteImageAnswer(lpaf, current); - - if (lpaf->fp) { - lpb = &lpaf->coords[current]; - if (lpb->fpos >= 0L) /* overwrite previous entry */ - { - if (fseek(lpaf->fp, lpb->fpos, SEEK_SET) < 0) - ErrorReturn(-1, (ERROR_BADFILE, "LPAFwrite could not seek to %ld", lpb->fpos)); - } - else - lpb->fpos = ftell(lpaf->fp); - - if (current > lpaf->last_written) - lpaf->last_written = current; - else /* write out rest of file */ - { - } - - fprintf(lpaf->fp, - FILE_FMT, - lpaf->filelist[current], - lpb->xc, - lpb->yc, - lpb->xp[0], - lpb->yp[0], - lpb->xp[1], - lpb->yp[1], - lpb->xp[2], - lpb->yp[2], - lpb->xp[3], - lpb->yp[3]); - - if (lpaf->flush++ >= NFLUSH) { - fflush(lpaf->fp); - lpaf->flush = 0; - } - } - return (0); -} - -int LPAFread(LPAF *lpaf, int current) -{ - LP_BOX *lpb; - char line[300], *cp; - - lpb = &lpaf->coords[current]; - - if (LPAFreadImageAnswer(lpaf, current) <= 0) /* not in image file */ - { - if (!lpaf->fp || (lpb->fpos < 0)) return (0); /* hasn't been written yet */ - - if (fseek(lpaf->fp, lpb->fpos, SEEK_SET) < 0) - ErrorReturn(-1, (ERROR_BADFILE, "LPAFread could not seek to %ld", lpb->fpos)); - - cp = fgetl(line, 299, lpaf->fp); - if (!cp) ErrorReturn(-1, (ERROR_BADFILE, "LPAFread: could not read line")); - - if (sscanf(cp, - FILE_FMT, - lpaf->filelist[current], - &lpb->xc, - &lpb->yc, - &lpb->xp[0], - &lpb->yp[0], - &lpb->xp[1], - &lpb->yp[1], - &lpb->xp[2], - &lpb->yp[2], - &lpb->xp[3], - &lpb->yp[3]) != 11) - ErrorReturn(-1, (ERROR_BADFILE, "LPAFread: could not scan all parms from %s", cp)); - } - -#if 0 - { - int i ; - - for (i = 0 ; i < NPOINTS ; i++) - fprintf(stderr, "(%d, %d) ", lpb->xp[i], lpb->yp[i]) ; - fprintf(stderr, "\n") ; - } -#endif - - return (abs(lpb->xc) < INIT_VAL); /* handles garbages as well as unwritten */ -} - -int LPAFset(LPAF *lpaf, int current, int *xp, int *yp, int xc, int yc) -{ - LP_BOX *lpb; - int i; - - lpb = &lpaf->coords[current]; - lpb->xc = xc; - lpb->yc = yc; - for (i = 0; i < NPOINTS; i++) { - lpb->xp[i] = xp[i]; - lpb->yp[i] = yp[i]; - } - return (1); -} - -#define NPARAMS 10 - -static void lpafAllocParms(IMAGE *I) -{ - int frame, nframes, i; - struct extpar *params; - - nframes = I->num_frame; - I->numparam = nframes; - I->params = params = (struct extpar *)calloc(nframes, sizeof(*params)); - if (!params) ErrorExit(ERROR_NO_MEMORY, "lpafAllocParms: could not allocate (%d, %d)", nframes, sizeof(*params)); - I->paramdealloc = TRUE; - - /* set up link-list and allocate enough space */ - for (frame = 0; frame < nframes; frame++) { - if (frame < (nframes - 1)) - params[frame].nextp = ¶ms[frame + 1]; - else - params[frame].nextp = NULL; - - params[frame].name = STRCPALLOC("LP_ANSWER"); - params[frame].format = PFINT; - params[frame].count = NPARAMS; /* 4 corners and centroid */ - params[frame].dealloc = TRUE; - params[frame].val.v_pi = (int *)calloc(NPARAMS, sizeof(int)); - for (i = 0; i < NPARAMS; i++) params[frame].val.v_pi[i] = INIT_VAL; - } -} diff --git a/utilscpp/lut.cpp b/utils/lut.cpp similarity index 98% rename from utilscpp/lut.cpp rename to utils/lut.cpp index c0ea689d4a7..1c29a397673 100644 --- a/utilscpp/lut.cpp +++ b/utils/lut.cpp @@ -1,7 +1,7 @@ #include #include -#include "lut.hpp" +#include "lut.h" LookupTable::LookupTable(std::string filename) diff --git a/utils/machine.c b/utils/machine.cpp similarity index 100% rename from utils/machine.c rename to utils/machine.cpp diff --git a/utils/matfile.c b/utils/matfile.cpp similarity index 99% rename from utils/matfile.c rename to utils/matfile.cpp index a3b4b2fcd0e..7465db49eb1 100644 --- a/utils/matfile.c +++ b/utils/matfile.cpp @@ -40,7 +40,7 @@ static void matFree(double **matrix, int nrows, int ncols); static int readMatFile(FILE *fp, MATFILE *mf, double **real_matrix, double **imag_matrix); static int znzreadMatFile(char *unbuff, MATFILE *mf, double **real_matrix, double **imag_matrix); static void swapBytes(MATFILE *mf); -static char *MatProgname = "matfile"; +static const char *MatProgname = "matfile"; int MatFileWrite(const char *fname, float *data, int rows, int cols, const char *name); char *MatReadHeader(FILE *fp, MATFILE *mf, long32 *compressed); @@ -874,7 +874,7 @@ char *MatReadHeader(FILE *fp, MATFILE *mf, long32 *compressed) long32 dt; char ctmp[4]; long32 tmp; - int fourbytes = 4; + unsigned int fourbytes = 4; if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) DiagPrintf(DIAG_VERBOSE, "MatReadHeader: fp=%lx, mf=%lx\n", fp, mf); diff --git a/utils/matrix.c b/utils/matrix.cpp similarity index 99% rename from utils/matrix.c rename to utils/matrix.cpp index 280cf1a0cdb..a3253fcfd15 100644 --- a/utils/matrix.c +++ b/utils/matrix.cpp @@ -867,7 +867,7 @@ int MatrixPrint(FILE *fp, const MATRIX *mat) return (NO_ERROR); } -int MatrixPrintWithString(FILE *fp, MATRIX *m, char *Pre, char *Post) +int MatrixPrintWithString(FILE *fp, MATRIX *m, const char *Pre, const char *Post) { int err; fprintf(fp, "%s", Pre); diff --git a/utils/mgh_filter.c b/utils/mgh_filter.cpp similarity index 100% rename from utils/mgh_filter.c rename to utils/mgh_filter.cpp diff --git a/utils/mgh_malloc.c b/utils/mgh_malloc.cpp similarity index 100% rename from utils/mgh_malloc.c rename to utils/mgh_malloc.cpp diff --git a/utils/mgh_matrix.c b/utils/mgh_matrix.c deleted file mode 100644 index 69fe32e6c27..00000000000 --- a/utils/mgh_matrix.c +++ /dev/null @@ -1,658 +0,0 @@ -/** - * @file mgh_matrix.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.7 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include - -#include "error.h" -#include "proto.h" -#include "typedefs.h" - -#include "mgh_matrix.h" - -FLOATTYPE *MGH_vector(int n) -{ - FLOATTYPE *h; - - h = (FLOATTYPE *)calloc(n, sizeof(FLOATTYPE)); - if (h == NULL) { - printf("out of memory in vector(%d)\n", n); - exit(0); - } - return h; -} - -int *MGH_ivector(int n) -{ - int *h; - - h = (int *)calloc(n, sizeof(int)); - if (h == NULL) { - printf("out of memory in ivector(%d)\n", n); - exit(0); - } - return h; -} - -FLOATTYPE **MGH_matrix(int n, int m) -{ - FLOATTYPE **h; - int i; - - h = (FLOATTYPE **)calloc(n, sizeof(FLOATTYPE *)); - if (h == NULL) { - printf("out of memory in matrix(%d,%d)\n", n, m); - exit(0); - } - for (i = 0; i < n; i++) h[i] = MGH_vector(m); - return h; -} - -void print_matrix(FLOATTYPE **a, int m, int n) -{ - int i, j; - - if (n > 0) { - for (i = 0; i < m; i++) { - for (j = 0; j < n; j++) { - printf("%10.3e ", a[i][j]); - } - printf("\n"); - } - printf("\n"); - } -} - -void read_matrix(FILE *fptr, FLOATTYPE **a, int m, int n) -{ - int i, j; - float f; - - for (i = 0; i < m; i++) - for (j = 0; j < n; j++) { - if (fscanf(fptr, "%f", &f) != 1) { - printf("read_matrix: scan failed\n"); - } - a[i][j] = f; - } -} - -void print_vector(FLOATTYPE *v, int n) -{ - int i; - - for (i = 0; i < n; i++) { - printf("%10.3e ", v[i]); - } - printf("\n\n"); -} - -void row_vector(FLOATTYPE **a, FLOATTYPE *v, int i, int n) -{ - int j; - - for (j = 0; j < n; j++) { - v[j] = a[i][j]; - } -} - -void vector_to_matrix(FLOATTYPE *v, FLOATTYPE **a, int m, int n) -{ - int i, j, indx = 0; - - for (i = 0; i < m; i++) - for (j = 0; j < n; j++) { - a[i][j] = v[indx++]; - } -} - -void scale_matrix(FLOATTYPE **a, FLOATTYPE s, int n, int m) -{ - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < m; j++) a[i][j] *= s; -} - -void normalize_matrix(FLOATTYPE **a, int n, int m) -{ - FLOATTYPE sum = 0; - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < m; j++) sum += a[i][j]; - /* scale_matrix(a,n/sum,n,m); */ -} - -void matrix_copy(FLOATTYPE **a, FLOATTYPE **b, int n, int m) -{ - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < m; j++) b[i][j] = a[i][j]; -} - -void matrix_copy2(FLOATTYPE **a, FLOATTYPE **b, int n, int m, int sno, int smo, int tno, int tmo) -{ - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < m; j++) b[i + tno][j + tmo] = a[i + sno][j + smo]; -} - -void matrix_transpose(FLOATTYPE **a, FLOATTYPE **at, int n, int m) -{ - int i, j; - - for (i = 0; i < m; i++) - for (j = 0; j < n; j++) at[i][j] = a[j][i]; -} - -void matrix_add(FLOATTYPE **a, FLOATTYPE **b, FLOATTYPE **c, int n, int m) -{ - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < m; j++) c[i][j] = a[i][j] + b[i][j]; -} - -void matrix_multiply(FLOATTYPE **a, FLOATTYPE **b, FLOATTYPE **c, int n, int m) -{ - FLOATTYPE sum; - int i, j, k; - - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - sum = 0.0; - for (k = 0; k < m; k++) sum += a[i][k] * b[k][j]; - c[i][j] = sum; - } - } -} - -void matrix_multiply2(FLOATTYPE **a, FLOATTYPE **b, FLOATTYPE **c, int n, int m, int l) -{ - FLOATTYPE sum; - int i, j, k; - - for (i = 0; i < n; i++) { - for (j = 0; j < l; j++) { - sum = 0.0; - for (k = 0; k < m; k++) sum += a[i][k] * b[k][j]; - c[i][j] = sum; - } - } -} - -void matrix_angles(FLOATTYPE **a, FLOATTYPE **b, FLOATTYPE **c, int n, int m) -{ - FLOATTYPE sum, asum, bsum; - int i, j, k; - - for (i = 0; i < n; i++) { - for (j = 0; j < m; j++) { - sum = asum = bsum = 0.0; - for (k = 0; k < m; k++) { - sum += a[i][k] * b[k][j]; - asum += a[i][k] * a[i][k]; - bsum += b[k][j] * b[k][j]; - } - c[i][j] = (sum == 0.0) ? 0.0 : sum / sqrt(asum * bsum); - } - } -} - -void vector_subtract(FLOATTYPE *a, FLOATTYPE *b, FLOATTYPE *c, int n) -{ - int i; - - for (i = 0; i < n; i++) c[i] = a[i] - b[i]; -} - -void vector_add(FLOATTYPE *a, FLOATTYPE *b, FLOATTYPE *c, FLOATTYPE fa, FLOATTYPE fb, int n) -{ - int i; - - for (i = 0; i < n; i++) c[i] = fa * a[i] + fb * b[i]; -} - -void vector_multiply(FLOATTYPE **a, FLOATTYPE *b, FLOATTYPE *c, int n, int m) -{ - FLOATTYPE sum; - int i, j; - - for (i = 0; i < n; i++) { - sum = 0.0; - for (j = 0; j < m; j++) sum += a[i][j] * b[j]; - c[i] = sum; - } -} - -void derivative_matrix(FLOATTYPE **D, int dy, int dx) -{ - int i, j, n = dx * dy; - - for (i = 0; i < n; i++) - for (j = 0; j < n; j++) D[i][j] = 0.0; - for (i = 0; i < n; i++) { - D[i][i] = 1; - D[i][(i + 1) % n] = -1; - } -} - -void MGH_identity_matrix(FLOATTYPE **I, int n) -{ - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < n; j++) I[i][j] = (i == j) ? 1.0 : 0.0; -} - -void regularization_matrix(FLOATTYPE **R, int n) -{ - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < n; j++) R[i][j] = 0; - for (i = 0; i < n; i++) { - R[i][(i == 0) ? n - 1 : i - 1] = -1.0; - R[i][i] = 2.1; - R[i][(i == n - 1) ? 0 : i + 1] = -1.0; - } -} - -void covariance_matrix(FLOATTYPE **R, int n) -{ - int i, j; - - for (i = 0; i < n; i++) - for (j = 0; j < n; j++) { - R[i][j] = 1.0 / (1.0 + fabs(i - j)); - /* printf("i=%d,j=%d,R[i][j]=%f\n",i,j,R[i][j]); */ - } -} - -void mgh_ludcmp(FLOATTYPE **a, int n, int *indx, FLOATTYPE *d) -{ - int i, imax = 0, j, k; /* imax = 0 to shut up gcc */ - FLOATTYPE big, dum, sum, temp; - FLOATTYPE *vv, *vector(); - - vv = MGH_vector(n); - *d = 1.0; - for (i = 0; i < n; i++) { - big = 0.0; - for (j = 0; j < n; j++) - if ((temp = fabs(a[i][j])) > big) big = temp; - if (big == 0.0) ErrorExit(ERROR_BADPARM, "LU decomposition: matrix in singular"); - vv[i] = 1.0 / big; - } - for (j = 0; j < n; j++) { - for (i = 0; i < j; i++) { - sum = a[i][j]; - for (k = 0; k < i; k++) sum -= a[i][k] * a[k][j]; - a[i][j] = sum; - } - big = 0.0; - for (i = j; i < n; i++) { - sum = a[i][j]; - for (k = 0; k < j; k++) sum -= a[i][k] * a[k][j]; - a[i][j] = sum; - if ((dum = vv[i] * fabs(sum)) >= big) { - big = dum; - imax = i; - } - } - if (j != imax) { - for (k = 0; k < n; k++) { - dum = a[imax][k]; - a[imax][k] = a[j][k]; - a[j][k] = dum; - } - *d = -(*d); - vv[imax] = vv[j]; - } - indx[j] = imax; - if (a[j][j] == 0.0) a[j][j] = TINY; - if (j != n - 1) { - dum = 1.0 / (a[j][j]); - for (i = j + 1; i < n; i++) a[i][j] *= dum; - } - } - free(vv); -} - -void mgh_lubksb(FLOATTYPE **a, int n, int *indx, FLOATTYPE *b) -{ - int i, ii = -1, ip, j; - FLOATTYPE sum; - - for (i = 0; i < n; i++) { - ip = indx[i]; - sum = b[ip]; - b[ip] = b[i]; - if (ii > -1) - for (j = ii; j < i; j++) sum -= a[i][j] * b[j]; - else if (sum) - ii = i; - b[i] = sum; - } - for (i = n - 1; i >= 0; i--) { - sum = b[i]; - for (j = i + 1; j < n; j++) sum -= a[i][j] * b[j]; - b[i] = sum / a[i][i]; - } -} - -void inverse(FLOATTYPE **a, FLOATTYPE **y, int n) -{ - FLOATTYPE d, *col; - int i, j, *indx; - - col = MGH_vector(n); - indx = MGH_ivector(n); - mgh_ludcmp(a, n, indx, &d); - for (j = 0; j < n; j++) { - for (i = 0; i < n; i++) col[i] = 0.0; - col[j] = 1.0; - mgh_lubksb(a, n, indx, col); - for (i = 0; i < n; i++) y[i][j] = col[i]; - } -} - -FLOATTYPE determinant(FLOATTYPE **a, int n) -{ - FLOATTYPE d; - int j, *indx; - - indx = MGH_ivector(n); - mgh_ludcmp(a, n, indx, &d); - print_matrix(a, n, n); - for (j = 0; j < n; j++) d *= a[j][j]; - return d; -} - -FLOATTYPE MGH_svd(FLOATTYPE **A, FLOATTYPE **V, FLOATTYPE *z, int m, int n) -{ - int i, j, k, count; - FLOATTYPE c, s, p, q, r, v, toll = 0.1; - - MGH_identity_matrix(V, n); - for (count = n * (n - 1) / 2; count > 0;) { - count = n * (n - 1) / 2; - for (j = 0; j < n - 1; j++) { - for (k = j + 1; k < n; k++) { - p = q = r = 0; - for (i = 0; i < m; i++) { - p += A[i][j] * A[i][k]; - q += A[i][j] * A[i][j]; - r += A[i][k] * A[i][k]; - } - if ((q * r == 0) || (p * p / (q * r) < toll)) count--; - if (q < r) { - c = 0; - s = 1; - } - else { - q = q - r; - v = sqrt(4 * p * p + q * q); - c = sqrt((v + q) / (2 * v)); - s = p / (v * c); - } - for (i = 0; i < m; i++) { - r = A[i][j]; - A[i][j] = r * c + A[i][k] * s; - A[i][k] = -r * s + A[i][k] * c; - } - for (i = 0; i < n; i++) { - r = V[i][j]; - V[i][j] = r * c + V[i][k] * s; - V[i][k] = -r * s + V[i][k] * c; - } - } - } - printf("count=%d\n", count); - print_matrix(A, m, n); - } - for (j = 0; j < n; j++) { - q = 0; - for (i = 0; i < m; i++) q += A[i][j] * A[i][j]; - q = sqrt(q); - z[j] = q; - - for (i = 0; i < m; i++) A[i][j] /= q; - } - - return (FLOATTYPE)(0.0); /* What is this *really* suppose to return? (RJW) */ -} - -static FLOATTYPE at, bt, ct; -#define PYTHAG(a, b) \ - ((at = fabs(a)) > (bt = fabs(b)) ? (ct = bt / at, at * sqrt(1.0 + ct * ct)) \ - : (bt ? (ct = at / bt, bt * sqrt(1.0 + ct * ct)) : 0.0)) - -#ifdef MAX -#undef MAX -#endif -static FLOATTYPE maxarg1, maxarg2; -#define MAX(a, b) (maxarg1 = (a), maxarg2 = (b), (maxarg1) > (maxarg2) ? (maxarg1) : (maxarg2)) - -#ifndef SIGN -#define SIGN(a, b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) -#endif - -void mgh_svdcmp(FLOATTYPE **a, FLOATTYPE *w, FLOATTYPE **v, int m, int n) -{ - int flag, i, its, j, jj, k, l = 0, nm = 0; /* Keep gcc happy */ - FLOATTYPE c, f, h, s, x, y, z; - FLOATTYPE anorm = 0.0, g = 0.0, scale = 0.0; - FLOATTYPE *rv1; - - if (m < n) ErrorExit(ERROR_BADPARM, "Singular value decompostion: input matrix has too few rows"); - rv1 = MGH_vector(n); - for (i = 0; i < n; i++) { - l = i + 1; - rv1[i] = scale * g; - g = s = scale = 0.0; - if (i < m) { - for (k = i; k < m; k++) scale += fabs(a[k][i]); - if (scale) { - for (k = i; k < m; k++) { - a[k][i] /= scale; - s += a[k][i] * a[k][i]; - } - f = a[i][i]; - g = -SIGN(sqrt(s), f); - h = f * g - s; - a[i][i] = f - g; - if (i != n - 1) { - for (j = l; j < n; j++) { - for (s = 0.0, k = i; k < m; k++) s += a[k][i] * a[k][j]; - f = s / h; - for (k = i; k < m; k++) a[k][j] += f * a[k][i]; - } - } - for (k = i; k < m; k++) a[k][i] *= scale; - } - } - w[i] = scale * g; - g = s = scale = 0.0; - if (i < m && i != n - 1) { - for (k = l; k < n; k++) scale += fabs(a[i][k]); - if (scale) { - for (k = l; k < n; k++) { - a[i][k] /= scale; - s += a[i][k] * a[i][k]; - } - f = a[i][l]; - g = -SIGN(sqrt(s), f); - h = f * g - s; - a[i][l] = f - g; - for (k = l; k < n; k++) rv1[k] = a[i][k] / h; - if (i != m - 1) { - for (j = l; j < m; j++) { - for (s = 0.0, k = l; k < n; k++) s += a[j][k] * a[i][k]; - for (k = l; k < n; k++) a[j][k] += s * rv1[k]; - } - } - for (k = l; k < n; k++) a[i][k] *= scale; - } - } - anorm = MAX(anorm, (fabs(w[i]) + fabs(rv1[i]))); - } - - for (i = n - 1; i >= 0; i--) { - if (i < n - 1) { - if (g) { - for (j = l; j < n; j++) v[j][i] = (a[i][j] / a[i][l]) / g; - for (j = l; j < n; j++) { - for (s = 0.0, k = l; k < n; k++) s += a[i][k] * v[k][j]; - for (k = l; k < n; k++) v[k][j] += s * v[k][i]; - } - } - for (j = l; j < n; j++) v[i][j] = v[j][i] = 0.0; - } - v[i][i] = 1.0; - g = rv1[i]; - l = i; - } - - for (i = n - 1; i >= 0; i--) { - l = i + 1; - g = w[i]; - if (i < n - 1) - for (j = l; j < n; j++) a[i][j] = 0.0; - if (g) { - g = 1.0 / g; - if (i != n - 1) { - for (j = l; j < n; j++) { - for (s = 0.0, k = l; k < m; k++) s += a[k][i] * a[k][j]; - f = (s / a[i][i]) * g; - for (k = i; k < m; k++) a[k][j] += f * a[k][i]; - } - } - for (j = i; j < m; j++) a[j][i] *= g; - } - else { - for (j = i; j < m; j++) a[j][i] = 0.0; - } - ++a[i][i]; - } - - for (k = n - 1; k >= 0; k--) { - for (its = 1; its <= 30; its++) { - flag = 1; - for (l = k; l >= 0; l--) { - nm = l - 1; - if ((FLOATTYPE)(fabs(rv1[l]) + anorm) == anorm) { - flag = 0; - break; - } - if ((FLOATTYPE)(fabs(w[nm]) + anorm) == anorm) break; - } - if (flag) { - c = 0.0; - s = 1.0; - for (i = l; i <= k; i++) { - f = s * rv1[i]; - rv1[i] = c * rv1[i]; - if ((FLOATTYPE)(fabs(f) + anorm) == anorm) break; - g = w[i]; - h = PYTHAG(f, g); - w[i] = h; - h = 1.0 / h; - c = g * h; - s = (-f * h); - for (j = 0; j < m; j++) { - y = a[j][nm]; - z = a[j][i]; - a[j][nm] = y * c + z * s; - a[j][i] = z * c - y * s; - } - } - } - z = w[k]; - if (l == k) { - if (z < 0.0) { - w[k] = -z; - for (j = 0; j < n; j++) v[j][k] = (-v[j][k]); - } - break; - } - if (its == 30) ErrorExit(ERROR_BADPARM, "Singular value decomposition failed to converge"); - x = w[l]; - nm = k - 1; - y = w[nm]; - g = rv1[nm]; - h = rv1[k]; - f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2.0 * h * y); - g = PYTHAG(f, 1.0); - f = ((x - z) * (x + z) + h * ((y / (f + SIGN(g, f))) - h)) / x; - - c = s = 1.0; - for (j = l; j <= nm; j++) { - i = j + 1; - g = rv1[i]; - y = w[i]; - h = s * g; - g = c * g; - z = PYTHAG(f, h); - rv1[j] = z; - c = f / z; - s = h / z; - f = x * c + g * s; - g = g * c - x * s; - h = y * s; - y = y * c; - for (jj = 0; jj < n; jj++) { - x = v[jj][j]; - z = v[jj][i]; - v[jj][j] = x * c + z * s; - v[jj][i] = z * c - x * s; - } - z = PYTHAG(f, h); - w[j] = z; - if (z) { - z = 1.0 / z; - c = f * z; - s = h * z; - } - f = (c * g) + (s * y); - x = (c * y) - (s * g); - for (jj = 0; jj < m; jj++) { - y = a[jj][j]; - z = a[jj][i]; - a[jj][j] = y * c + z * s; - a[jj][i] = z * c - y * s; - } - } - rv1[l] = 0.0; - rv1[k] = f; - w[k] = x; - } - } - free(rv1); -} diff --git a/utils/min_heap.c b/utils/min_heap.cpp similarity index 100% rename from utils/min_heap.c rename to utils/min_heap.cpp diff --git a/utils/mincutils.c b/utils/mincutils.c deleted file mode 100644 index 587867ea06a..00000000000 --- a/utils/mincutils.c +++ /dev/null @@ -1,273 +0,0 @@ -/** - * @file mincutils.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "mincutils.h" - -#include - -#include "mri.h" -#include "minc_volume_io.h" - -/*-----------------------------------------------------*/ -int DumpMINCAxes(FILE *fp, MINCAXES *MA) -{ - int i; - - fprintf(fp, - "Storage Order: %d %d %d\n", - MA->VoxAxisStorageOrder[0], - MA->VoxAxisStorageOrder[1], - MA->VoxAxisStorageOrder[2]); - fprintf(fp, "Volume Voxel Center: %g %g %g\n", MA->VolCenterVox[0], MA->VolCenterVox[1], MA->VolCenterVox[2]); - fprintf(fp, "Volume World Center: %g %g %g\n", MA->VolCenterWorld[0], MA->VolCenterWorld[1], MA->VolCenterWorld[2]); - - for (i = 0; i < 3; i++) { - fprintf(fp, "VoxAxisName: %s ------ \n", MA->Axis[i].VoxAxisName); - fprintf(fp, "VoxAxisId: %d\n", MA->Axis[i].VoxAxisId); - fprintf(fp, "MINCAxisId: %d\n", MA->Axis[i].MINCAxisId); - fprintf(fp, "MINCAxisName: %s\n", MA->Axis[i].MINCAxisName); - fprintf(fp, "Length: %d\n", MA->Axis[i].Len); - fprintf(fp, "Resolution: %g\n", MA->Axis[i].Res); - fprintf(fp, "DC: %g %g %g \n", MA->Axis[i].DirCos[0], MA->Axis[i].DirCos[1], MA->Axis[i].DirCos[2]); - } - - return (0); -} - -/*-----------------------------------------------------*/ -MINCAXES *ConfigMINCAxes(MRI *mri) -{ - MINCAXES *MA; - int va; - - MA = (MINCAXES *)calloc(1, sizeof(MINCAXES)); - - /* column voxel axis */ - va = 0; - MA->Axis[va].VoxAxisId = va; - MA->Axis[va].VoxAxisName = "col"; - MA->Axis[va].VoxAxisId = va; - MA->Axis[va].Len = mri->width; - MA->Axis[va].Res = mri->xsize; - MA->Axis[va].DirCos[0] = mri->x_r; - MA->Axis[va].DirCos[1] = mri->x_a; - MA->Axis[va].DirCos[2] = mri->x_s; - - /* row voxel axis */ - va = 1; - MA->Axis[va].VoxAxisId = va; - MA->Axis[va].VoxAxisName = "row"; - MA->Axis[va].VoxAxisId = va; - MA->Axis[va].Len = mri->height; - MA->Axis[va].Res = mri->ysize; - MA->Axis[va].DirCos[0] = mri->y_r; - MA->Axis[va].DirCos[1] = mri->y_a; - MA->Axis[va].DirCos[2] = mri->y_s; - - /* slice voxel axis */ - va = 2; - MA->Axis[va].VoxAxisId = va; - MA->Axis[va].VoxAxisName = "slice"; - MA->Axis[va].VoxAxisId = va; - MA->Axis[va].Len = mri->depth; - MA->Axis[va].Res = mri->zsize; - MA->Axis[va].DirCos[0] = mri->z_r; - MA->Axis[va].DirCos[1] = mri->z_a; - MA->Axis[va].DirCos[2] = mri->z_s; - - MA->VolCenterWorld[0] = mri->c_r; - MA->VolCenterWorld[1] = mri->c_a; - MA->VolCenterWorld[2] = mri->c_s; - - NameMINCAxes(MA); - MINCAxesStorageOrder(MA); - - return (MA); -} - -/*-----------------------------------------------------*/ -int NameMINCAxes(MINCAXES *MA) -{ - int xspacehit, yspacehit, zspacehit; - int xspaceid, yspaceid, zspaceid; - char *space[3]; - int colspaceid = 0, rowspaceid = 0, slcspaceid = 0; - float col_dc_x, col_dc_y, col_dc_z; - float row_dc_x, row_dc_y, row_dc_z; - float slc_dc_x, slc_dc_y, slc_dc_z; - int err; - - col_dc_x = fabs(MA->Axis[0].DirCos[0]); - col_dc_y = fabs(MA->Axis[0].DirCos[1]); - col_dc_z = fabs(MA->Axis[0].DirCos[2]); - - row_dc_x = fabs(MA->Axis[1].DirCos[0]); - row_dc_y = fabs(MA->Axis[1].DirCos[1]); - row_dc_z = fabs(MA->Axis[1].DirCos[2]); - - slc_dc_x = fabs(MA->Axis[2].DirCos[0]); - slc_dc_y = fabs(MA->Axis[2].DirCos[1]); - slc_dc_z = fabs(MA->Axis[2].DirCos[2]); - - xspaceid = 0; - yspaceid = 1; - zspaceid = 2; - - xspacehit = 0; - yspacehit = 0; - zspacehit = 0; - - /* Name the Column Axis */ - if (col_dc_x >= row_dc_x && col_dc_x >= slc_dc_x) { - colspaceid = xspaceid; - MA->VolCenterVox[0] = (MA->Axis[0].Len - 1) / 2; - xspacehit = 1; - } - else if (col_dc_y >= row_dc_y && col_dc_y >= slc_dc_y) { - colspaceid = yspaceid; - MA->VolCenterVox[1] = (MA->Axis[0].Len - 1) / 2; - yspacehit = 1; - } - else if (col_dc_z >= row_dc_z && col_dc_z >= slc_dc_z) { - colspaceid = zspaceid; - MA->VolCenterVox[2] = (MA->Axis[0].Len - 1) / 2; - zspacehit = 1; - } - - /* Name the Row Axis */ - if (!xspacehit && row_dc_x >= slc_dc_x) { - rowspaceid = xspaceid; - MA->VolCenterVox[0] = (MA->Axis[1].Len - 1) / 2; - xspacehit = 1; - } - else if (!yspacehit && row_dc_y >= slc_dc_y) { - rowspaceid = yspaceid; - MA->VolCenterVox[1] = (MA->Axis[1].Len - 1) / 2; - yspacehit = 1; - } - else if (!zspacehit && row_dc_z >= slc_dc_z) { - rowspaceid = zspaceid; - MA->VolCenterVox[2] = (MA->Axis[1].Len - 1) / 2; - zspacehit = 1; - } - - /* Name the Slice Axis */ - if (!xspacehit) { - slcspaceid = xspaceid; - MA->VolCenterVox[0] = (MA->Axis[2].Len - 1) / 2; - xspacehit = 1; - } - else if (!yspacehit) { - slcspaceid = yspaceid; - MA->VolCenterVox[1] = (MA->Axis[2].Len - 1) / 2; - yspacehit = 1; - } - if (!zspacehit) { - slcspaceid = zspaceid; - MA->VolCenterVox[2] = (MA->Axis[2].Len - 1) / 2; - zspacehit = 1; - } - - /* Check for errors */ - err = 0; - if (!xspacehit) { - printf("ERROR: could not assign xspace\n"); - err = 1; - } - if (!yspacehit) { - printf("ERROR: could not assign yspace\n"); - err = 1; - } - if (!zspacehit) { - printf("ERROR: could not assign zspace\n"); - err = 1; - } - if (err) return (1); - - /* Make final assignments */ - space[xspaceid] = MIxspace; - space[yspaceid] = MIyspace; - space[zspaceid] = MIzspace; - - MA->Axis[0].MINCAxisId = colspaceid; - MA->Axis[1].MINCAxisId = rowspaceid; - MA->Axis[2].MINCAxisId = slcspaceid; - - MA->Axis[0].MINCAxisName = space[colspaceid]; - MA->Axis[1].MINCAxisName = space[rowspaceid]; - MA->Axis[2].MINCAxisName = space[slcspaceid]; - - return (0); -} -/*-----------------------------------------------------*/ -int MINCAxesStorageOrder(MINCAXES *MA) -{ - int ncols, nrows, nslcs; - int col, row, slc; - - col = 0; - row = 1; - slc = 2; - - ncols = MA->Axis[0].Len; - nrows = MA->Axis[1].Len; - nslcs = MA->Axis[2].Len; - - if (ncols >= nrows && ncols >= nslcs) { - MA->VoxAxisStorageOrder[0] = col; - if (nrows >= nslcs) { - MA->VoxAxisStorageOrder[1] = row; - MA->VoxAxisStorageOrder[2] = slc; - } - else { - MA->VoxAxisStorageOrder[1] = slc; - MA->VoxAxisStorageOrder[2] = row; - } - } - else if (nrows >= nslcs) { - MA->VoxAxisStorageOrder[0] = row; - if (ncols >= nslcs) { - MA->VoxAxisStorageOrder[1] = col; - MA->VoxAxisStorageOrder[2] = slc; - } - else { - MA->VoxAxisStorageOrder[1] = slc; - MA->VoxAxisStorageOrder[2] = col; - } - } - else { - MA->VoxAxisStorageOrder[0] = slc; - if (ncols >= nrows) { - MA->VoxAxisStorageOrder[1] = col; - MA->VoxAxisStorageOrder[2] = row; - } - else { - MA->VoxAxisStorageOrder[1] = row; - MA->VoxAxisStorageOrder[2] = col; - } - } - - return (0); -} diff --git a/utils/minmaxrc.c b/utils/minmaxrc.c deleted file mode 100644 index 208a75e9108..00000000000 --- a/utils/minmaxrc.c +++ /dev/null @@ -1,184 +0,0 @@ -/** - * @file minmaxrc.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/************************************************************** - * Name: minmaxrc.c - * Author: Douglas N. Greve, 5/14/96 - * Purpose: hips-based routines to find the minimum and maximum - * pixel values in an image as well as their row and - * column. The hips function h_minmax() does not - * return the row and col of the min and max. - * Notes: 1. MinPoint[0] = row of minimum... - ***************************************************************/ - -#include - -#include "minmaxrc.h" - -/************************************************************/ -int h_minmaxrc(struct header *phdSrc, Pixelval *Min, int MinPoint[2], Pixelval *Max, int MaxPoint[2]) -{ - switch (phdSrc->pixel_format) { - case PFBYTE: - return (h_minmaxrc_b(phdSrc, (byte *)Min, MinPoint, (byte *)Max, MaxPoint)); - case PFSHORT: - return (h_minmaxrc_s(phdSrc, (short *)Min, MinPoint, (short *)Max, MaxPoint)); - case PFINT: - return (h_minmaxrc_i(phdSrc, (int *)Min, MinPoint, (int *)Max, MaxPoint)); - case PFFLOAT: - return (h_minmaxrc_f(phdSrc, (float *)Min, MinPoint, (float *)Max, MaxPoint)); - default: - return (perr(HE_FMTSUBR, "h_minmaxrc:", hformatname(phdSrc->pixel_format))); - } -} - -/************************************************************/ -int h_minmaxrc_b(struct header *phdSrc, byte *Min, int MinPoint[2], byte *Max, int MaxPoint[2]) -{ - register int r, c; - register byte x, *p; - - p = phdSrc->image; - - *Min = *p; - *Max = *p; - MinPoint[0] = 0; - MinPoint[1] = 0; - MaxPoint[0] = 0; - MaxPoint[1] = 0; - - for (r = 0; r < phdSrc->rows; r++) { - for (c = 0; c < phdSrc->cols; c++) { - x = *p++; - if (x > *Max) { - *Max = x; - MaxPoint[0] = r; - MaxPoint[1] = c; - } - else if (x < *Min) { - *Min = x; - MinPoint[0] = r; - MinPoint[1] = c; - } - } - } - return (HIPS_OK); -} -/************************************************************/ -int h_minmaxrc_s(struct header *phdSrc, short *Min, int MinPoint[2], short *Max, int MaxPoint[2]) -{ - register int r, c; - register short x, *p; - - p = (short *)phdSrc->image; - - *Min = *p; - *Max = *p; - MinPoint[0] = 0; - MinPoint[1] = 0; - MaxPoint[0] = 0; - MaxPoint[1] = 0; - - for (r = 0; r < phdSrc->rows; r++) { - for (c = 0; c < phdSrc->cols; c++) { - x = *p++; - if (x > *Max) { - *Max = x; - MaxPoint[0] = r; - MaxPoint[1] = c; - } - else if (x < *Min) { - *Min = x; - MinPoint[0] = r; - MinPoint[1] = c; - } - } - } - return (HIPS_OK); -} -/************************************************************/ -int h_minmaxrc_i(struct header *phdSrc, int *Min, int MinPoint[2], int *Max, int MaxPoint[2]) -{ - register int r, c; - register int x, *p; - - p = (int *)phdSrc->image; - - *Min = *p; - *Max = *p; - MinPoint[0] = 0; - MinPoint[1] = 0; - MaxPoint[0] = 0; - MaxPoint[1] = 0; - - for (r = 0; r < phdSrc->rows; r++) { - for (c = 0; c < phdSrc->cols; c++) { - x = *p++; - if (x > *Max) { - *Max = x; - MaxPoint[0] = r; - MaxPoint[1] = c; - } - else if (x < *Min) { - *Min = x; - MinPoint[0] = r; - MinPoint[1] = c; - } - } - } - return (HIPS_OK); -} -/************************************************************/ -int h_minmaxrc_f(struct header *phdSrc, float *Min, int MinPoint[2], float *Max, int MaxPoint[2]) -{ - register int r, c; - register float x, *p; - - p = (float *)phdSrc->image; - - *Min = *p; - *Max = *p; - MinPoint[0] = 0; - MinPoint[1] = 0; - MaxPoint[0] = 0; - MaxPoint[1] = 0; - - for (r = 0; r < phdSrc->rows; r++) { - for (c = 0; c < phdSrc->cols; c++) { - x = *p++; - if (x > *Max) { - *Max = x; - MaxPoint[0] = r; - MaxPoint[1] = c; - } - else if (x < *Min) { - *Min = x; - MinPoint[0] = r; - MinPoint[1] = c; - } - } - } - return (HIPS_OK); -} diff --git a/utils/morph.c b/utils/morph.cpp similarity index 99% rename from utils/morph.c rename to utils/morph.cpp index bc4e23ca907..1f6d5bce223 100644 --- a/utils/morph.c +++ b/utils/morph.cpp @@ -736,7 +736,7 @@ IMAGE *ImageMorph(IMAGE *Isrc, IMAGE *Idst, int which) IMAGE *Iin, *Itmp, *Iout, *Ifiltered; unsigned char *lut; - if (which < 0 || which >= NLUTS) ErrorReturn(NULL, (ERROR_BADPARM, "ImageMorph(%d): unknown operation code", which)); + if (which < 0 || (unsigned)which >= NLUTS) ErrorReturn(NULL, (ERROR_BADPARM, "ImageMorph(%d): unknown operation code", which)); lut = lut_pointers[which]; diff --git a/utils/mosaic.c b/utils/mosaic.cpp similarity index 100% rename from utils/mosaic.c rename to utils/mosaic.cpp diff --git a/utils/mri.c b/utils/mri.cpp similarity index 99% rename from utils/mri.c rename to utils/mri.cpp index ced112f6c8e..5802cabf29f 100644 --- a/utils/mri.c +++ b/utils/mri.cpp @@ -23,7 +23,6 @@ */ extern const char *Progname; -const char *MRI_C_VERSION = "$Revision: 1.575 $"; /*----------------------------------------------------- INCLUDE FILES @@ -50,10 +49,9 @@ const char *MRI_C_VERSION = "$Revision: 1.575 $"; #include "fnv_hash.h" #include "macros.h" #include "matrix.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mri2.h" #include "mriBSpline.h" -#include "mri_transform.h" #include "pdf.h" #include "proto.h" #include "randomfields.h" @@ -1325,7 +1323,7 @@ int MRIsetVoxVal(MRI *mri, int c, int r, int s, int f, float voxval) MRIinterpCode() - returns the numeric interpolation code given the name of the interpolation method. -----------------------------------------------------------------*/ -int MRIinterpCode(char *InterpString) +int MRIinterpCode(const char *InterpString) { if (!strncasecmp(InterpString, "nearest", 3)) return (SAMPLE_NEAREST); if (!strncasecmp(InterpString, "trilinear", 3)) return (SAMPLE_TRILINEAR); @@ -1340,7 +1338,7 @@ int MRIinterpCode(char *InterpString) MRIinterpString() - returns the the name of the interpolation method given numeric interpolation code -----------------------------------------------------------------*/ -char *MRIinterpString(int InterpCode) +const char *MRIinterpString(int InterpCode) { switch (InterpCode) { case SAMPLE_NEAREST: @@ -1363,7 +1361,7 @@ char *MRIinterpString(int InterpCode) name of the precision. This corresponds to the value of the type field in the MRI structure. -----------------------------------------------------------------*/ -int MRIprecisionCode(char *PrecisionString) +int MRIprecisionCode(const char *PrecisionString) { if (!strcasecmp(PrecisionString, "uchar")) return (MRI_UCHAR); if (!strcasecmp(PrecisionString, "short")) return (MRI_SHORT); @@ -1379,7 +1377,7 @@ int MRIprecisionCode(char *PrecisionString) numeric precision code. The code corresponds to the value of the type field in the MRI structure. -----------------------------------------------------------------*/ -char *MRIprecisionString(int PrecisionCode) +const char *MRIprecisionString(int PrecisionCode) { switch (PrecisionCode) { case MRI_UCHAR: @@ -1950,7 +1948,7 @@ MRI *MRIvalScale(MRI *mri_src, MRI *mri_dst, float flo, float fhi) MRI *MRIconfThresh( MRI *mri_src, MRI *mri_probs, MRI *mri_classes, MRI *mri_dst, float thresh, int min_target, int max_target) { - int x, y, z, width, height, depth, class; + int x, y, z, width, height, depth, classnum; float *pprobs, prob; BUFTYPE *pclasses, *pdst, *psrc, src; @@ -1969,10 +1967,10 @@ MRI *MRIconfThresh( for (x = 0; x < width; x++) { src = *psrc++; prob = *pprobs++; - class = (int)*pclasses++; - if (prob >= thresh && ((class >= min_target) && (class <= max_target))) + classnum = (int)*pclasses++; + if (prob >= thresh && ((classnum >= min_target) && (classnum <= max_target))) *pdst++ = src; - else if ((class >= min_target) && (class <= max_target)) + else if ((classnum >= min_target) && (classnum <= max_target)) *pdst++ = 25; else *pdst++ = 0; @@ -5510,7 +5508,7 @@ MRI *MRIallocChunk(int width, int height, int depth, int type, int nframes) /* Instead of allocating each row, just point to the correct location in the chunk. */ for (row = 0; row < mri->height; row++) { - mri->slices[slice][row] = p; + mri->slices[slice][row] = (unsigned char *)p; p += mri->bytes_per_row; } } @@ -15129,7 +15127,7 @@ float MRIfovCol(MRI *mri) get the direction cosines "about right". --------------------------------------------------------------------*/ -int MRIorientationStringToDircos(MRI *mri, char *ostr) +int MRIorientationStringToDircos(MRI *mri, const char *ostr) { int c, r = 0; double Mdc[3][3], v = 0; @@ -15201,7 +15199,7 @@ int MRIorientationStringToDircos(MRI *mri, char *ostr) ok, otherwise is returns a string that lists all the errors it encountered. ---------------------------------------------------------------*/ -char *MRIcheckOrientationString(char *ostr) +char *MRIcheckOrientationString(const char *ostr) { int c, nsag = 0, ncor = 0, nax = 0, err; char errstr[1000], *errstrret = NULL; @@ -15340,7 +15338,7 @@ int MRIdircosToOrientationString(MRI *mri, char *ostr) char *MRIsliceDirectionName(MRI *mri) { char ostr[4]; - char *slicedir = NULL; + const char *slicedir = NULL; char *rtstr; int len; diff --git a/utils/mri2.c b/utils/mri2.cpp similarity index 99% rename from utils/mri2.c rename to utils/mri2.cpp index 92791d22e8c..e9cf32ed94a 100644 --- a/utils/mri2.c +++ b/utils/mri2.cpp @@ -385,7 +385,7 @@ int mri_framepower(MRI *vol, float *framepower) number of voxels in vol that meet the threshold criteria (ie, the number of 1's in volbin). -----------------------------------------------------------------*/ -MRI *mri_binarize(MRI *vol, float thresh, char *tail, int invert, MRI *volbin, int *nover) +MRI *mri_binarize(MRI *vol, float thresh, const char *tail, int invert, MRI *volbin, int *nover) { int r, c, s, f, tailcode; float val; @@ -2806,9 +2806,9 @@ double *MRIsegDice(MRI *seg1, MRI *seg2, int *nsegs, int **segidlist) /* ----------------------------------------------------------*/ /*! - \fn MRI *MRIsegDiff(MRI *old, MRI *new, int *DiffFlag) - \brief Determines differences between old and new segmentation. - Voxels that are different will take the value of the new + \fn MRI *MRIsegDiff(MRI *old, MRI *curr, int *DiffFlag) + \brief Determines differences between old and curr segmentation. + Voxels that are different will take the value of the curr segmentation. Voxels that are NOT different will take the value of VOXEL_UNCHANGED (defined as 256 in cma.h and LUT.txt). This allows the diff to be loaded as a segmentation in tkmedit. @@ -2816,21 +2816,21 @@ double *MRIsegDice(MRI *seg1, MRI *seg2, int *nsegs, int **segidlist) Note that if there is no difference, all voxels will have the value of VOXEL_UNCHANGED. See also MRIsegMergeDiff(). */ -MRI *MRIsegDiff(MRI *old, MRI *new, int *DiffFlag) +MRI *MRIsegDiff(MRI *old, MRI *curr, int *DiffFlag) { MRI *diff; int c, r, s; int vold, vnew, vdiff; - diff = MRIallocSequence(new->width, new->height, new->depth, MRI_INT, 1); - MRIcopyHeader(new, diff); + diff = MRIallocSequence(curr->width, curr->height, curr->depth, MRI_INT, 1); + MRIcopyHeader(curr, diff); *DiffFlag = 0; - for (c = 0; c < new->width; c++) { - for (r = 0; r < new->height; r++) { - for (s = 0; s < new->depth; s++) { + for (c = 0; c < curr->width; c++) { + for (r = 0; r < curr->height; r++) { + for (s = 0; s < curr->depth; s++) { vold = MRIgetVoxVal(old, c, r, s, 0); - vnew = MRIgetVoxVal(new, c, r, s, 0); + vnew = MRIgetVoxVal(curr, c, r, s, 0); if (vold == vnew) vdiff = VOXEL_UNCHANGED; else { @@ -2856,28 +2856,28 @@ MRI *MRIsegDiff(MRI *old, MRI *new, int *DiffFlag) */ MRI *MRIsegMergeDiff(MRI *old, MRI *diff) { - MRI *new; + MRI *curr; int c, r, s; int vold, vdiff, vnew; - new = MRIallocSequence(old->width, old->height, old->depth, MRI_INT, 1); - MRIcopyHeader(old, new); + curr = MRIallocSequence(old->width, old->height, old->depth, MRI_INT, 1); + MRIcopyHeader(old, curr); - for (c = 0; c < new->width; c++) { - for (r = 0; r < new->height; r++) { - for (s = 0; s < new->depth; s++) { + for (c = 0; c < curr->width; c++) { + for (r = 0; r < curr->height; r++) { + for (s = 0; s < curr->depth; s++) { vold = MRIgetVoxVal(old, c, r, s, 0); vdiff = MRIgetVoxVal(diff, c, r, s, 0); if (vdiff == VOXEL_UNCHANGED) vnew = vold; else vnew = MRIgetVoxVal(diff, c, r, s, 0); - MRIsetVoxVal(new, c, r, s, 0, vnew); + MRIsetVoxVal(curr, c, r, s, 0, vnew); } } } - return (new); + return (curr); } /* ----------------------------------------------------------*/ diff --git a/utils/mriBSpline.c b/utils/mriBSpline.cpp similarity index 99% rename from utils/mriBSpline.c rename to utils/mriBSpline.cpp index 896633c9ae8..498962a1223 100644 --- a/utils/mriBSpline.c +++ b/utils/mriBSpline.cpp @@ -1355,7 +1355,7 @@ static void PyramidFilterCenteredL2(double g[], long *ng, double h[], long *nh, FALSE if it is not a centered filter ---------------------------------------------------------------------------- */ -static int GetPyramidFilter(char *Filter, long Order, double g[], long *ng, double h[], long *nh, short *IsCentered) +static int GetPyramidFilter(const char *Filter, long Order, double g[], long *ng, double h[], long *nh, short *IsCentered) { ng[0] = -1L; nh[0] = -1L; diff --git a/utils/mriFunctionalDataAccess.c b/utils/mriFunctionalDataAccess.c deleted file mode 100644 index cf7efa75830..00000000000 --- a/utils/mriFunctionalDataAccess.c +++ /dev/null @@ -1,2878 +0,0 @@ -/** - * @file mriFunctionalDataAccess.c - * @brief fmri utils - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: greve $ - * $Date: 2016/01/07 22:23:57 $ - * $Revision: 1.58 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "mriFunctionalDataAccess.h" -#include -#include -#include -#include -#include -#include "error.h" -#include "machine.h" -#include "macros.h" -#include "matrix.h" -#include "mri2.h" -#include "mri_identify.h" -#include "stats.h" -#include "xDebug.h" -#include "xUtilities.h" -#include "xVoxel.h" - -#ifndef min -#define min(x, y) (x < y ? x : y) -#endif - -#ifndef max -#define max(x, y) (x > y ? x : y) -#endif - -#define KEEP_NULL_CONDITION 1 - -#define FunD_ksStemHeaderSuffix "dat" -#define FunD_ksRegisterFileName "register.dat" - -char *FunD_ksaErrorString[FunD_tErr_knNumErrorCodes] = {"No error.", - "Invalid object signature.", - "Invalid ptr to volume (was probably NULL).", - "Path not found.", - "No stem provided and it couldn't be guessed.", - "Data not found in specified path.", - "Header file not found in specified path.", - "Couldn't allocate volume (memory allocation failed).", - "Unrecognized header format.", - "Questionable header format (found expected types of values, " - "but keywords were different).", - "Couldn't find a recognizable data file.", - "Couldn't allocate storage (memory allocation failed).", - "Couldn't allocate MRI.", - "Couldn't allocate matrix (not my fault).", - "Couldn't load MRI volume.", - "Couldn't read register file.", - "Couldn't calculate deviations.", - "Error performing an operation on a transform.", - "Invalid parameter", - "Invalid time resolution, number of time points must be " - "evenly divisble by it.", - "Invalid number of pre stim time points.", - "Invalid functional voxel, out of bounds.", - "Invalid condition (is it zero-based?)", - "Invalid time point (is it zero-based?)", - "Couldn't transform mask into local space.", - "Error performing FDR.", - "Invalid error code."}; - -// ===================================================================== VOLUME - -FunD_tErr FunD_New(mriFunctionalDataRef *opVolume, - char *isFileName, - FunD_tRegistrationType iRegistrationType, - char *isRegistrationFileName, - int inScalarSize, - mriVolumeRef iAnatomicalVolume, - tBoolean ibIsLeftHemisphere) -{ - mriFunctionalDataRef this = NULL; - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction( - ("FunD_New( opVolume=%p, isFileName=%s, " - "iRegistrationType=%d, isRegistrationFileName=%s, " - "inScalarSize=%d, iAnatomicalVolume=%p)", - opVolume, - isFileName, - iRegistrationType, - isRegistrationFileName, - inScalarSize, - iAnatomicalVolume)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != opVolume && NULL != isFileName), eResult, FunD_tErr_InvalidParameter); - - /* Allocate the storage */ - DebugNote(("Allocating mriFunctionalData")); - this = (mriFunctionalDataRef)malloc(sizeof(mriFunctionalData)); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_CouldntAllocateVolume); - - this->mSignature = FunD_kSignature; - - /* Save registration name. If we didn't get one, build one out of - the base path of the file name. */ - DebugNote(("Saving file name")); - strcpy(this->msFileName, isFileName); - if (NULL != isRegistrationFileName) { - DebugNote(("Saving registration file name")); - strcpy(this->msRegistrationFileName, isRegistrationFileName); - } - else { - strcpy(this->msRegistrationFileName, ""); - } - - /* Init values. */ - this->mSampleType = FunD_tSampleType_Nearest; - this->mConvMethod = FunD_tConversionMethod_FFF; - this->mNumTimePoints = -1; - this->mNumConditions = -1; - this->mbNullConditionPresent = FALSE; - this->mpData = NULL; - this->mMinValue = 10000; - this->mMaxValue = -10000; - this->mTimeResolution = 0; - this->mNumPreStimTimePoints = 0; - this->mIdxToIdxTransform = NULL; - this->mOriginalIdxToIdxTransform = NULL; - this->mbErrorDataPresent = FALSE; - this->mCovMtx = NULL; - this->mpResampledData = NULL; - this->mClientXMin = 0; - this->mClientYMin = 0; - this->mClientZMin = 0; - this->mClientXMax = -1; - this->mClientYMax = -1; - this->mClientZMax = -1; - this->mbHaveClientBounds = FALSE; - this->mbScalar = FALSE; - - this->mFrequencies = NULL; - this->mNumBins = 0; - - /* Init transform objects */ - DebugNote(("Creating idx to idx transform")); - Trns_New(&(this->mIdxToIdxTransform)); - - /* Load the data.*/ - this->mpData = MRIread(this->msFileName); - DebugAssertThrowX((NULL != this->mpData), eResult, FunD_tErr_CouldntReadMRI); - - /* Try to parse a stem header if we have a stem specified. */ - DebugNote(("Trying stem header")); - eResult = FunD_FindAndParseStemHeader_(this); - if (FunD_tErr_NoError != eResult) { - DebugNote(("Guess meta information")); - eResult = FunD_GuessMetaInformation_(this); - } - - /* Try to reshape if we can. */ - if (inScalarSize > 0) { - DebugNote(("Trying reshape with %d values", inScalarSize)); - FunD_ReshapeIfScalar_(this, inScalarSize, NULL, ibIsLeftHemisphere); - } - - /* If we're not scalar by now, parse the registration file */ - if (!this->mbScalar) { - DebugNote(("Parsing registration file")); - eResult = FunD_ParseRegistrationAndInitMatricies_(this, iRegistrationType, iAnatomicalVolume); - DebugAssertThrow((FunD_tErr_NoError == eResult)); - } - - FunD_DebugPrint(this); - - /* Get the value range. */ - DebugNote(("Getting value range")); - MRIvalRange(this->mpData, &this->mMinValue, &this->mMaxValue); - - /* return what we got */ - *opVolume = this; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - - /* delete data if no good */ - if (NULL != this) { - free(this); - this = NULL; - } - - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_Delete(mriFunctionalDataRef *iopVolume) -{ - FunD_tErr eResult = FunD_tErr_NoError; - mriFunctionalDataRef this = NULL; - int column = 0; - - DebugEnterFunction(("FunD_Delete( iopVolume=%p )", iopVolume)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != iopVolume), eResult, FunD_tErr_InvalidParameter); - - /* Get the object. */ - this = *iopVolume; - - /* Make sure we're valid. */ - eResult = FunD_Verify(this); - DebugAssertThrow((FunD_tErr_NoError == eResult)); - - /* mangle our signature */ - this->mSignature = 0x1; - - /* Delete other data. */ - if (NULL != this->mpData) { - MRIfree(&this->mpData); - } - if (NULL != this->mCovMtx) { - for (column = 0; column < (this->mNumConditions - 1) * this->mNumTimePoints; column++) { - free(this->mCovMtx[column]); - } - free(this->mCovMtx); - } - - /* delete our transformers. */ - if (NULL != this->mIdxToIdxTransform) { - Trns_Delete(&(this->mIdxToIdxTransform)); - } - if (NULL != this->mOriginalIdxToIdxTransform) { - Trns_Delete(&(this->mOriginalIdxToIdxTransform)); - } - - /* delete the structure. */ - free(this); - - *iopVolume = NULL; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ReshapeIfScalar_(mriFunctionalDataRef this, - int inNumValues, - tBoolean *obReshaped, - tBoolean ibIsLeftHemisphere) -{ - FunD_tErr eResult = FunD_tErr_NoError; - MRI *reshapedVolume = NULL; - - DebugEnterFunction( - ("FunD_ReshapeIfScalar_( this=%p, inNumValues=%d, " - "obReshaped=%p )", - this, - inNumValues, - obReshaped)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((inNumValues > 0), eResult, FunD_tErr_InvalidParameter); - - if (this->mpData->width * this->mpData->height * this->mpData->depth == 2 * inNumValues) { - MRI *mri_tmp, *mri_tmp2; - this->mbScalar = 1; - if (ibIsLeftHemisphere) { - mri_tmp = MRIextractInto( - this->mpData, NULL, 0, 0, 0, this->mpData->width / 2, this->mpData->height, this->mpData->depth, 0, 0, 0); - mri_tmp2 = MRIcopyFrames(mri_tmp, NULL, 0, inNumValues - 1, 0); - } - else { - mri_tmp = MRIextractInto(this->mpData, - NULL, - 0, - 0, - 0, - this->mpData->width / 2, - this->mpData->height, - this->mpData->depth, - inNumValues, - 0, - 0); - mri_tmp2 = MRIcopyFrames(mri_tmp, NULL, inNumValues, 2 * inNumValues - 1, 0); - } - MRIfree(&mri_tmp); - MRIfree(&this->mpData); - this->mpData = mri_tmp2; - } - - if (this->mpData->width * this->mpData->height * this->mpData->depth == inNumValues) { - /* Reshape it so that everything is in the x direction. */ - DebugNote(("Calling mri_reshape")); - reshapedVolume = mri_reshape(this->mpData, inNumValues, 1, 1, this->mpData->nframes); - DebugAssertThrowX((NULL != reshapedVolume), eResult, FunD_tErr_CouldntAllocateVolume); - - DebugNote(("Freeing current data")); - MRIfree(&this->mpData); - this->mpData = reshapedVolume; - reshapedVolume = NULL; - - /* If we're scalar, we don't use a registration or transform. */ - this->mbScalar = TRUE; - } - - if (NULL != obReshaped) { - DebugNote(("Returning whether it was reshaped")); - *obReshaped = this->mbScalar = TRUE; - } - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - - if (NULL != reshapedVolume) { - DebugNote(("Freeing reshaped volume")); - MRIfree(&reshapedVolume); - } - - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_FindAndParseStemHeader_(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - tBoolean bFoundFile = FALSE; - char sFileName[FunD_knPathLen] = "", *ptmp; - float fPreStimSecs = 0; - FILE *pHeader = NULL; - tBoolean bGood = FALSE; - tBoolean bSomethingRead = FALSE; - char sKeyword[256] = ""; - int nNumValues = 0; - int nCovMtxCol = 0; - int nCovMtxRow = 0; - int nValue = 0; - int nValuesRead = 0; - - if (getenv("USEDNGDRAW")) { - printf("FunD_FindAndParseStemHeader_ msFileName %s\n", this->msFileName); - printf("Using dng draw %s\n", getenv("USEDNGDRAW")); - fflush(stdout); - this->mNumConditions = CountItemsInString(getenv("USEDNGDRAW")) + 1; - printf("Using dng draw nc=%d\n", this->mNumConditions - 1); - fflush(stdout); - bFoundFile = FALSE; - eResult = FunD_tErr_NoError; - // DebugAssertQuietThrowX( (bFoundFile), eResult, FunD_tErr_HeaderNotFound ); - // Cant have overlay and plot at the same time! - return (FunD_tErr_NoError); - } - - DebugEnterFunction(("FunD_FindAndParseStemHeader_( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - // Get the name of any .dat file - ptmp = IDstemFromName(this->msFileName); - sprintf(sFileName, "%s.dat", ptmp); - free(ptmp); - /* Try to open it. */ - printf("tkmedit: Trying to open %s\n", sFileName); - DebugNote(("Trying to open %s", sFileName)); - pHeader = fopen(sFileName, "r"); - if (NULL != pHeader) { - fclose(pHeader); - bFoundFile = TRUE; - } - /* Bail if no file. */ - DebugAssertQuietThrowX((bFoundFile), eResult, FunD_tErr_HeaderNotFound); - - /* Try to open the file. */ - pHeader = fopen(sFileName, "r"); - - /* Start scanning for keywords... We use bSomethingRead to keep - track if recognized a keyword and tried to read something. Since - we are happy to skip unrecognized lines, we could have a totally - random .dat file there that we would skip over and not get any - valid meta information. So if end up going through the file and - not recognizing anything, we want to bail. This will be the case - is bSomethingRead is still false at the end of the reading. */ - bSomethingRead = FALSE; - while (!feof(pHeader)) { - /* grab a keyword */ - DebugNote(("Reading a keyword")); - nValuesRead = fscanf(pHeader, "%s", sKeyword); - if (feof(pHeader)) { - break; - } - DebugAssertThrowX((1 == nValuesRead && !feof(pHeader)), eResult, FunD_tErr_UnrecognizedHeaderFormat); - - /* assume success */ - bGood = TRUE; - - /* look at the keyword */ - if (strcmp(sKeyword, "TER") == 0) { - DebugNote(("Reading TER")); - nValuesRead = fscanf(pHeader, "%f", &this->mTimeResolution); - bGood = (1 == nValuesRead); - bSomethingRead = TRUE; - } - else if (strcmp(sKeyword, "TPreStim") == 0) { - DebugNote(("Reading TPreStim")); - nValuesRead = fscanf(pHeader, "%f", &fPreStimSecs); - bGood = (1 == nValuesRead); - bSomethingRead = TRUE; - } - else if (strcmp(sKeyword, "nCond") == 0) { - DebugNote(("Reading nCond")); - nValuesRead = fscanf(pHeader, "%d", &this->mNumConditions); - bGood = (1 == nValuesRead); - this->mbNullConditionPresent = TRUE; - bSomethingRead = TRUE; - } - else if (strcmp(sKeyword, "Nh") == 0) { - DebugNote(("Reading Nh")); - nValuesRead = fscanf(pHeader, "%d", &this->mNumTimePoints); - bGood = (1 == nValuesRead); - bSomethingRead = TRUE; - } - else if (strcmp(sKeyword, "SumXtX") == 0) { - DebugNote(("Reading SumXtX")); - nNumValues = pow(this->mNumTimePoints * (this->mNumConditions - 1), 2); - for (nValue = 0; nValue < nNumValues; nValue++) { - if (fscanf(pHeader, "%*d") != 0) { - DebugNote(("Reading variable failed")); - } - } - bSomethingRead = TRUE; - } - else if (strcmp(sKeyword, "hCovMtx") == 0) { - /* Allocate the covariance matrix. It's the size of the number - of time points times conditions (minus null condition) on both - sides. */ - DebugNote(("Allocating cov mtx")); - this->mCovMtx = (float **)calloc(this->mNumTimePoints * (this->mNumConditions - 1), sizeof(float *)); - DebugAssertThrowX((NULL != this->mCovMtx), eResult, FunD_tErr_CouldntAllocateStorage); - - /* The cov mtx doesn't have values for the null condition, so we - start with 1 instead of 0 in our loops here, and use that-1. */ - for (nCovMtxRow = 0; nCovMtxRow < this->mNumTimePoints * (this->mNumConditions - 1); nCovMtxRow++) { - DebugNote(("Allocating cov mtx col %d", nCovMtxCol)); - this->mCovMtx[nCovMtxRow] = (float *)calloc(this->mNumTimePoints * (this->mNumConditions - 1), sizeof(float *)); - DebugAssertThrowX((NULL != this->mCovMtx), eResult, FunD_tErr_CouldntAllocateStorage); - - for (nCovMtxCol = 0; nCovMtxCol < this->mNumTimePoints * (this->mNumConditions - 1); nCovMtxCol++) { - DebugNote(("Reading cov mtx value %d, %d", nCovMtxCol, nCovMtxRow)); - nValuesRead = fscanf(pHeader, "%f", &this->mCovMtx[nCovMtxRow][nCovMtxCol]); - bGood = (1 == nValuesRead); - DebugAssertThrowX((bGood), eResult, FunD_tErr_UnrecognizedHeaderFormat); - } - } - bSomethingRead = TRUE; - } - - DebugAssertThrowX((bGood), eResult, FunD_tErr_UnrecognizedHeaderFormat); - } - - /* If nothing was read, this isn't a real .dat file, so bail. */ - DebugAssertThrowX((bSomethingRead), eResult, FunD_tErr_UnrecognizedHeaderFormat); - - /* Divide the num prestim points by the time res. Do it here because - we might not have gotten the timeres when we read TPreStim up - there. */ - this->mNumPreStimTimePoints = fPreStimSecs / this->mTimeResolution; - - /* In this format we have error data. */ - this->mbErrorDataPresent = TRUE; - - DebugCatch; - - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - DebugPrint(("Last parsed keyword: '%s' nValuesRead=%d\n", sKeyword, nValuesRead)); - EndDebugCatch; - - if (NULL != pHeader) { - fclose(pHeader); - } - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GuessMetaInformation_(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_GuessMetaInformation_( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - /* Set default values from MRI info. Just one condition, with all - frames being time points, and no error data. */ - this->mTimeResolution = 1.0; - this->mNumConditions = 1; - this->mNumTimePoints = this->mpData->nframes; - this->mNumPreStimTimePoints = 0; - this->mbErrorDataPresent = FALSE; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ParseRegistrationAndInitMatricies_(mriFunctionalDataRef this, - FunD_tRegistrationType iType, - mriVolumeRef iAnatomicalVolume) -{ - FunD_tErr eResult = FunD_tErr_NoError; - char sBasePath[1024] = ""; - char sFileName[1024] = ""; - struct stat fileInfo; - int eStat = 0; - char *pCurChar = NULL; - char *pBaseEnd = NULL; - fMRI_REG *theRegInfo = NULL; - FILE *fRegister = NULL; - char sLine[1024] = ""; - char sKeyWord[1024] = ""; - tBoolean bGood = FALSE; - FunD_tConversionMethod convMethod = FunD_tConversionMethod_FCF; - int eMRI = ERROR_NONE; - - DebugEnterFunction(("FunD_ParseRegistrationAndInitMatricies_( this=%p )", this)); - - DebugNote(("Checking this")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking registration type")); - DebugAssertThrowX((iType >= 0 && iType < FunD_knNumRegistrationTypes), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking iAnatomicalVolume")); - DebugAssertThrowX((NULL != iAnatomicalVolume), eResult, FunD_tErr_InvalidParameter); - - /* Switch on the registration type. We'll need to get some info out - of the registration file if they specified one, or generate some - default info. */ - switch (iType) { - /* These both try to load files, so we'll share some code. */ - case FunD_tRegistration_File: - case FunD_tRegistration_Find: - - /* If we need to find a file, look for it now. */ - if (FunD_tRegistration_Find == iType) { - /* Construct a registration name based on our data location and - try to open that. If we didn't find one, return an error. - Start by finding the last slash in the data file name. */ - DebugNote(("Looking for last slash")); - xUtil_strncpy(sBasePath, this->msFileName, sizeof(sBasePath)); - pCurChar = sBasePath; - while (NULL != pCurChar && *pCurChar != '\0') { - if ('/' == *pCurChar) { - pBaseEnd = pCurChar; - } - pCurChar++; - } - - /* Set this to null char, terminating the string. Then use this - string and the header suffix to build the header file name. */ - *pBaseEnd = '\0'; - xUtil_snprintf(sFileName, sizeof(sFileName), "%s/%s", sBasePath, FunD_ksRegisterFileName); - - /* Save the file name we found. */ - strncpy(this->msRegistrationFileName, sFileName, sizeof(this->msRegistrationFileName)); - } - - /* See if the file exists and is a regular file. */ - DebugNote(("Checking if %s exists", this->msRegistrationFileName)); - eStat = stat(this->msRegistrationFileName, &fileInfo); - DebugAssertThrowX((0 == eStat), eResult, FunD_tErr_CouldntReadRegisterFile); - - DebugNote(("Checking S_ISREG")); - DebugAssertThrowX((S_ISREG(fileInfo.st_mode)), eResult, FunD_tErr_CouldntReadRegisterFile); - - /* Read the registration info. */ - DebugNote(("StatReadRegistration on %s\n", this->msRegistrationFileName)); - theRegInfo = StatReadRegistration(this->msRegistrationFileName); - DebugAssertThrowX((NULL != theRegInfo), eResult, FunD_tErr_CouldntReadRegisterFile); - - /* Grab the brightness scale from it. */ - this->mBrightnessScale = theRegInfo->brightness_scale; - strcpy(this->msSubjectName, theRegInfo->name); - - /* If the ps and thickness from our volume does not match the ps and - thickness in the registration file, complain */ - if (!FEQUAL(this->mpData->xsize, theRegInfo->in_plane_res) || - !FEQUAL(this->mpData->zsize, theRegInfo->slice_thickness)) { - DebugPrint( - ("\tWARNING: MRI xsize and zsize are not equal to " - "reginfo in_plane_res and slice_thickness:\n" - "\t MRI: xsize = %f zsize = %f\n" - "\treginfo: in_plane_res = %f slice_thickness = %f\n", - this->mpData->xsize, - this->mpData->zsize, - theRegInfo->in_plane_res, - theRegInfo->slice_thickness)); - } - - /* Get rid of the registration info. */ - StatFreeRegistration(&theRegInfo); - - /* At this point we scan thru the register file looking for a line - with a registration keyword on it. This will specify our - conversion method. If nothing is found, tkregister will be - used. */ - DebugNote(("Opening this->msRegistrationFileName")); - fRegister = fopen(this->msRegistrationFileName, "r"); - DebugAssertThrowX((NULL != theRegInfo), eResult, FunD_tErr_CouldntReadRegisterFile); - - /* Start with our default of FCF. */ - convMethod = FunD_tConversionMethod_FCF; - - DebugNote(("Looking for conversion keyword")); - while (!feof(fRegister)) { - /* read line and look for string */ - if (!fgets(sLine, 1024, fRegister) && ferror(fRegister)) { - break; - } - if (feof(fRegister)) { - break; - } - bGood = sscanf(sLine, "%s", sKeyWord); - if (bGood) { - if (strcmp(sKeyWord, FunD_ksConversionMethod_FCF) == 0) { - convMethod = FunD_tConversionMethod_FCF; - } - if (strcmp(sKeyWord, FunD_ksConversionMethod_FFF) == 0) { - convMethod = FunD_tConversionMethod_FFF; - } - if (strcmp(sKeyWord, FunD_ksConversionMethod_Round) == 0) { - convMethod = FunD_tConversionMethod_Round; - } - } - } - - /* Close the register file. */ - fclose(fRegister); - - break; - - case FunD_tRegistration_Identity: - - /* Default values here. */ - this->mBrightnessScale = 1.0; - strcpy(this->msSubjectName, ""); - convMethod = FunD_tConversionMethod_FCF; - - break; - default: - break; - } - - /* Generate our anatomical index -> functional index transform */ - DebugNote(("Calling MRImakeVox2VoxReg")); - eMRI = MRImakeVox2VoxReg(iAnatomicalVolume->mpMriValues, - this->mpData, - (int)iType, - this->msRegistrationFileName, - &this->mIdxToIdxTransform); - DebugAssertThrowX((ERROR_NONE == eMRI), eResult, FunD_tErr_CouldntReadRegisterFile); - - /* Save the registration. */ - Trns_DeepClone(this->mIdxToIdxTransform, &this->mOriginalIdxToIdxTransform); - - /* Set the conversion method. */ - FunD_SetConversionMethod(this, convMethod); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_RestoreRegistration(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_RestoreRegistration( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugAssertThrowX((NULL != this->mOriginalIdxToIdxTransform), eResult, FunD_tErr_ErrorAccessingTransform); - - /* Delete the matrix and clone the backup. */ - Trns_Delete(&this->mIdxToIdxTransform); - Trns_DeepClone(this->mOriginalIdxToIdxTransform, &this->mIdxToIdxTransform); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_SetClientCoordBounds( - mriFunctionalDataRef this, int inXMin, int inYMin, int inZMin, int inXMax, int inYMax, int inZMax) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction( - ("FunD_SetClientCoordBounds( this=%p, inXMin=%d, " - "inYMin=%d, inZMin=%d, inXMax=%d, inYMax=%d, inZMax=%d )", - this, - inXMin, - inYMin, - inZMin, - inXMax, - inYMax, - inZMax)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking max > min")); - DebugAssertThrowX((inXMax >= inXMin && inYMax >= inYMin && inZMax >= inZMin), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Set the bounds. */ - this->mClientXMin = inXMin; - this->mClientYMin = inYMin; - this->mClientZMin = inZMin; - this->mClientXMax = inXMax; - this->mClientYMax = inYMax; - this->mClientZMax = inZMax; - this->mbHaveClientBounds = TRUE; - - /* Generate the resampled volume. */ - FunD_ResampleData_(this); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_SetConversionMethod(mriFunctionalDataRef this, FunD_tConversionMethod iMethod) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_SetConversionMethod( this=%p, iMethod=%d )", this, iMethod)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((iMethod >= 0 && iMethod < FunD_knNumConversionMethods), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Set the method. */ - this->mConvMethod = iMethod; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetSampleType(mriFunctionalDataRef this, FunD_tSampleType *oType) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction( - ("FunD_GetSampleType( this=%p, " - "oType=%p )", - this, - oType)); - - DebugNote(("Verifying volume")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((oType != NULL), eResult, FunD_tErr_InvalidParameter); - - /* return the type */ - DebugNote(("Returning the type")); - *oType = this->mSampleType; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_SetSampleType(mriFunctionalDataRef this, FunD_tSampleType iType) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_SetSampleType( this=%p, iType=%d )", this, (int)iType)); - - DebugNote(("Verifying volume")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iType >= 0 && iType < FunD_knNumSampleTypes), eResult, FunD_tErr_InvalidParameter); - - /* Set the sample type. */ - this->mSampleType = iType; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ClientSpaceIsTkRegRAS(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - MATRIX *identity = NULL; - Trns_tErr eTrns = Trns_tErr_NoErr; - - DebugEnterFunction(("FunD_ClientSpaceIsTkRegRAS( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Set the A->RAS part of the transform to identity. */ - DebugNote(("Checking if mIdxToIdxTransform exists")); - DebugAssertThrowX((NULL != this->mIdxToIdxTransform), eResult, FunD_tErr_ErrorAccessingTransform); - - DebugNote(("Creating identity matrix")); - identity = MatrixIdentity(4, NULL); - DebugAssertThrowX((NULL != identity), eResult, FunD_tErr_CouldntAllocateMatrix); - - DebugNote(("Copying in transform")); - eTrns = Trns_CopyAtoRAS(this->mIdxToIdxTransform, identity); - DebugAssertThrowX((Trns_tErr_NoErr == eTrns), eResult, FunD_tErr_ErrorAccessingTransform); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - if (NULL != identity) { - MatrixFree(&identity); - } - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_IsScalar(mriFunctionalDataRef this, tBoolean *obScalar) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_IsScalar( this=%p, obScalar=%p )", this, obScalar)); - - DebugNote(("Verifying volume")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((obScalar != NULL), eResult, FunD_tErr_InvalidParameter); - - /* return the value */ - DebugNote(("Returning the scalar flag")); - *obScalar = this->mbScalar; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -/* NOTE: I removed all the DebugEnter/ExitFunction and DebugNote calls - because they make this call much slower. I wish there was a better - way to do this. - RKT */ -#define BE_SUPA_FAST - -FunD_tErr FunD_GetData(mriFunctionalDataRef this, xVoxelRef iClientVox, int iCondition, int iTimePoint, float *oValue) -{ - FunD_tErr eResult = FunD_tErr_NoError; - xVoxel funcIdx; - float fValue = 0; - -#ifndef BE_SUPA_FAST - DebugEnterFunction( - ("FunD_GetData( this=%p, iClientVox=%p, " - "iCondition=%d, iTimePoint=%d, oValue=%p)", - this, - iClientVox, - iCondition, - iTimePoint, - oValue)); -#endif - -#ifndef BE_SUPA_FAST - DebugNote(("Checking parameters")); -#endif - DebugAssertThrowX((NULL != this && NULL != iClientVox && NULL != oValue), eResult, FunD_tErr_InvalidParameter); -#ifndef BE_SUPA_FAST - DebugNote(("Checking condition")); -#endif - DebugAssertThrowX((iCondition >= 0 && iCondition < this->mNumConditions), eResult, FunD_tErr_InvalidParameter); -#ifndef BE_SUPA_FAST - DebugNote(("Checking time point")); -#endif - DebugAssertThrowX((iTimePoint >= 0 && iTimePoint < this->mNumTimePoints), eResult, FunD_tErr_InvalidParameter); - -#ifndef BE_SUPA_FAST - DebugNote(("Verifying object")); -#endif - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - if (!this->mbScalar) { -#ifndef BE_SUPA_FAST - DebugNote(("Converting client to func idx")); -#endif - FunD_ConvertClientToFloatFuncIdx_(this, iClientVox, &funcIdx); - } - else { - xVoxl_Copy(&funcIdx, iClientVox); - } - -#ifndef BE_SUPA_FAST - DebugNote(("Verifying func idx")); -#endif - eResult = FunD_VerifyFuncIdx_(this, &funcIdx); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - -#ifndef BE_SUPA_FAST - DebugNote(("Getting value")); -#endif - FunD_GetValue_(this, this->mpData, &funcIdx, iCondition, iTimePoint, &fValue); - -#ifndef BE_SUPA_FAST - DebugNote(("Setting return value")); -#endif - *oValue = fValue; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - -#ifndef BE_SUPA_FAST - DebugExitFunction; -#endif - - return eResult; -} - -FunD_tErr FunD_GetSampledData( - mriFunctionalDataRef this, xVoxelRef iClientVox, int iCondition, int iTimePoint, float *oValue) -{ - FunD_tErr eResult = FunD_tErr_NoError; - xVoxel funcIdx; - float fValue = 0; - -#ifndef BE_SUPA_FAST - DebugEnterFunction( - ("FunD_GetSampledData( this=%p, iClientVox=%p, " - "iCondition=%d, iTimePoint=%d, oValue=%p)", - this, - iClientVox, - iCondition, - iTimePoint, - oValue)); -#endif - -#ifndef BE_SUPA_FAST - DebugNote(("Checking parameters")); -#endif - DebugAssertThrowX((NULL != this && NULL != iClientVox && NULL != oValue), eResult, FunD_tErr_InvalidParameter); -#ifndef BE_SUPA_FAST - DebugNote(("Checking condition")); -#endif - DebugAssertThrowX((iCondition >= 0 && iCondition < this->mNumConditions), eResult, FunD_tErr_InvalidParameter); -#ifndef BE_SUPA_FAST - DebugNote(("Checking time point")); -#endif - DebugAssertThrowX((iTimePoint >= 0 && iTimePoint < this->mNumTimePoints), eResult, FunD_tErr_InvalidParameter); - -#ifndef BE_SUPA_FAST - DebugNote(("Verifying object")); -#endif - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - if (!this->mbScalar) { -#ifndef BE_SUPA_FAST - DebugNote(("Converting client to func idx")); -#endif - FunD_ConvertClientToFloatFuncIdx_(this, iClientVox, &funcIdx); - } - else { - xVoxl_Copy(&funcIdx, iClientVox); - } - -#ifndef BE_SUPA_FAST - DebugNote(("Verifying func idx")); -#endif - eResult = FunD_VerifyFuncIdx_(this, &funcIdx); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - -#ifndef BE_SUPA_FAST - DebugNote(("Getting value")); -#endif - FunD_GetSampledValue_(this, this->mpData, &funcIdx, iCondition, iTimePoint, &fValue); - -#ifndef BE_SUPA_FAST - DebugNote(("Setting return value")); -#endif - *oValue = fValue; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - -#ifndef BE_SUPA_FAST - DebugExitFunction; -#endif - - return eResult; -} - -FunD_tErr FunD_GetDataForAllTimePoints(mriFunctionalDataRef this, xVoxelRef iClientVox, int iCondition, float *oaValue) -{ - FunD_tErr eResult = FunD_tErr_NoError; - xVoxel funcIdx; - int nTimePoint = 0; - float fValue = 0; - - DebugEnterFunction( - ("FunD_GetDataForAllTimePoints( this=%p, iClientVox=%p, " - "iCondition=%d, oaValue=%p)", - this, - iClientVox, - iCondition, - oaValue)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != iClientVox && NULL != oaValue), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking condition")); - DebugAssertThrowX((iCondition >= 0 && iCondition < this->mNumConditions), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - if (!this->mbScalar) { - DebugNote(("Converting client to func idx")); - FunD_ConvertClientToFloatFuncIdx_(this, iClientVox, &funcIdx); - } - else { - xVoxl_Copy(&funcIdx, iClientVox); - } - - DebugNote(("Verifying func idx")); - eResult = FunD_VerifyFuncIdx_(this, &funcIdx); - DebugAssertQuietThrow((eResult == FunD_tErr_NoError)); - - for (nTimePoint = 0; nTimePoint < this->mNumTimePoints; nTimePoint++) { - DebugNote(("Getting value")); - FunD_GetValue_(this, this->mpData, &funcIdx, iCondition, nTimePoint, &fValue); - - DebugNote(("Setting return value for tp %d", nTimePoint)); - oaValue[nTimePoint] = fValue; - } - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetDeviation( - mriFunctionalDataRef this, xVoxelRef iClientVox, int iCondition, int iTimePoint, float *oValue) -{ - FunD_tErr eResult = FunD_tErr_NoError; - xVoxel funcIdx; - float fCovariance = 0; - float fSigma = 0; - int nCovMtx = 0; - - DebugEnterFunction( - ("FunD_GetDeviation( this=%p, iCondition=%d, " - "iTimePoint=%d, oValue=%p)", - this, - iCondition, - iTimePoint, - oValue)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oValue), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking condition")); - DebugAssertThrowX((iCondition >= 0 && iCondition < this->mNumConditions), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking time point")); - DebugAssertThrowX((iTimePoint >= 0 && iTimePoint < this->mNumTimePoints), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* If this is condition 0, just return 0, since there's not error - data on the null condition. */ - if (0 == iCondition) { - DebugNote(("Setting return value")); - *oValue = 0; - } - else { - DebugNote(("Getting cov mtx for cond %d tp %d\n", iCondition, iTimePoint)); - nCovMtx = ((iCondition - 1) * this->mNumTimePoints) + iTimePoint; - fCovariance = this->mCovMtx[nCovMtx][nCovMtx]; - - if (!this->mbScalar) { - DebugNote(("Converting client to func idx")); - FunD_ConvertClientToFuncIdx_(this, iClientVox, &funcIdx); - } - else { - xVoxl_Copy(&funcIdx, iClientVox); - } - - DebugNote(("Getting sigma value")); - FunD_GetSigma_(this, &funcIdx, iTimePoint, &fSigma); - - DebugNote(("Setting return value")); - *oValue = sqrt(fSigma * fSigma * fCovariance); - } - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetDeviationForAllTimePoints(mriFunctionalDataRef this, - xVoxelRef iClientVox, - int iCondition, - float *oaValue) -{ - FunD_tErr eResult = FunD_tErr_NoError; - int nTimePoint = 0; - xVoxel funcIdx; - float fCovariance = 0; - float fSigma = 0; - int nCovMtx = 0; - - DebugEnterFunction( - ("FunD_GetDeviation( this=%p, iCondition=%d, " - "oaValue=%p)", - this, - iCondition, - oaValue)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oaValue), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking condition")); - DebugAssertThrowX((iCondition >= 0 && iCondition < this->mNumConditions), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - if (!this->mbScalar) { - DebugNote(("Converting client to func idx")); - FunD_ConvertClientToFuncIdx_(this, iClientVox, &funcIdx); - } - else { - xVoxl_Copy(&funcIdx, iClientVox); - } - - for (nTimePoint = 0; nTimePoint < this->mNumTimePoints; nTimePoint++) { - /* If this is condition 0, just return 0, since there's not error - data on the null condition. */ - if (0 == iCondition) { - DebugNote(("Setting return value")); - oaValue[nTimePoint] = 0; - } - else { - DebugNote(("Getting sigma value")); - FunD_GetSigma_(this, &funcIdx, nTimePoint, &fSigma); - - DebugNote(("Getting cov mtx for cond %d tp %d\n", iCondition, nTimePoint)); - nCovMtx = ((iCondition - 1) * this->mNumTimePoints) + nTimePoint; - fCovariance = this->mCovMtx[nCovMtx][nCovMtx]; - - DebugNote(("Setting return value")); - oaValue[nTimePoint] = sqrt(fSigma * fSigma * fCovariance); - } - } - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_Smooth(mriFunctionalDataRef this, int iTimePoint, int iCondition, float iSigma) -{ - FunD_tErr eResult = FunD_tErr_NoError; - MRI *kernel = NULL; - - DebugEnterFunction( - ("FunD_Smooth( this=%p, iCondition=%d, " - "iTimePoint=%d, iSigma=%f)", - this, - iCondition, - iTimePoint, - iSigma)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking condition")); - DebugAssertThrowX((iCondition >= 0 && iCondition < this->mNumConditions), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking time point")); - DebugAssertThrowX((iTimePoint >= 0 && iTimePoint < this->mNumTimePoints), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - DebugNote(("Allocating gaussian kenrel with MRIgaussian1d")); - kernel = MRIgaussian1d(iSigma, 100); - DebugAssertThrowX((NULL != kernel), eResult, FunD_tErr_CouldntAllocateMRI); - - DebugNote(("Performing convolution with MRIconvolveGaussian")); - MRIconvolveGaussian(this->mpData, this->mpData, kernel); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - if (NULL != kernel) { - MRIfree(&kernel); - } - - return eResult; -} - -FunD_tErr FunD_NormalizeOverAll(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_NormalizeOverAll( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - DebugNote(("Performing normalization with MRInormalizeFrames")); - MRInormalizeFrames(this->mpData); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ConvertTimePointToSecond(mriFunctionalDataRef this, int iTimePoint, float *oSecond) -{ - FunD_tErr eResult = FunD_tErr_NoError; - float timeAtFirstPoint = 0; - - DebugEnterFunction( - ("FunD_ConvertTimePointToSecond( this=%p, " - "iTimePoint=%d, oSecond=%p)", - this, - iTimePoint, - oSecond)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oSecond), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking time point")); - DebugAssertThrowX((iTimePoint >= 0 && iTimePoint < this->mNumTimePoints), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Calc the time second. */ - timeAtFirstPoint = -((float)(this->mNumPreStimTimePoints) * this->mTimeResolution); - DebugNote(("Setting return value")); - *oSecond = timeAtFirstPoint + ((float)iTimePoint * this->mTimeResolution); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ConvertSecondToTimePoint(mriFunctionalDataRef this, float iSecond, int *oTimePoint) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction( - ("FunD_ConvertSecondToTimePoint( this=%p, iSecond=%f, " - "oTimePoint=%p)", - this, - iSecond, - oTimePoint)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oTimePoint), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - // calc the time point - DebugNote(("Setting return value")); - *oTimePoint = (iSecond / this->mTimeResolution) + this->mNumPreStimTimePoints; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_SetTimeResolution(mriFunctionalDataRef this, float iTimeResolution) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_SetTimeResolution( this=%p, iTimeResolution=%f )", this, iTimeResolution)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((iTimeResolution > 0), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Set the time resolution. */ - this->mTimeResolution = iTimeResolution; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_SetNumPreStimTimePoints(mriFunctionalDataRef this, int iNumPoints) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_SetNumPreStimTimePoints( this=%p, iNumPoints=%d)", this, iNumPoints)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((iNumPoints >= 0 && iNumPoints < this->mNumTimePoints), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Set the number of prestim time points. */ - this->mNumPreStimTimePoints = iNumPoints; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetSubjectName(mriFunctionalDataRef this, char *oSubjectName) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_GetSubjectName( this=%p, oSubjectName=%s)", this, oSubjectName)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oSubjectName), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Return the value. */ - DebugNote(("Copying subject name")); - strcpy(oSubjectName, this->msSubjectName); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetNumTimePoints(mriFunctionalDataRef this, int *oNumTimePoints) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_GetNumTimePoints( this=%p, oNumTimePoints=%p)", this, oNumTimePoints)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oNumTimePoints), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Return the value. */ - DebugNote(("Setting return value")); - *oNumTimePoints = this->mNumTimePoints; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetNumConditions(mriFunctionalDataRef this, int *oNumConditions) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_GetNumConditions( this=%p, oNumConditions=%p)", this, oNumConditions)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oNumConditions), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Return the value. */ - DebugNote(("Setting return value")); - *oNumConditions = this->mNumConditions; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetTimeResolution(mriFunctionalDataRef this, float *oTimeResolution) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_Get( this=%p, oTimeResolution=%p)", this, oTimeResolution)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oTimeResolution), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Return the value. */ - DebugNote(("Setting return value")); - *oTimeResolution = this->mTimeResolution; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetNumPreStimTimePoints(mriFunctionalDataRef this, int *oNumPoints) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_GetNumPreStimTimePoints( this=%p, oNumPoints=%p)", this, oNumPoints)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oNumPoints), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Return the value. */ - DebugNote(("Setting return value")); - *oNumPoints = this->mNumPreStimTimePoints; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetValueRange(mriFunctionalDataRef this, float *oMin, float *oMax) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_GetValueRange( this=%p, oMin=%p, oMax=%p)", this, oMin, oMax)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oMin && NULL != oMax), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Return the value. */ - DebugNote(("Setting return value")); - *oMin = this->mMinValue; - *oMax = this->mMaxValue; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_IsErrorDataPresent(mriFunctionalDataRef this, tBoolean *oPresent) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_IsErrorDataPresent( this=%p, oPresent=%p)", this, oPresent)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oPresent), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Return the value. */ - DebugNote(("Setting return value")); - *oPresent = this->mbErrorDataPresent; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetBoundsInClientSpace(mriFunctionalDataRef this, xVoxelRef oBeginCorner, xVoxelRef oEndCorner) -{ - FunD_tErr eResult = FunD_tErr_NoError; - xVoxel curIdx; - xVoxel curClient; - xVoxel minClient; - xVoxel maxClient; - - DebugEnterFunction( - ("FunD_GetBoundsInClientSpace( this=%p, " - "oBeginCorner=%p, oEndCorner=%p)", - this, - oBeginCorner, - oEndCorner)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oBeginCorner && NULL != oEndCorner), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - DebugNote(("Initializing min and max voxels")); - xVoxl_Set(&minClient, 9999, 9999, 9999); - xVoxl_Set(&maxClient, -9999, -9999, -9999); - - /* For all of our indices, convert it to client space and compare to - the min/max. Save the most min/max. */ - xVoxl_Set(&curIdx, 0, 0, 0); - while (xVoxl_IncrementUntilLimits(&curIdx, this->mpData->width, this->mpData->height, this->mpData->depth)) { - DebugNote(("Converting to client space")); - FunD_ConvertFuncIdxToClient_(this, &curIdx, &curClient); - - DebugNote(("Setting min voxel")); - xVoxl_Set(&minClient, - min(xVoxl_GetX(&minClient), xVoxl_GetX(&curClient)), - min(xVoxl_GetY(&minClient), xVoxl_GetY(&curClient)), - min(xVoxl_GetZ(&minClient), xVoxl_GetZ(&curClient))); - - DebugNote(("Setting max voxel")); - xVoxl_Set(&maxClient, - max(xVoxl_GetX(&maxClient), xVoxl_GetX(&curClient)), - max(xVoxl_GetY(&maxClient), xVoxl_GetY(&curClient)), - max(xVoxl_GetZ(&maxClient), xVoxl_GetZ(&curClient))); - } - - DebugNote(("Setting min return voxel")); - xVoxl_Copy(oBeginCorner, &minClient); - DebugNote(("Setting max return voxel")); - xVoxl_Copy(oEndCorner, &maxClient); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_GetValueAtPercentile(mriFunctionalDataRef this, float iPercentile, float *oValue) -{ - FunD_tErr eResult = FunD_tErr_NoError; - int numValues = 0; - int targetCount = 0; - int sum = 0; - int nBin = 0; - float value = 0; - - DebugEnterFunction( - ("FunD_GetValueAtPercentile( this=%p, iPercentile=%f, " - "oValue=%p)", - this, - iPercentile, - oValue)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != oValue), eResult, FunD_tErr_InvalidParameter); - DebugNote(("Checking 0 <= percentile <= 100 ")); - DebugAssertThrowX((iPercentile >= 0 && iPercentile <= 100), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* If we don't have our frequencies yet, calc them now with 100 bins. */ - if (NULL == this->mFrequencies) { - eResult = FunD_CalcFrequencies_(this, FunD_knNumFrequencyBins); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - } - - /* Calc the total number of values. Calc the precent of that. */ - numValues = - this->mpData->width * this->mpData->height * this->mpData->depth * this->mNumConditions * this->mNumTimePoints; - - targetCount = (float)numValues * iPercentile / 100.0; - - /* Start from the beginning. Add the sum of each bin until we get to - the number we're looking for. */ - sum = 0; - nBin = 0; - while (sum < targetCount && nBin < this->mNumBins) { - sum += this->mFrequencies[nBin]; - nBin++; - } - - /* Calc the number that is at the beginning of that bin. */ - value = this->mMinValue + (((this->mMaxValue - this->mMinValue + 1) * nBin) / this->mNumBins); - - /* Return it. */ - DebugNote(("Setting return value")); - *oValue = value; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -/* This function doesn't seem to work very well but is left here for - reference . */ -#if 0 -FunD_tErr FunD_GetPercentileOfValue ( mriFunctionalDataRef this, - float inValue, - float* outPercentile ) -{ - - FunD_tErr theErr = FunD_tErr_NoError; - int theTargetBin, theBin; - int theSum, theNumValues; - float thePercentile; - - /* If we don't have our frequencies yet, calc them now with 100 bins. */ - if ( NULL == this->mFrequencies ) - { - theErr = FunD_CalcFrequencies_( this, FunD_knNumFrequencyBins ); - if ( FunD_tErr_NoError != theErr ) - { - goto error; - } - } - - /* Check to make sure numBins is 100 here? */ - - /* Calculate the bin in which it should be. This is done with - floating math because they want a percentile even tho we call it - a bin and use the integer version. */ - theTargetBin = (inValue - this->mMinValue) / - (((this->mMaxValue - this->mMinValue)+1.0) / (float)this->mNumBins); - theTargetBin = ((inValue - this->mMinValue) * (float)this->mNumBins) / - (this->mMaxValue - this->mMinValue + 1.0); - - /* Walk through the frequency array until we hit the bin we got as - an answer. Add up the counts along the way. */ - theSum = 0; - theBin = 0; - for ( theBin = 0; theBin <= theTargetBin; theBin++ ) - { - theSum += this->mFrequencies[theBin]; - } - - /* Divide the counts by the total number of values to get our - percentile. */ - theNumValues = this->mNumConditions * this->mNumTimePoints * - this->mNumRows * this->mNumCols * this->mNumSlices; - thePercentile = (float)theSum / (float)theNumValues * 100.0; - - *outPercentile = thePercentile; - - goto cleanup; -error: - - if ( FunD_tErr_NoError != theErr ) - { - DebugPrint( ("Error in FunD_GetPercentileOfValue (%d): %s\n", - theErr, FunD_GetErrorString(theErr) ) ); - } - -cleanup: - - return theErr; -} -#endif - -FunD_tErr FunD_CalcFDRThreshold(mriFunctionalDataRef this, - int iCondition, - int iTimePoint, - int iSign, - float iRate, - MRI *iMaskVolume, - float *oThresholdMin) -{ - FunD_tErr eResult = FunD_tErr_NoError; - int eMRI = ERROR_NONE; - int nFrame = 0; - double newMin = 0; - MRI *pLocalMaskVol = NULL; - MATRIX *localToClient = NULL; - - DebugEnterFunction( - ("FunD_CalcFDRThreshold( this=%p, iCondition=%d, " - "iTimePoint=%d, iSign=%d, iRate=%f, iMaskVolume=%p," - "oThresholdMin=%p)", - this, - iCondition, - iTimePoint, - iSign, - iRate, - iMaskVolume, - oThresholdMin)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* We need to transform the mask into our space. Allocate an empty 1 - frame volume with the same dimesnions as our data, then transform - the mask volume into it. To transform, we need the target->source - transform, which is local->client, which is the inverse of our - mIdxToIdxTransform, so create that too.*/ - if (NULL != iMaskVolume) { - DebugNote(("Allocating local mask volume")); - pLocalMaskVol = MRIalloc(this->mpData->width, this->mpData->height, this->mpData->depth, this->mpData->type); - DebugAssertThrowX((NULL != pLocalMaskVol), eResult, FunD_tErr_CouldntAllocateVolume); - - DebugNote(("Copying header")); - MRIcopyHeader(this->mpData, pLocalMaskVol); - - DebugNote(("Creating inverse of transform (for local->client)")); - localToClient = MatrixInverse(this->mIdxToIdxTransform->mAtoB, NULL); - DebugAssertThrowX((NULL != localToClient), eResult, FunD_tErr_CouldntAllocateMatrix); - - DebugNote(("Converting client mask to local mask")); - eMRI = MRIvol2Vol(iMaskVolume, pLocalMaskVol, localToClient, SAMPLE_NEAREST, 0); - DebugAssertThrowX((ERROR_NONE == eMRI), eResult, FunD_tErr_CouldntTransformMask); - } - - /* Get a frame number. */ - FunD_GetDataFrameNumber(iCondition, iTimePoint, &nFrame); - - /* Do the FDR */ - DebugNote(("Running MRIfdr2vwth")); - eMRI = MRIfdr2vwth(&this->mpData, - 1, - &nFrame, /* 0-based frame number of input vol */ - iRate, /* rate 0-1 */ - iSign, /* 0=all, +1=only pos, -1=only neg */ - TRUE, /* interp vals as -log10(p) */ - &pLocalMaskVol, /* optional mask volume */ - &newMin, /* voxel-wise thresh (vwth) 0-1, - or if log10flag, -log10(vwth) */ - NULL); /* option thresholded output */ - DebugAssertThrowX((ERROR_NONE == eMRI), eResult, FunD_tErr_ErrorPerformingFDR); - - /* Return the new min. */ - DebugNote(("Returning threshold min")); - *oThresholdMin = newMin; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - if (NULL != pLocalMaskVol) { - DebugNote(("Freeing local mask vol")); - MRIfree(&pLocalMaskVol); - } - if (NULL != localToClient) { - DebugNote(("Freeing local to client transform")); - MatrixFree(&localToClient); - } - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_SaveRegistration(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - fMRI_REG *regInfo = NULL; - struct stat fileInfo; - char sFileName[256]; - char sBackupFileName[256]; - char sConversionMethod[256]; - FILE *pBackupFile; - FILE *pFile; - char data; - int nBackup = 1; - - DebugEnterFunction(("FunD_SaveRegistration( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* make a reg info struct */ - DebugNote(("Allocating registration")); - regInfo = (fMRI_REG *)malloc(sizeof(fMRI_REG)); - DebugAssertThrowX((NULL != regInfo), eResult, FunD_tErr_CouldntAllocateStorage); - - /* Fill out the fmri registration struct. Notice we used the ps and - st values we first got from the registration, instead of the - values in the MRI. */ - DebugNote(("Setting registration info")); - regInfo->in_plane_res = this->mpData->ps; - regInfo->slice_thickness = this->mpData->thick; - regInfo->brightness_scale = this->mBrightnessScale; - DebugNote(("Copying subject name")); - strcpy(regInfo->name, this->msSubjectName); - - /* Copy it into the regInfo structure. */ - DebugNote(("Copying registration matrix into registration info")); - regInfo->mri2fmri = MatrixCopy(this->mIdxToIdxTransform->mARAStoBRAS, NULL); - DebugNote(("Inversing registration matrix into registration info")); - regInfo->fmri2mri = MatrixInverse(regInfo->mri2fmri, NULL); - - /* If a registration already exists... */ - if (stat(sFileName, &fileInfo) != 0) { - /* We need to backup the file. Generate a new backup filename */ - do { - /* Keep appending an increasing number to the end of the - original filename. Check if the newly named file exists. It - it doesn't exist, the while loop will exit and we've found - our new backup filename. */ - sprintf(sBackupFileName, "%s.%d", sFileName, nBackup++); - DebugNote(("Opening file %s", sBackupFileName)); - - } while (stat(sFileName, &fileInfo) != 0); - - /* Copy the registration file to backup.*/ - DebugNote(("Opening file %s", sFileName)); - pFile = fopen(sFileName, "r"); - - DebugNote(("Opening backup file %s", sBackupFileName)); - pBackupFile = fopen(sBackupFileName, "w"); - - DebugNote(("Copying bytes to backup file")); - while (!feof(pFile)) { - if (fread(&data, sizeof(data), 1, pFile) != 1) { - DebugNote(("Could not read variable")); - } - if (feof(pFile)) { - break; - } - fwrite(&data, sizeof(data), 1, pBackupFile); - } - - DebugNote(("Closing backup file")); - fclose(pBackupFile); - DebugNote(("Closing file")); - fclose(pFile); - } - - /* Write it to disk */ - DebugNote(("Writing registration with StatWriteRegistration")); - StatWriteRegistration(regInfo, sFileName); - - DebugNote(("Freeing registration with StatFreeRegistration")); - StatFreeRegistration(®Info); - - /* Append the conversion type to the registration file. */ - switch (this->mConvMethod) { - case FunD_tConversionMethod_FFF: - strcpy(sConversionMethod, FunD_ksConversionMethod_FFF); - break; - case FunD_tConversionMethod_Round: - strcpy(sConversionMethod, FunD_ksConversionMethod_Round); - break; - case FunD_tConversionMethod_FCF: - strcpy(sConversionMethod, FunD_ksConversionMethod_FCF); - break; - default: - break; - } - DebugNote(("Opening %s")); - pFile = fopen(sFileName, "a"); - if (NULL != pFile) { - DebugNote(("Printing conversion method to file")); - fprintf(pFile, "%s\n", sConversionMethod); - DebugNote(("Closing file")); - fclose(pFile); - } - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_SetRegistrationToIdentity(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - MATRIX *identity = NULL; - - DebugEnterFunction(("FunD_SetRegistrationToIdentity( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Create an identity matrix and copy it into the registration - transform. */ - DebugNote(("Creting identity matrix")); - identity = MatrixAlloc(4, 4, MATRIX_REAL); - MatrixIdentity(4, identity); - - DebugNote(("Copying identity to transform")); - Trns_CopyARAStoBRAS(this->mIdxToIdxTransform, identity); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - if (NULL != identity) { - DebugNote(("Freeing identity matrix")); - MatrixFree(&identity); - } - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ApplyTransformToRegistration(mriFunctionalDataRef this, MATRIX *iTransform) -{ - FunD_tErr eResult = FunD_tErr_NoError; - Trns_tErr eTransform = Trns_tErr_NoErr; - MATRIX *invTransform = NULL; - - DebugEnterFunction( - ("FunD_ApplyTransformToRegistration( this=%p )" - "iTransform=%p", - this, - iTransform)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != iTransform), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* We apply the inverse of the transform to our idx to idx - transform. */ - DebugNote(("Getting inverse of matrix")); - invTransform = MatrixInverse(iTransform, NULL); - - DebugNote(("Applying matrix to transform")); - eTransform = Trns_ApplyTransform(this->mIdxToIdxTransform, invTransform); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, FunD_tErr_ErrorAccessingTransform); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - if (NULL != invTransform) { - DebugNote(("Freeing inverse matrix")); - MatrixFree(&invTransform); - } - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_TranslateRegistration(mriFunctionalDataRef this, float ifDistance, tAxis iAxis) -{ - FunD_tErr eResult = FunD_tErr_NoError; - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_TranslateRegistration( this=%p )" - "ifDistance=%f, iAxis=%d", - this, - ifDistance, - iAxis)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((iAxis >= 0 && iAxis < knNumAxes), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* do the inverse of this action */ - DebugNote(("Translating transformation object")); - eTransform = Trns_Translate(this->mIdxToIdxTransform, -ifDistance, iAxis); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, FunD_tErr_ErrorAccessingTransform); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_RotateRegistration(mriFunctionalDataRef this, float ifDegrees, tAxis iAxis, xVoxelRef iCenterFuncRAS) -{ - FunD_tErr eResult = FunD_tErr_NoError; - Trns_tErr eTransform = Trns_tErr_NoErr; - float fX = 0; - float fY = 0; - float fZ = 0; - - DebugEnterFunction( - ("FunD_RotateRegistration( this=%p, ifDegrees=%f, " - "iAxis=%d iCenterFuncRAS=%p", - this, - ifDegrees, - iAxis, - iCenterFuncRAS)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this && NULL != iCenterFuncRAS), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((iAxis >= 0 && iAxis < knNumAxes), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* get the center point */ - DebugNote(("Getting center coordinates")); - fX = xVoxl_GetFloatX(iCenterFuncRAS); - fY = xVoxl_GetFloatY(iCenterFuncRAS); - fZ = xVoxl_GetFloatZ(iCenterFuncRAS); - - /* first translate to the center we're rotating around */ - DebugNote(("Translating registration by negative center")); - FunD_TranslateRegistration(this, -fX, tAxis_X); - FunD_TranslateRegistration(this, -fY, tAxis_Y); - FunD_TranslateRegistration(this, -fZ, tAxis_Z); - - /* do the inverse of this action */ - DebugNote(("Rotating transformation object by %f degrees around %d", -ifDegrees, iAxis)); - eTransform = Trns_Rotate(this->mIdxToIdxTransform, -ifDegrees, iAxis); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, FunD_tErr_ErrorAccessingTransform); - - /* translate back */ - DebugNote(("Translating registration by center")); - FunD_TranslateRegistration(this, fX, tAxis_X); - FunD_TranslateRegistration(this, fY, tAxis_Y); - FunD_TranslateRegistration(this, fZ, tAxis_Z); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ScaleRegistration(mriFunctionalDataRef this, float ifFactor, tAxis iAxis) -{ - FunD_tErr eResult = FunD_tErr_NoError; - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_ScaleRegistration( this=%p, ifFactor=%f, " - "iAxis=%d", - this, - ifFactor, - iAxis)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((iAxis >= 0 && iAxis < knNumAxes), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* do the inverse of this action */ - DebugNote(("Scaling the transformation object")); - eTransform = Trns_Scale(this->mIdxToIdxTransform, 1.0 / ifFactor, iAxis); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, FunD_tErr_ErrorAccessingTransform); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_DebugPrint(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_DebugPrint( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - DebugPrint(("mriFunctionalData:\n")); - DebugPrint(("\tmsFileName=%s\n", this->msFileName)); - DebugPrint(("\tmsRegistrationFileName=%s\n", this->msRegistrationFileName)); - DebugPrint(("\tmsSubjectName=%s\n", this->msSubjectName)); - DebugPrint(("\tmpData->ps=%f\n", this->mpData->ps)); - DebugPrint(("\tmpData->thick=%f\n", this->mpData->thick)); - DebugPrint(("\tmpData->width=%d\n", this->mpData->width)); - DebugPrint(("\tmpData->height=%d\n", this->mpData->height)); - DebugPrint(("\tmpData->depth=%d\n", this->mpData->depth)); - DebugPrint(("\tmConvMethod=%d\n", this->mConvMethod)); - DebugPrint(("\tmNumTimePoints=%d\n", this->mNumTimePoints)); - DebugPrint(("\tmNumConditions=%d\n", this->mNumConditions)); - DebugPrint(("\tmbNullConditionPresent=%d\n", this->mbNullConditionPresent)); - DebugPrint(("\tmMaxValue=%f\n", this->mMaxValue)); - DebugPrint(("\tmMinValue=%f\n", this->mMinValue)); - DebugPrint(("\tmTimeResolution=%f\n", this->mTimeResolution)); - DebugPrint(("\tmNumPreStimTimePoints=%d\n", this->mNumPreStimTimePoints)); - DebugPrint(("\tmbErrorDataPresent=%d\n", this->mbErrorDataPresent)); - DebugPrint(("\tmNumBins=%d\n", this->mNumBins)); - DebugPrint(("\n")); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_ResampleData_(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - MRI *volume = NULL; - int nTimePoint = 0; - int nCondition = 0; - xVoxel begin; - xVoxel end; - xVoxel clientIdx; - xVoxel funcIdx; - xVoxel resampleIdx; - float value = 0; - - DebugEnterFunction(("FunD_ResampleData_( this=%p )", this)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Make sure we have the bounds. */ - DebugAssertThrowX((this->mbHaveClientBounds), eResult, FunD_tErr_InvalidParameter); - - /* Make an MRI with the same dimensions as the client. Use the type - and number of frames of our data volume. */ - DebugNote(("Creating volume")); - volume = MRIallocSequence(this->mClientXMax - this->mClientXMin, - this->mClientYMax - this->mClientYMin, - this->mClientZMax - this->mClientZMin, - this->mpData->type, - this->mpData->nframes); - DebugAssertThrowX((NULL != volume), eResult, FunD_tErr_CouldntAllocateMRI); - - DebugNote(("Getting bounds")); - FunD_GetBoundsInClientSpace(this, &begin, &end); - - /* For each timepoint and condition... */ - for (nCondition = 0; nCondition < this->mNumConditions; nCondition++) { - for (nTimePoint = 0; nTimePoint < this->mNumTimePoints; nTimePoint++) { - /* For each voxel... */ - xVoxl_Copy(&clientIdx, &begin); - while (xVoxl_IncrementWithMinsUntilLimits( - &clientIdx, xVoxl_GetX(&begin), xVoxl_GetY(&begin), xVoxl_GetX(&end), xVoxl_GetY(&end), xVoxl_GetZ(&end))) { - DebugPrint(("\rResampling: %d %d %d", nCondition, nTimePoint, xVoxl_GetZ(&clientIdx))); - - /* Get the func idx. */ - if (!this->mbScalar) { - DebugNote(("Converting client to func idx")); - FunD_ConvertClientToFuncIdx_(this, &clientIdx, &funcIdx); - } - else { - xVoxl_Copy(&funcIdx, &clientIdx); - } - eResult = FunD_VerifyFuncIdx_(this, &funcIdx); - if (FunD_tErr_NoError == eResult) { - FunD_GetValue_(this, this->mpData, &funcIdx, nCondition, nTimePoint, &value); - } - else { - continue; - } - - /* Set the value. */ - xVoxl_Set(&resampleIdx, - xVoxl_GetX(&clientIdx) - this->mClientXMin, - xVoxl_GetY(&clientIdx) - this->mClientYMin, - xVoxl_GetZ(&clientIdx) - this->mClientZMin); - FunD_SetValue_(this, volume, &resampleIdx, nCondition, nTimePoint, value); - } - } - } - - fprintf(stdout, "\rResampling: 100%% done. \n"); - - if (NULL != this->mpResampledData) { - MRIfree(&this->mpResampledData); - } - this->mpResampledData = volume; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - - if (NULL != volume) { - MRIfree(&volume); - } - - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_CalcFrequencies_(mriFunctionalDataRef this, int iNumBins) -{ - FunD_tErr eResult = FunD_tErr_NoError; - int *aFrequencies = NULL; - int nCondition = 0; - int nTimePoint = 0; - xVoxel curIdx; - int nBin = 0; - float value = 0; - - DebugEnterFunction(("FunD_CalcFrequencies_( this=%p, iNumBins=%d )", this, iNumBins)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((iNumBins > 0), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Verifying object")); - eResult = FunD_Verify(this); - DebugAssertThrow((eResult == FunD_tErr_NoError)); - - /* Allocate the storage. */ - DebugNote(("Allocating storage for new frequencies")); - aFrequencies = calloc(iNumBins, sizeof(int)); - DebugAssertThrowX((NULL != aFrequencies), eResult, FunD_tErr_CouldntAllocateStorage); - - for (nCondition = 0; nCondition < this->mNumConditions; nCondition++) { - for (nTimePoint = 0; nTimePoint < this->mNumTimePoints; nTimePoint++) { - xVoxl_Set(&curIdx, 0, 0, 0); - while (xVoxl_IncrementUntilLimits(&curIdx, this->mpData->width, this->mpData->height, this->mpData->depth)) { - FunD_GetValue_(this, this->mpData, &curIdx, nCondition, nTimePoint, &value); - - /* Calculate the bin in which it should be. */ - nBin = (value - this->mMinValue) / (((this->mMaxValue - this->mMinValue) + 1.0) / (float)iNumBins); - - /* Inc the count in that bin. */ - aFrequencies[nBin]++; - } - } - } - - /* If we already have frequencies, free them. */ - if (NULL != this->mFrequencies) { - DebugNote(("Deleting exisiting frequencies")); - free(this->mFrequencies); - } - - DebugNote(("Assigning new frequencies")); - this->mFrequencies = aFrequencies; - this->mNumBins = iNumBins; - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - - if (NULL != aFrequencies) { - DebugNote(("Deleting temp frequencies")); - free(aFrequencies); - } - - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -char *FunD_GetErrorString(FunD_tErr iErr) -{ - if (!(iErr >= 0 && iErr < FunD_tErr_knNumErrorCodes)) { - iErr = FunD_tErr_InvalidErrorCode; - } - - return (char *)(FunD_ksaErrorString[iErr]); -} - -#ifndef FUND_USE_MACROS - -void FunD_ConvertClientToFuncIdx_(mriFunctionalDataRef this, xVoxelRef iClientVox, xVoxelRef oFuncIdx) -{ - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_ConvertClientToFuncIdx_( this=%p, iClientVox=%p, " - "oFuncIdx=%p", - this, - iClientVox, - oFuncIdx)); - - DebugNote(("Checking parameters")); - DebugAssertThrow((NULL != this && NULL != iClientVox && NULL != oFuncIdx)); - - DebugNote(("Copying client voxel to temp1")); - xVoxl_Copy(&this->mTmpVoxel1, iClientVox); - - DebugNote(("Converting client to func idx")); - eTransform = Trns_ConvertAtoB(this->mIdxToIdxTransform, &this->mTmpVoxel1, &this->mTmpVoxel2); - DebugAssertThrow((Trns_tErr_NoErr == eTransform)); - - /* do the proper conversion method */ - switch (this->mConvMethod) { - case FunD_tConversionMethod_FFF: - DebugNote(("Using FFF conversion")); - xVoxl_SetFloat(oFuncIdx, - floor(xVoxl_GetFloatX(&this->mTmpVoxel2)), - floor(xVoxl_GetFloatY(&this->mTmpVoxel2)), - floor(xVoxl_GetFloatZ(&this->mTmpVoxel2))); - break; - case FunD_tConversionMethod_Round: - DebugNote(("Using Round conversion")); - xVoxl_SetFloat(oFuncIdx, - rint(xVoxl_GetFloatX(&this->mTmpVoxel2)), - rint(xVoxl_GetFloatY(&this->mTmpVoxel2)), - rint(xVoxl_GetFloatZ(&this->mTmpVoxel2))); - break; - case FunD_tConversionMethod_FCF: - DebugNote(("Using FCF conversion")); - xVoxl_SetFloat(oFuncIdx, - floor(xVoxl_GetFloatX(&this->mTmpVoxel2)), - ceil(xVoxl_GetFloatY(&this->mTmpVoxel2)), - floor(xVoxl_GetFloatZ(&this->mTmpVoxel2))); - break; - default: - break; - } - - DebugCatch; - xVoxl_Set(oFuncIdx, -1, -1, -1); - EndDebugCatch; - - DebugExitFunction; -} - -void FunD_ConvertClientToFloatFuncIdx_(mriFunctionalDataRef this, xVoxelRef iClientVox, xVoxelRef oFuncIdx) -{ - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_ConvertClientToFloatFuncIdx_( this=%p, iClientVox=%p, " - "oFuncIdx=%p", - this, - iClientVox, - oFuncIdx)); - - DebugNote(("Checking parameters")); - DebugAssertThrow((NULL != this && NULL != iClientVox && NULL != oFuncIdx)); - - DebugNote(("Copying client voxel to temp1")); - xVoxl_Copy(&this->mTmpVoxel1, iClientVox); - - DebugNote(("Converting client to func idx")); - eTransform = Trns_ConvertAtoB(this->mIdxToIdxTransform, &this->mTmpVoxel1, oFuncIdx); - DebugAssertThrow((Trns_tErr_NoErr == eTransform)); - - DebugCatch; - xVoxl_Set(oFuncIdx, -1, -1, -1); - EndDebugCatch; - - DebugExitFunction; -} - -#endif - -void FunD_ConvertClientToFuncRAS_(mriFunctionalDataRef this, xVoxelRef iClientVox, xVoxelRef oFuncRAS) -{ - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_ConvertClientToFuncRAS_( this=%p, iClientVox=%p, " - "oFuncRAS=%p", - this, - iClientVox, - oFuncRAS)); - - DebugNote(("Checking parameters")); - DebugAssertThrow((NULL != this && NULL != iClientVox && NULL != oFuncRAS)); - - DebugNote(("Copying client voxel to temp1")); - xVoxl_Copy(&this->mTmpVoxel1, iClientVox); - - DebugNote(("Converting client to func idx")); - eTransform = Trns_ConvertAtoB(this->mIdxToIdxTransform, &this->mTmpVoxel1, &this->mTmpVoxel2); - DebugAssertThrow((Trns_tErr_NoErr == eTransform)); - - DebugNote(("Converting func idx to func RAS")); - eTransform = Trns_ConvertBtoRAS(this->mIdxToIdxTransform, &this->mTmpVoxel2, &this->mTmpVoxel1); - DebugAssertThrow((Trns_tErr_NoErr == eTransform)); - - DebugNote(("Copying into return voxel")); - xVoxl_Copy(oFuncRAS, &this->mTmpVoxel1); - - DebugCatch; - xVoxl_Set(oFuncRAS, -1, -1, -1); - EndDebugCatch; - - DebugExitFunction; -} - -void FunD_ConvertFuncIdxToClient_(mriFunctionalDataRef this, xVoxelRef iFuncIdx, xVoxelRef oClientVox) -{ - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_ConvertFuncIdxToClient_( this=%p, iFuncIdx=%p, " - "oClientVox=%p", - this, - iFuncIdx, - oClientVox)); - - DebugNote(("Checking parameters")); - DebugAssertThrow((NULL != this && NULL != iFuncIdx && NULL != oClientVox)); - - DebugNote(("Copying func idx voxel to temp1")); - xVoxl_Copy(&this->mTmpVoxel1, iFuncIdx); - - DebugNote(("Converting func idx to client")); - eTransform = Trns_ConvertBtoA(this->mIdxToIdxTransform, &this->mTmpVoxel1, &this->mTmpVoxel2); - DebugAssertThrow((Trns_tErr_NoErr == eTransform)); - - DebugNote(("Copying into return voxel")); - xVoxl_Copy(oClientVox, &this->mTmpVoxel2); - - DebugCatch; - xVoxl_Set(oClientVox, -1, -1, -1); - EndDebugCatch; - - DebugExitFunction; -} - -void FunD_ConvertRASToFuncIdx_(mriFunctionalDataRef this, xVoxelRef iRAS, xVoxelRef oFuncIdx) -{ - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_ConvertRASToFuncIdx_( this=%p, iRAS=%p, " - "oFuncIdx=%p", - this, - iRAS, - oFuncIdx)); - - DebugNote(("Checking parameters")); - DebugAssertThrow((NULL != this && NULL != iRAS && NULL != oFuncIdx)); - - DebugNote(("Copying RAS to temp1")); - xVoxl_Copy(&this->mTmpVoxel1, iRAS); - - DebugNote(("Converting RAS to func idx")); - eTransform = Trns_ConvertBRAStoB(this->mIdxToIdxTransform, &this->mTmpVoxel1, &this->mTmpVoxel2); - DebugAssertThrow((Trns_tErr_NoErr == eTransform)); - - /* do the proper conversion method */ - switch (this->mConvMethod) { - case FunD_tConversionMethod_FFF: - DebugNote(("Using FFF conversion")); - xVoxl_SetFloat(oFuncIdx, - floor(xVoxl_GetFloatX(&this->mTmpVoxel2)), - floor(xVoxl_GetFloatY(&this->mTmpVoxel2)), - floor(xVoxl_GetFloatZ(&this->mTmpVoxel2))); - break; - case FunD_tConversionMethod_Round: - DebugNote(("Using Round conversion")); - xVoxl_SetFloat(oFuncIdx, - rint(xVoxl_GetFloatX(&this->mTmpVoxel2)), - rint(xVoxl_GetFloatY(&this->mTmpVoxel2)), - rint(xVoxl_GetFloatZ(&this->mTmpVoxel2))); - break; - case FunD_tConversionMethod_FCF: - DebugNote(("Using FCF conversion")); - xVoxl_SetFloat(oFuncIdx, - floor(xVoxl_GetFloatX(&this->mTmpVoxel2)), - ceil(xVoxl_GetFloatY(&this->mTmpVoxel2)), - floor(xVoxl_GetFloatZ(&this->mTmpVoxel2))); - break; - default: - break; - } - - DebugCatch; - xVoxl_Set(oFuncIdx, -1, -1, -1); - EndDebugCatch; - - DebugExitFunction; -} - -void FunD_ConvertFuncIdxToFuncRAS_(mriFunctionalDataRef this, xVoxelRef iFuncIdx, xVoxelRef oFuncRAS) -{ - Trns_tErr eTransform = Trns_tErr_NoErr; - - DebugEnterFunction( - ("FunD_ConvertFuncIdxToFuncRAS_( this=%p, iFuncIdx=%p, " - "oFuncRAS=%p", - this, - iFuncIdx, - oFuncRAS)); - - DebugNote(("Checking parameters")); - DebugAssertThrow((NULL != this && NULL != iFuncIdx && NULL != oFuncRAS)); - - DebugNote(("Copying func idx to temp1")); - xVoxl_Copy(&this->mTmpVoxel1, iFuncIdx); - - DebugNote(("Covnerting func idx to func ras")); - eTransform = Trns_ConvertBtoRAS(this->mIdxToIdxTransform, &this->mTmpVoxel1, &this->mTmpVoxel2); - DebugAssertThrow((Trns_tErr_NoErr == eTransform)); - - DebugNote(("Copying to return voxel")); - xVoxl_Copy(oFuncRAS, &this->mTmpVoxel2); - - DebugCatch; - xVoxl_Set(oFuncRAS, -1, -1, -1); - EndDebugCatch; - - DebugExitFunction; -} - -#ifndef FUND_USE_MACROS - -void FunD_GetValue_( - mriFunctionalDataRef this, MRI *iData, xVoxelRef iIdx, int inCondition, int inTimePoint, float *oValue) -{ - int nFrame = 0; - - FunD_GetDataFrameNumber(inCondition, inTimePoint, &nFrame); - - MRIsampleVolumeFrameType(iData, - xVoxl_GetFloatX(iIdx), - xVoxl_GetFloatY(iIdx), - xVoxl_GetFloatZ(iIdx), - nFrame, - SAMPLE_NEAREST, - &this->mTmpReal); - - *oValue = this->mTmpReal; - -#if 0 - switch ( iData->type ) - { - case MRI_UCHAR: - *oValue = MRIseq_vox( iData, xVoxl_GetX(iIdx), - xVoxl_GetY(iIdx),xVoxl_GetZ(iIdx),nFrame); - break; - case MRI_INT: - *oValue = MRIIseq_vox( iData, xVoxl_GetX(iIdx), - xVoxl_GetY(iIdx),xVoxl_GetZ(iIdx),nFrame); - break; - case MRI_LONG: - *oValue = MRILseq_vox( iData, xVoxl_GetX(iIdx), - xVoxl_GetY(iIdx),xVoxl_GetZ(iIdx),nFrame); - break; - case MRI_FLOAT: - *oValue = MRIFseq_vox( iData, xVoxl_GetX(iIdx), - xVoxl_GetY(iIdx),xVoxl_GetZ(iIdx),nFrame); - break; - case MRI_SHORT: - *oValue = MRISseq_vox( iData, xVoxl_GetX(iIdx), - xVoxl_GetY(iIdx),xVoxl_GetZ(iIdx),nFrame); - break; - default: - *oValue = 0; - break ; - } -#endif -} - -void FunD_GetSampledValue_( - mriFunctionalDataRef this, MRI *iData, xVoxelRef iIdx, int inCondition, int inTimePoint, float *oValue) -{ - int nFrame = 0; - - FunD_GetDataFrameNumber(inCondition, inTimePoint, &nFrame); - - MRIsampleVolumeFrameType(iData, - xVoxl_GetFloatX(iIdx), - xVoxl_GetFloatY(iIdx), - xVoxl_GetFloatZ(iIdx), - nFrame, - (int)this->mSampleType, - &this->mTmpReal); - - *oValue = this->mTmpReal; -} - -void FunD_SetValue_( - mriFunctionalDataRef this, MRI *iData, xVoxelRef iIdx, int inCondition, int inTimePoint, float iValue) -{ - int nFrame = 0; - - FunD_GetDataFrameNumber(inCondition, inTimePoint, &nFrame); - - switch (iData->type) { - case MRI_UCHAR: - MRIseq_vox(iData, xVoxl_GetX(iIdx), xVoxl_GetY(iIdx), xVoxl_GetZ(iIdx), nFrame) = iValue; - break; - case MRI_INT: - MRIIseq_vox(iData, xVoxl_GetX(iIdx), xVoxl_GetY(iIdx), xVoxl_GetZ(iIdx), nFrame) = iValue; - break; - case MRI_LONG: - MRILseq_vox(iData, xVoxl_GetX(iIdx), xVoxl_GetY(iIdx), xVoxl_GetZ(iIdx), nFrame) = iValue; - break; - case MRI_FLOAT: - MRIFseq_vox(iData, xVoxl_GetX(iIdx), xVoxl_GetY(iIdx), xVoxl_GetZ(iIdx), nFrame) = iValue; - break; - case MRI_SHORT: - MRISseq_vox(iData, xVoxl_GetX(iIdx), xVoxl_GetY(iIdx), xVoxl_GetZ(iIdx), nFrame) = iValue; - break; - default: - break; - } -} - -#endif /* FUND_USE_MACROS */ - -void FunD_GetSigma_(mriFunctionalDataRef this, xVoxelRef iFuncIdx, int inTimePoint, float *oSigma) -{ - int nFrame = 0; - - FunD_GetSigmaFrameNumber(inTimePoint, &nFrame); - - switch (this->mpData->type) { - case MRI_UCHAR: - *oSigma = MRIseq_vox(this->mpData, xVoxl_GetX(iFuncIdx), xVoxl_GetY(iFuncIdx), xVoxl_GetZ(iFuncIdx), nFrame); - break; - case MRI_INT: - *oSigma = MRIIseq_vox(this->mpData, xVoxl_GetX(iFuncIdx), xVoxl_GetY(iFuncIdx), xVoxl_GetZ(iFuncIdx), nFrame); - break; - case MRI_LONG: - *oSigma = MRILseq_vox(this->mpData, xVoxl_GetX(iFuncIdx), xVoxl_GetY(iFuncIdx), xVoxl_GetZ(iFuncIdx), nFrame); - break; - case MRI_FLOAT: - *oSigma = MRIFseq_vox(this->mpData, xVoxl_GetX(iFuncIdx), xVoxl_GetY(iFuncIdx), xVoxl_GetZ(iFuncIdx), nFrame); - break; - case MRI_SHORT: - *oSigma = MRISseq_vox(this->mpData, xVoxl_GetX(iFuncIdx), xVoxl_GetY(iFuncIdx), xVoxl_GetZ(iFuncIdx), nFrame); - break; - default: - *oSigma = 0; - break; - } -} - -FunD_tErr FunD_Verify(mriFunctionalDataRef this) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - // DebugEnterFunction( ("FunD_Verify( this=%p )", this) ); - - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - DebugAssertThrowX((FunD_kSignature == this->mSignature), eResult, FunD_tErr_InvalidSignature); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - // DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_VerifyFuncIdx_(mriFunctionalDataRef this, xVoxelRef iFuncIdx) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugAssertThrowX((NULL != this && NULL != iFuncIdx), eResult, FunD_tErr_InvalidParameter); - - DebugAssertThrowX((xVoxl_GetFloatX(iFuncIdx) >= 0 && xVoxl_GetFloatX(iFuncIdx) < this->mpData->width && - xVoxl_GetFloatY(iFuncIdx) >= 0 && xVoxl_GetFloatY(iFuncIdx) < this->mpData->height && - xVoxl_GetFloatZ(iFuncIdx) >= 0 && xVoxl_GetFloatZ(iFuncIdx) < this->mpData->depth), - eResult, - FunD_tErr_InvalidFunctionalVoxel); - - DebugCatch; - // DebugCatchError( eResult, FunD_tErr_NoError, FunD_GetErrorString ); - EndDebugCatch; - - return eResult; -} - -FunD_tErr FunD_VerifyTimePoint(mriFunctionalDataRef this, int iTimePoint) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_VerifyTimePoint( this=%p, iTimePoint=%p )", this, iTimePoint)); - - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Checking time point bounds")); - DebugAssertThrowX((iTimePoint >= 0 && iTimePoint < this->mNumTimePoints), eResult, FunD_tErr_InvalidTimePoint); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -FunD_tErr FunD_VerifyCondition(mriFunctionalDataRef this, int iCondition) -{ - FunD_tErr eResult = FunD_tErr_NoError; - - DebugEnterFunction(("FunD_VerifyTimePoint( this=%p, iCondition=%p )", this, iCondition)); - - DebugAssertThrowX((NULL != this), eResult, FunD_tErr_InvalidParameter); - - DebugNote(("Checking condition bounds")); - DebugAssertThrowX((iCondition >= 0 && iCondition < this->mNumConditions), eResult, FunD_tErr_InvalidConditionIndex); - - DebugCatch; - DebugCatchError(eResult, FunD_tErr_NoError, FunD_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} diff --git a/utils/mriHeadPointList.c b/utils/mriHeadPointList.c deleted file mode 100644 index 2c07f9a0a4b..00000000000 --- a/utils/mriHeadPointList.c +++ /dev/null @@ -1,1150 +0,0 @@ -/** - * @file mriHeadPointList.c - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.11 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "mriHeadPointList.h" -#include -#include -#include - -char *HPtL_ksaErrorStrings[HPtL_knNumErrorCodes] = { - - "No error.", - "Invalid object.", - "Invalid parameter.", - "Invalid signature.", - "Allocation failed.", - "Error opening or finding head point file.", - "Error parsing head point file.", - "Error opening or finding transform file.", - "Error parsing transform file.", - "Error creating transform object.", - "Error accessing client transform object.", - "Couldn't access transform.", - "Last point.", - "Invalid error code."}; - -HPtL_tErr HPtL_New(mriHeadPointListRef *oList, char *isListName, char *isTransformName, MATRIX *iClientTransform) -{ - mriHeadPointListRef this = NULL; - HPtL_tErr eResult = HPtL_tErr_NoErr; - - DebugEnterFunction( - ("Hptl_New( oList=%p, isListName=%s, isTransformName=%s " - "iClientTransform=%p )", - oList, - isListName, - isTransformName, - iClientTransform)); - - /* check for valid params */ - DebugNote(("Checking parameters")); - if (NULL == isListName) { - eResult = HPtL_tErr_InvalidParameter; - goto error; - } - - /* allocate us */ - DebugNote(("Allocating us")); - this = (mriHeadPointListRef)malloc(sizeof(mriHeadPointList)); - if (NULL == this) { - eResult = HPtL_tErr_AllocationFailed; - goto error; - } - - /* set signature */ - this->mSignature = HPtL_kSignature; - - /* set stuff to initial values */ - DebugNote(("Initializing member variables")); - strcpy(this->msPointFile, ""); - this->maPoints = NULL; - this->mnNumPoints = 0; - this->mTransform = NULL; - this->mnCurPoint = 0; - - /* transform name could be null */ - if (NULL != isTransformName) { - DebugNote(("Initializing transform file name to empty string")); - strcpy(this->msTransformFile, ""); - } - - /* read in the head list file */ - DebugNote(("Reading head point file")); - eResult = HPtL_ReadHeadListFile_(this, isListName); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* read in the transform file. makes a transform object for us with - the clients transform as aras->a and the transform file as the - b->ras */ - DebugNote(("Creating transform file")); - eResult = HPtL_CreateTransform_(this, isTransformName, iClientTransform); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* convert all our points to client space */ - DebugNote(("Converting points into client space")); - eResult = HPtL_ConvertListToClientSpace_(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* set current point to the beginning */ - this->mnCurPoint = 0; - - /* return us */ - *oList = this; - - DebugCatch; - DebugCatchError(eResult, HPtL_tErr_NoErr, HPtL_GetErrorString); - - if (NULL != this) { - free(this); - } - - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -HPtL_tErr HPtL_Delete(mriHeadPointListRef *iopList) -{ - mriHeadPointListRef this = NULL; - HPtL_tErr eResult = HPtL_tErr_NoErr; - - /* check the param. */ - if (NULL == iopList) { - eResult = HPtL_tErr_InvalidParameter; - goto error; - } - - /* get and verify us. */ - this = *iopList; - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* delete our point storage */ - if (NULL != this->maPoints) { - free(this->maPoints); - } - - /* mangle sig */ - this->mSignature = 0x1; - - /* delete us. */ - free(this); - - /* return nil */ - *iopList = NULL; - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_Delete: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_ReadHeadListFile_(mriHeadPointListRef this, char *isListName) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - FILE *file = NULL; - char sLine[1024] = ""; - int nNumPoints = 0; - HPtL_tHeadPoint *aStorage = NULL; - int nPoint = 0; - tBoolean bGood = FALSE; - char sPointLabel[256] = ""; - int nPointIndex = 0; - float fPointX = 0; - float fPointY = 0; - float fPointZ = 0; - - /* try to open the file */ - file = fopen(isListName, "r"); - if (NULL == file) { - eResult = HPtL_tErr_ErrorOpeningHeadPointFile; - goto error; - } - - /* scan it and count the number of points */ - nNumPoints = 0; - while (1) /* !feof( file ) ) */ - { - if (!fgets(sLine, 1024, file) && ferror(file)) { - break; - } - if (feof(file)) // wow read too much. break - { - break; - } - nNumPoints++; - } - - /* allocate storage */ - aStorage = (HPtL_tHeadPoint *)calloc(nNumPoints, sizeof(HPtL_tHeadPoint)); - if (NULL == aStorage) { - eResult = HPtL_tErr_AllocationFailed; - goto error; - } - - /* for each point */ - rewind(file); - for (nPoint = 0; nPoint < nNumPoints; nPoint++) { - /* read and parse line */ - if (!fgets(sLine, 1024, file) && ferror(file)) { - fprintf(stdout, "ERROR (mriHeadPointList.c): reading file.\n"); - break; - } - bGood = sscanf(sLine, "%s %d %f %f %f", sPointLabel, &nPointIndex, &fPointX, &fPointY, &fPointZ); - if (!bGood) { - eResult = HPtL_tErr_ErrorParsingHeadPointFile; - fprintf(stdout, "ERROR: Error parsing head point file %s on line %d.\n", isListName, nPoint); - goto error; - } - - /* set the data */ - strcpy(aStorage[nPoint].msLabel, sPointLabel); - aStorage[nPoint].mnIndex = nPointIndex; - xVoxl_SetFloat(&aStorage[nPoint].mPoint, fPointX, fPointY, fPointZ); - } - - /* save the file name, number of points, and storage */ - if (NULL != this->maPoints) { - free(this->maPoints); - } - this->maPoints = aStorage; - this->mnNumPoints = nNumPoints; - strcpy(this->msPointFile, isListName); - - goto cleanup; - -error: - - if (NULL != aStorage) { - free(aStorage); - } - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_ReadHeadListFile_: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - if (NULL != file) { - fclose(file); - } - - return eResult; -} - -HPtL_tErr HPtL_CreateTransform_(mriHeadPointListRef this, char *isTransformName, MATRIX *iClientTransform) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - char sTransformName[256] = ""; - char *psSuffix = NULL; - Trns_tErr eTransform = Trns_tErr_NoErr; - mriTransformRef transform = NULL; - FILE *file = NULL; - MATRIX *mTmp = NULL; - MATRIX *clientTransformI = NULL; - int nRow = 0; - int nCol = 0; - float fValue = 0; - tBoolean bGood = FALSE; - - DebugEnterFunction( - ("HPtL_CreateTransform_( this=%p, isTransformName=%s, " - "iClientTransform=%p", - this, - isTransformName, - iClientTransform)); - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* create a new transform */ - DebugNote(("Creating transform")); - eTransform = Trns_New(&transform); - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_AllocationFailed; - goto error; - } - - /* if we don't have a transform name, grab the head points file name - and replace the suffix with .trans */ - if (NULL == isTransformName) { - DebugNote(("Creating transform name. Copying point name")); - strcpy(sTransformName, this->msPointFile); - DebugNote(("Creating transform name. Finding .hpts")); - psSuffix = strstr(sTransformName, ".hpts"); - if (NULL != psSuffix) { - DebugNote(("Creating transform name. Replacing .hpts with .trans")); - strcpy(psSuffix, ".trans"); - } - else { - eResult = HPtL_tErr_InvalidParameter; - goto error; - } - } - else { - DebugNote(("Copying transform name")); - strcpy(sTransformName, isTransformName); - } - - /* try to open the transform file */ - DebugNote(("Opening transform file %s", sTransformName)); - file = fopen(sTransformName, "r"); - if (NULL == file) { - eResult = HPtL_tErr_ErrorOpeningTransformFile; - goto error; - } - - /* create a new matrix */ - DebugNote(("Allocating matrix")); - mTmp = MatrixAlloc(4, 4, MATRIX_REAL); - MatrixClear(mTmp); - - /* read in the transform file */ - DebugNote(("Reading matrix from file")); - for (nRow = 1; nRow <= 4; nRow++) { - for (nCol = 1; nCol <= 4; nCol++) { - bGood = fscanf(file, "%f", &fValue); - if (!bGood) { - eResult = HPtL_tErr_ErrorParsingTransformFile; - goto error; - } - - *MATRIX_RELT(mTmp, nRow, nCol) = fValue; - } - } - - /* copy the matrix into b->ras */ - DebugNote(("Copying matrix to BtoRAS transform")); - eTransform = Trns_CopyBtoRAS(transform, mTmp); - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorCreatingTransform; - goto error; - } - - /* if there is a client matrix.. */ - if (NULL != iClientTransform) { - /* copy it in as our aras->a. We have to invert it and copy it in - as a->ras */ - DebugNote(("Inverting client transform")); - clientTransformI = MatrixInverse(iClientTransform, NULL); - if (clientTransformI) { - DebugNote(("Copying client transform invert")); - eTransform = Trns_CopyAtoRAS(transform, clientTransformI); - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorCreatingTransform; - goto error; - } - } - } - - /* use an identity matrix as our a->b */ - DebugNote(("Making identity matrix")); - MatrixIdentity(4, mTmp); - DebugNote(("Copying identity matrix to ARAStoBRAS")); - eTransform = Trns_CopyARAStoBRAS(transform, mTmp); - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorCreatingTransform; - goto error; - } - - /* set our matrix and transform name */ - if (NULL != this->mTransform) { - DebugNote(("Deleting existring transform")); - Trns_Delete(&this->mTransform); - } - this->mTransform = transform; - DebugNote(("Copying transform name")); - strcpy(this->msTransformFile, sTransformName); - - DebugCatch; - DebugCatchError(eResult, HPtL_tErr_NoErr, HPtL_GetErrorString); - - if (NULL != transform) { - DebugNote(("Deleting transform")); - Trns_Delete(&transform); - } - - EndDebugCatch; - - if (NULL != file) { - DebugNote(("Closing file")); - fclose(file); - } - - if (NULL != mTmp) { - DebugNote(("Deleting matrix")); - MatrixFree(&mTmp); - } - - if (NULL != clientTransformI) { - DebugNote(("Deleting client transform inverse")); - MatrixFree(&clientTransformI); - } - - DebugExitFunction; - - return eResult; -} - -HPtL_tErr HPtL_ConvertListToClientSpace_(mriHeadPointListRef this) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - HPtL_tHeadPointRef pHeadPt = NULL; - - DebugEnterFunction(("HPtL_ConvertListToClientSpace_( this=%p )", this)); - - /* reset the iterator */ - DebugNote(("Resetting iterator")); - eResult = HPtL_ResetIterator(this, HPtL_tIterationPlane_All, 0, 0); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - DebugNote(("Starting loop")); - while ((eResult = HPtL_NextPoint(this, &pHeadPt)) == HPtL_tErr_NoErr) { - /* first scale the point up */ - DebugNote(("Multiplying point %.2f, %.2f, %.2f by 1000", xVoxl_ExpandFloat(&(pHeadPt->mPoint)))); - xVoxl_SetFloat(&(pHeadPt->mClientPoint), - xVoxl_GetFloatX(&(pHeadPt->mPoint)), - xVoxl_GetFloatY(&(pHeadPt->mPoint)), - xVoxl_GetFloatZ(&(pHeadPt->mPoint))); - - /* run the transform */ - DebugNote(("Transforming point %.2f, %.2f, %.2f to client space", xVoxl_ExpandFloat(&(pHeadPt->mClientPoint)))); - Trns_ConvertBtoA(this->mTransform, &(pHeadPt->mClientPoint), &(pHeadPt->mClientPoint)); - } - - if (eResult != HPtL_tErr_LastPoint) { - goto error; - } - - /* clear error */ - eResult = HPtL_tErr_NoErr; - - DebugCatch; - DebugCatchError(eResult, HPtL_tErr_NoErr, HPtL_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -HPtL_tErr HPtL_WriteTransform(mriHeadPointListRef this, char *isDest) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - char sTransform[256] = ""; - MATRIX *mTmp = NULL; - MATRIX *mARAStoBRAS = NULL; - MATRIX *mBRAStoARAS = NULL; - MATRIX *mBtoRAS = NULL; - FILE *file = NULL; - int nRow = 0; - int nCol = 0; - float fValue = 0; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* if null arg, use saved transform name */ - if (NULL == isDest) { - strcpy(sTransform, this->msTransformFile); - } - else { - strcpy(sTransform, isDest); - } - - /* get our matrices */ - Trns_GetARAStoBRAS(this->mTransform, &mARAStoBRAS); - Trns_GetBtoRAS(this->mTransform, &mBtoRAS); - - /* we actually want BRAS->ARAS to invert it */ - mBRAStoARAS = MatrixInverse(mARAStoBRAS, NULL); - - /* compose the BRAStoARAS and BtoRAS matrices */ - mTmp = MatrixMultiply(mBRAStoARAS, mBtoRAS, NULL); - - /* attempt to open the file */ - file = fopen(sTransform, "w"); - if (NULL == file) { - eResult = HPtL_tErr_ErrorOpeningTransformFile; - goto error; - } - - /* write the transform file */ - for (nRow = 1; nRow <= 4; nRow++) { - for (nCol = 1; nCol <= 4; nCol++) { - fValue = *MATRIX_RELT(mTmp, nRow, nCol); - fprintf(file, "%f ", fValue); - } - fprintf(file, "\n"); - } - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_WriteTransform: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - if (NULL != mTmp) { - MatrixFree(&mTmp); - } - if (NULL != mBRAStoARAS) { - MatrixFree(&mBRAStoARAS); - } - - if (NULL != file) { - fclose(file); - } - - return eResult; -} - -HPtL_tErr HPtL_WriteHeadPointFile(mriHeadPointListRef this, char *isDest) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - char sFilename[256] = ""; - FILE *file = NULL; - int nHeadPt = 0; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* if null arg, use saved name */ - if (NULL == isDest) { - strcpy(sFilename, this->msPointFile); - } - else { - strcpy(sFilename, isDest); - } - /* attempt to open the file */ - file = fopen(sFilename, "w"); - if (NULL == file) { - eResult = HPtL_tErr_ErrorOpeningHeadPointFile; - goto error; - } - - /* write the list */ - for (nHeadPt = 0; nHeadPt < this->mnNumPoints; nHeadPt++) { - /* write the point to the file.*/ - fprintf(file, - "%s %d %f %f %f\n", - this->maPoints[nHeadPt].msLabel, - this->maPoints[nHeadPt].mnIndex, - xVoxl_ExpandFloat(&(this->maPoints[nHeadPt].mPoint))); - } - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_WriteHeadPointFile: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - if (NULL != file) { - fclose(file); - } - - return eResult; -} - -HPtL_tErr HPtL_ResetIterator(mriHeadPointListRef this, - HPtL_tIterationPlane iPlane, - float ifPlaneNumber, - float ifPlaneRange) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* save iteration desires */ - this->mIterPlane = iPlane; - this->mfIterPlaneNumber = ifPlaneNumber; - this->mfIterPlaneRange = ifPlaneRange; - - /* set cur point to -1 */ - this->mnCurPoint = -1; - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_ResetIterator: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_NextPoint(mriHeadPointListRef this, HPtL_tHeadPointRef *opPoint) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - HPtL_tHeadPointRef point = NULL; - tBoolean bGoodPoint = FALSE; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* while we haven't found a good point */ - bGoodPoint = FALSE; - while (!bGoodPoint && this->mnCurPoint < this->mnNumPoints) { - /* get the next point */ - this->mnCurPoint++; - point = &(this->maPoints[this->mnCurPoint]); - - /* check it */ - switch (this->mIterPlane) { - case HPtL_tIterationPlane_X: - if (abs(xVoxl_GetFloatX(&(point->mClientPoint)) - this->mfIterPlaneNumber) <= this->mfIterPlaneRange) { - bGoodPoint = TRUE; - } - break; - case HPtL_tIterationPlane_Y: - if (abs(xVoxl_GetFloatY(&(point->mClientPoint)) - this->mfIterPlaneNumber) <= this->mfIterPlaneRange) { - bGoodPoint = TRUE; - } - break; - case HPtL_tIterationPlane_Z: - if (abs(xVoxl_GetFloatZ(&(point->mClientPoint)) - this->mfIterPlaneNumber) <= this->mfIterPlaneRange) { - bGoodPoint = TRUE; - } - break; - case HPtL_tIterationPlane_All: - bGoodPoint = TRUE; - break; - default: - break; - } - } - - if (this->mnCurPoint >= this->mnNumPoints) { - eResult = HPtL_tErr_LastPoint; - goto cleanup; - } - - /* return the point */ - *opPoint = point; - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_NextPoint: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_FindNearestPoint(mriHeadPointListRef this, - HPtL_tIterationPlane iPlane, - float ifPlaneRange, - xVoxelRef iWhere, - HPtL_tHeadPointRef *opPoint) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - float fPlane = 0; - HPtL_tHeadPointRef pPoint = NULL; - float fDistance = 0; - HPtL_tHeadPointRef pNearestPoint = NULL; - float fNearestDistance = 0; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* get the plane we're looking on */ - switch (iPlane) { - case HPtL_tIterationPlane_X: - fPlane = xVoxl_GetFloatX(iWhere); - break; - case HPtL_tIterationPlane_Y: - fPlane = xVoxl_GetFloatY(iWhere); - break; - case HPtL_tIterationPlane_Z: - fPlane = xVoxl_GetFloatZ(iWhere); - break; - case HPtL_tIterationPlane_All: - /* no range necessary */ - break; - default: - eResult = HPtL_tErr_InvalidParameter; - goto error; - } - - /* set the iterator */ - eResult = HPtL_ResetIterator(this, iPlane, fPlane, ifPlaneRange); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* for every point... */ - fNearestDistance = 999; - while ((eResult = HPtL_NextPoint(this, &pPoint)) == HPtL_tErr_NoErr) { - /* calc the distance in client space don't bother square rooting - because we don't care about the real distance */ - fDistance = pow(xVoxl_GetFloatX(&(pPoint->mClientPoint)) - xVoxl_GetFloatX(iWhere), 2) + - pow(xVoxl_GetFloatY(&(pPoint->mClientPoint)) - xVoxl_GetFloatY(iWhere), 2) + - pow(xVoxl_GetFloatZ(&(pPoint->mClientPoint)) - xVoxl_GetFloatZ(iWhere), 2); - - /* if less than min so far, save it */ - if (fDistance < fNearestDistance) { - fNearestDistance = fDistance; - pNearestPoint = pPoint; - } - } - - if (eResult != HPtL_tErr_LastPoint) { - goto error; - } - - /* clear error */ - eResult = HPtL_tErr_NoErr; - - /* return found point */ - *opPoint = pNearestPoint; - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_FindNearestPoint: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_FindFlattenedNearestPoint(mriHeadPointListRef this, - HPtL_tIterationPlane iPlane, - xVoxelRef iWhere, - HPtL_tHeadPointRef *opPoint) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - float fDistance = 0; - HPtL_tHeadPointRef pNearestPoint = NULL; - float fNearestDistance = 0; - HPtL_tHeadPointRef point = NULL; - int nCurPoint = 0; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* for every point... */ - fNearestDistance = 999; - for (nCurPoint = 0; nCurPoint < this->mnNumPoints; nCurPoint++) { - /* get the point */ - point = &(this->maPoints[nCurPoint]); - - /* calc the distance in 2D client space don't bother square rooting - because we don't care about the real distance. we're comparing - 2D points so switch on the plane to see which 2 coords we should - look at. */ - switch (iPlane) { - case HPtL_tIterationPlane_X: - fDistance = pow(xVoxl_GetFloatY(&(point->mClientPoint)) - xVoxl_GetFloatY(iWhere), 2) + - pow(xVoxl_GetFloatZ(&(point->mClientPoint)) - xVoxl_GetFloatZ(iWhere), 2); - break; - case HPtL_tIterationPlane_Y: - fDistance = pow(xVoxl_GetFloatX(&(point->mClientPoint)) - xVoxl_GetFloatX(iWhere), 2) + - pow(xVoxl_GetFloatZ(&(point->mClientPoint)) - xVoxl_GetFloatZ(iWhere), 2); - break; - case HPtL_tIterationPlane_Z: - fDistance = pow(xVoxl_GetFloatX(&(point->mClientPoint)) - xVoxl_GetFloatX(iWhere), 2) + - pow(xVoxl_GetFloatY(&(point->mClientPoint)) - xVoxl_GetFloatY(iWhere), 2); - break; - default: - eResult = HPtL_tErr_InvalidParameter; - goto error; - } - - /* if less than min so far, save it */ - if (fDistance < fNearestDistance) { - fNearestDistance = fDistance; - pNearestPoint = point; - } - } - - /* return found point */ - *opPoint = pNearestPoint; - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_FindFlattenedNearestPoint: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_RestoreTransform(mriHeadPointListRef this) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - Trns_tErr eTransform = Trns_tErr_NoErr; - MATRIX *mTransform = NULL; - - mTransform = MatrixIdentity(4, NULL); - - /* set the transform again */ - eTransform = Trns_CopyARAStoBRAS(this->mTransform, mTransform); - - /* reconvert all the points */ - eResult = HPtL_ConvertListToClientSpace_(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorAccessingTransform; - } - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_RestoreTransform: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - if (NULL != mTransform) { - MatrixFree(&mTransform); - } - - return eResult; -} - -HPtL_tErr HPtL_ApplyTransform(mriHeadPointListRef this, MATRIX *iTransform) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - Trns_tErr eTransform = Trns_tErr_NoErr; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - if (NULL == iTransform) { - eResult = HPtL_tErr_InvalidParameter; - goto error; - } - - /* apply the transform */ - eTransform = Trns_ApplyTransform(this->mTransform, iTransform); - if (Trns_tErr_NoErr != eTransform) { - goto error; - } - - /* reconvert all the points */ - eResult = HPtL_ConvertListToClientSpace_(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorAccessingTransform; - } - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_ApplyTransform: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_Translate(mriHeadPointListRef this, float ifDistance, tAxis iAxis) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - Trns_tErr eTransform = Trns_tErr_NoErr; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* translate by the inverse */ - eTransform = Trns_Translate(this->mTransform, -ifDistance, iAxis); - if (Trns_tErr_NoErr != eTransform) { - goto error; - } - - /* reconvert all the points */ - eResult = HPtL_ConvertListToClientSpace_(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorAccessingTransform; - } - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_Translate: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_Rotate(mriHeadPointListRef this, float ifDegrees, tAxis iAxis) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - Trns_tErr eTransform = Trns_tErr_NoErr; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* rotate by the inverse */ - eTransform = Trns_Rotate(this->mTransform, -ifDegrees, iAxis); - if (Trns_tErr_NoErr != eTransform) { - goto error; - } - - /* reconvert all the points */ - eResult = HPtL_ConvertListToClientSpace_(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorAccessingTransform; - } - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_Rotate: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_Scale(mriHeadPointListRef this, float ifFactor, tAxis iAxis) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - Trns_tErr eTransform = Trns_tErr_NoErr; - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* scale by the inverse */ - eTransform = Trns_Scale(this->mTransform, 1.0 / ifFactor, iAxis); - if (Trns_tErr_NoErr != eTransform) { - goto error; - } - - /* reconvert all the points */ - eResult = HPtL_ConvertListToClientSpace_(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - if (Trns_tErr_NoErr != eTransform) { - eResult = HPtL_tErr_ErrorAccessingTransform; - } - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_Scale: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -HPtL_tErr HPtL_AlignPointToClientVoxel(mriHeadPointListRef this, HPtL_tHeadPointRef iPoint, xVoxelRef iClientVox) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - xVoxel destPt; - xVoxel srcPt; - float fDeltaX = 0; - float fDeltaY = 0; - float fDeltaZ = 0; - MATRIX *mTranslation = NULL; - - if (NULL == iPoint || NULL == iClientVox) { - eResult = HPtL_tErr_InvalidParameter; - goto error; - } - - eResult = HPtL_Verify(this); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - /* convert the client vox and our head pt to ras */ - Trns_ConvertBtoRAS(this->mTransform, &(iPoint->mPoint), &srcPt); - Trns_ConvertAtoRAS(this->mTransform, iClientVox, &destPt); - - /* get the x,y, and z difference */ - fDeltaX = xVoxl_GetFloatX(&destPt) - xVoxl_GetFloatX(&srcPt); - fDeltaY = xVoxl_GetFloatY(&destPt) - xVoxl_GetFloatY(&srcPt); - fDeltaZ = xVoxl_GetFloatZ(&destPt) - xVoxl_GetFloatZ(&srcPt); - - DebugPrint( - ("ana dest: %d %d %d local src %.2f %.2f %.2f\n" - "ras dest %.2f %.2f %.2f ras src %.2f %.2f %.2f " - "delta %.2f %.2f %.2f\n", - xVoxl_ExpandInt(iClientVox), - xVoxl_ExpandFloat(&(iPoint->mPoint)), - xVoxl_ExpandFloat(&destPt), - xVoxl_ExpandFloat(&srcPt), - fDeltaX, - fDeltaY, - fDeltaZ)); - - /* create a trans matrix */ - mTranslation = MatrixIdentity(4, NULL); - *MATRIX_RELT(mTranslation, 1, 4) = fDeltaX; - *MATRIX_RELT(mTranslation, 2, 4) = fDeltaY; - *MATRIX_RELT(mTranslation, 3, 4) = fDeltaZ; - - DebugPrint(("Align:\n")); - MatrixPrint(stderr, mTranslation); - - /* apply it */ - eResult = HPtL_ApplyTransform(this, mTranslation); - if (HPtL_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - if (HPtL_tErr_NoErr != eResult) { - DebugPrint(("Error %d in HPtL_AlignPointToClientVoxel: %s\n", eResult, HPtL_GetErrorString(eResult))); - } - -cleanup: - - if (NULL != mTranslation) { - MatrixFree(&mTranslation); - } - - return eResult; -} - -HPtL_tErr HPtL_Verify(mriHeadPointListRef this) -{ - HPtL_tErr eResult = HPtL_tErr_NoErr; - - /* check for null ptr */ - if (NULL == this) { - eResult = HPtL_tErr_InvalidObject; - goto cleanup; - } - - /* check signature */ - if (HPtL_kSignature != this->mSignature) { - eResult = HPtL_tErr_InvalidSignature; - goto cleanup; - } - -cleanup: - - return eResult; -} - -char *HPtL_GetErrorString(HPtL_tErr ieCode) -{ - HPtL_tErr eCode = ieCode; - - if (ieCode < 0 || ieCode >= HPtL_knNumErrorCodes) { - eCode = HPtL_tErr_InvalidErrorCode; - } - - return HPtL_ksaErrorStrings[eCode]; -} diff --git a/utils/mriSurface.c b/utils/mriSurface.c deleted file mode 100644 index e054be188b4..00000000000 --- a/utils/mriSurface.c +++ /dev/null @@ -1,1382 +0,0 @@ -/** - * @file mriSurface.c - * @brief surface utils - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: fischl $ - * $Date: 2011/03/16 17:31:48 $ - * $Revision: 1.39 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "error.h" - -#include "mriSurface.h" - -char *Surf_ksaErrorStrings[Surf_knNumErrorCodes] = { - - "No error.", - "Invalid pointer to object.", - "Invalid paramter.", - "Invalid signature.", - "Memory allocation failed.", - "Error loading surface (MRISread).", - "Error loading vertex set.", - "Error loading annotation.", - "Error accessing surface.", - "Last face.", - "Last vertex.", - "Invalid error code."}; - -char *Surf_ksaVertexSets[Surf_knNumVertexSets] = {"main", "original", "pial"}; - -static xVoxel sTmpVertex; - -Surf_tErr Surf_New(mriSurfaceRef *opSurface, char *isFileName) -{ - mriSurfaceRef this = NULL; - Surf_tErr eResult = Surf_tErr_NoErr; - mriTransformRef transform = NULL; - MATRIX *identity = NULL; - - /* allocate us */ - this = (mriSurfaceRef)malloc(sizeof(mriSurface)); - if (NULL == this) { - eResult = Surf_tErr_AllocationFailed; - goto error; - } - - /* set the signature */ - this->mSignature = Surf_kSignature; - - /* read in the main surface */ - this->mSurface = MRISread(isFileName); - if (NULL == (this->mSurface)) { - eResult = Surf_tErr_ErrorLoadingSurface; - goto error; - } - - /* set longest face to nothing */ - this->mfLongestEdge = 0; - - /* set the loaded flags */ - this->mabVertexSetLoaded[Surf_tVertexSet_Main] = TRUE; - this->mabVertexSetLoaded[Surf_tVertexSet_Original] = FALSE; - this->mabVertexSetLoaded[Surf_tVertexSet_Pial] = FALSE; - this->mabVertexSetConverted[Surf_tVertexSet_Main] = FALSE; - this->mabVertexSetConverted[Surf_tVertexSet_Original] = FALSE; - this->mabVertexSetConverted[Surf_tVertexSet_Pial] = FALSE; - - /* init iterators */ - this->mnCurFace = 0; - this->mnCurVertex = 0; - - /* allocate our faces */ - this->maFaces = (Surf_tFaceRef)calloc(this->mSurface->nfaces, sizeof(Surf_tFace)); - if (NULL == this->maFaces) { - eResult = Surf_tErr_AllocationFailed; - goto error; - } - - /* save the file name. */ - this->msFileName = strdup(isFileName); - - /* Start with identity transform. */ - identity = MatrixIdentity(4, NULL); - Trns_New(&transform); - Trns_CopyAtoRAS(transform, identity); - Trns_CopyBtoRAS(transform, identity); - Trns_CopyARAStoBRAS(transform, identity); - Surf_SetTransform(this, transform); - - /* return us. */ - *opSurface = this; - - goto cleanup; - -error: - - if (NULL != this->mSurface) { - MRISfree(&this->mSurface); - } - - if (NULL != this) { - free(this); - } - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_New: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - if (NULL != transform) { - Trns_Delete(&transform); - } - - return eResult; -} - -Surf_tErr Surf_Delete(mriSurfaceRef *iopSurface) -{ - mriSurfaceRef this = NULL; - Surf_tErr eResult = Surf_tErr_NoErr; - - if (NULL == iopSurface) { - eResult = Surf_tErr_InvalidParameter; - goto error; - } - - /* get and verify us */ - this = *iopSurface; - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* free surface */ - MRISfree(&(this->mSurface)); - - /* free faces */ - free(this->maFaces); - - /* free file name */ - free(this->msFileName); - - /* mangle signature */ - this->mSignature = 0x1; - - /* free us */ - free(this); - - /* return null */ - *iopSurface = NULL; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_Delete: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_SetTransform(mriSurfaceRef this, mriTransformRef iTransform) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* copy the transformation */ - Trns_DeepClone(iTransform, &this->mTransform); - - /* Clear our converted flags. */ - this->mabVertexSetConverted[Surf_tVertexSet_Main] = FALSE; - this->mabVertexSetConverted[Surf_tVertexSet_Original] = FALSE; - this->mabVertexSetConverted[Surf_tVertexSet_Pial] = FALSE; - - /* convert our surface */ - Surf_ConvertSurfaceToClientSpace_(this, Surf_tVertexSet_Main); - if (this->mabVertexSetLoaded[Surf_tVertexSet_Pial]) { - Surf_ConvertSurfaceToClientSpace_(this, Surf_tVertexSet_Pial); - } - if (this->mabVertexSetLoaded[Surf_tVertexSet_Original]) { - Surf_ConvertSurfaceToClientSpace_(this, Surf_tVertexSet_Original); - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_SetTransform: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_LoadVertexSet(mriSurfaceRef this, char *isName, Surf_tVertexSet iSet) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - int eMRIS = NO_ERROR; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* save current vertex set to tmp */ - MRISsaveVertexPositions(this->mSurface, TMP_VERTICES); - - /* read in the vertices */ - eMRIS = MRISreadVertexPositions(this->mSurface, isName); - if (eMRIS != NO_ERROR) { - /* restore the vertices */ - MRISrestoreVertexPositions(this->mSurface, TMP_VERTICES); - eResult = Surf_tErr_ErrorLoadingVertexSet; - goto error; - } - - /* save them to the correct position and restore the vertices from - temp if necessary. */ - switch (iSet) { - case Surf_tVertexSet_Main: - /* do nothing here, leave the vertices we just read in in the main - position */ - break; - case Surf_tVertexSet_Original: - MRISsaveVertexPositions(this->mSurface, ORIG_VERTICES); - MRISrestoreVertexPositions(this->mSurface, TMP_VERTICES); - break; - case Surf_tVertexSet_Pial: - MRISsaveVertexPositions(this->mSurface, CANONICAL_VERTICES); - MRISrestoreVertexPositions(this->mSurface, TMP_VERTICES); - break; - default: - eResult = Surf_tErr_InvalidParameter; - goto error; - } - - /* conert this set */ - this->mabVertexSetConverted[iSet] = FALSE; - Surf_ConvertSurfaceToClientSpace_(this, iSet); - - /* set load status flag */ - this->mabVertexSetLoaded[iSet] = TRUE; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_LoadVertexSet: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_WriteValues(mriSurfaceRef this, char *isFileName) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - int vno; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - for (vno = 0; vno < this->mSurface->nvertices; vno++) { - if (this->mSurface->vertices[vno].val != 0) { - fprintf(stderr, "vertex %d = %.2f\n", vno, this->mSurface->vertices[vno].val); - } - } - - /* Write the val field */ - MRISwriteValues(this->mSurface, isFileName); - printf("Surface values written to %s.\n", isFileName); - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_WriteValueSet: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_IsVertexSetLoaded(mriSurfaceRef this, Surf_tVertexSet iSet, tBoolean *obIsLoaded) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* return flag */ - *obIsLoaded = this->mabVertexSetLoaded[iSet]; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_IsVertexSetLoaded: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_LoadAnnotation(mriSurfaceRef this, char *isFileName) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - int eMRIS = NO_ERROR; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* read in the annotation */ - eMRIS = MRISreadAnnotation(this->mSurface, isFileName); - if (eMRIS != NO_ERROR) { - /* restore the vertices */ - eResult = Surf_tErr_ErrorLoadingAnnotation; - goto error; - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_LoadAnnotation: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_IsInternalColorTablePresent(mriSurfaceRef this, tBoolean *obPresent) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Return whether or not we have a ct. */ - *obPresent = (this->mSurface->ct != NULL); - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_IsInternalColorTablePresent: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_NewColorTableFromInternal(mriSurfaceRef this, COLOR_TABLE **opTable) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - COLOR_TABLE *colorTable = NULL; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Make a COPY our ct, if we have one. */ - if (this->mSurface->ct) { - colorTable = CTABdeepCopy(this->mSurface->ct); - if (NULL == colorTable) { - goto error; - } - - *opTable = colorTable; - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_NewColorTableFromInternal: %s\n", eResult, Surf_GetErrorString(eResult))); - } - if (NULL == colorTable) { - DebugPrint(("Error in CTABdeepCopy: Couldn't copy color table\n")); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_ConvertSurfaceToClientSpace_(mriSurfaceRef this, Surf_tVertexSet iSet) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - int nFaceIdx = 0; - face_type *face = NULL; - Surf_tFaceRef localFace = NULL; - int nVertexIdx = 0; - int nNeighborVertexIdx = 0; - vertex_type *vertex = NULL; - vertex_type *neighborVertex = NULL; - xVoxelRef localVox = NULL; - float dx = 0; - float dy = 0; - float dz = 0; - float fDistance = 0; - - if (this->mabVertexSetConverted[iSet]) { - goto cleanup; - } - - for (nFaceIdx = 0; nFaceIdx < this->mSurface->nfaces; nFaceIdx++) { - face = &(this->mSurface->faces[nFaceIdx]); - localFace = &(this->maFaces[nFaceIdx]); - - for (nVertexIdx = 0; nVertexIdx < VERTICES_PER_FACE; nVertexIdx++) { - vertex = &(this->mSurface->vertices[face->v[nVertexIdx]]); - localVox = &(localFace->mVoxel[(int)iSet][nVertexIdx]); - - /* copy the vertex into the voxel. also set the index in the face. */ - Surf_ConvertVertexToVoxel(vertex, iSet, this->mTransform, localVox); - localFace->mnVertexIndex[(int)iSet][nVertexIdx] = face->v[nVertexIdx]; - - /* get the next vertex */ - nNeighborVertexIdx = nVertexIdx == 0 ? VERTICES_PER_FACE - 1 : nVertexIdx - 1; - neighborVertex = &(this->mSurface->vertices[face->v[nNeighborVertexIdx]]); - - /* calc the distance */ - dx = (Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_X) - - Surf_GetVertexCoord(neighborVertex, iSet, Surf_tOrientation_X)); - dy = (Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_Y) - - Surf_GetVertexCoord(neighborVertex, iSet, Surf_tOrientation_Y)); - dz = (Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_Z) - - Surf_GetVertexCoord(neighborVertex, iSet, Surf_tOrientation_Z)); - fDistance = sqrt(dx * dx + dy * dy + dz * dz); - - /* if longer than the longest edge, set it */ - if (fDistance > this->mfLongestEdge) { - this->mfLongestEdge = fDistance; - } - } - - if (!(nFaceIdx % 1000)) { - fprintf(stdout, - "\rConverting %s surface: %.2f%% done", - Surf_ksaVertexSets[iSet], - ((float)nFaceIdx / (float)this->mSurface->nfaces) * 100.0); - } - } - - fprintf(stdout, "\rConverting %s surface: 100%% done. \n", Surf_ksaVertexSets[iSet]); - - this->mabVertexSetConverted[iSet] = TRUE; - - goto cleanup; - - goto error; -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_ConvertSurfaceToClientSpace_: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_SetIteratorPosition(mriSurfaceRef this, xVoxelRef iPlane) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* see what orientation we're in and save the plane */ - if (xVoxl_GetFloatX(iPlane) != 0) { - this->mIterOrientation = Surf_tOrientation_X; - this->mfIterPlane = xVoxl_GetFloatX(iPlane); - } - else if (xVoxl_GetFloatY(iPlane) != 0) { - this->mIterOrientation = Surf_tOrientation_Y; - this->mfIterPlane = xVoxl_GetFloatY(iPlane); - } - else if (xVoxl_GetFloatZ(iPlane) != 0) { - this->mIterOrientation = Surf_tOrientation_Z; - this->mfIterPlane = xVoxl_GetFloatZ(iPlane); - } - - /* right now just start on first face */ - this->mnCurFace = -1; - this->mnCurVertex = -1; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_SetIteratorPosition: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_GetNextAndNeighborVertex(mriSurfaceRef this, - Surf_tVertexSet iSet, - xVoxelRef oNextVoxel, - int *onNextIndex, - xVoxelRef oNeighborVoxel, - int *onNeighborIndex) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - tBoolean bFaceFound = FALSE; - Surf_tFaceRef face = NULL; - float fVertexPlane = 0; - int nNeighborVertex = 0; - xVoxelRef vertex = NULL; - xVoxelRef neighborVertex = NULL; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* if vertex is -1, search for next face. */ - if (-1 == this->mnCurVertex) { - this->mnCurFace++; - if (this->mnCurFace >= this->mSurface->nfaces) { - eResult = Surf_tErr_LastFace; - goto cleanup; - } - - bFaceFound = FALSE; - while (this->mnCurFace < this->mSurface->nfaces && !bFaceFound) { - /* get the face and the first vertex on the face. */ - face = &(this->maFaces[this->mnCurFace]); - vertex = &(face->mVoxel[iSet][0]); - - /* get the plane it's on relative to our iteration orientation */ - switch (this->mIterOrientation) { - case Surf_tOrientation_X: - fVertexPlane = xVoxl_GetFloatX(vertex); - break; - case Surf_tOrientation_Y: - fVertexPlane = xVoxl_GetFloatY(vertex); - break; - case Surf_tOrientation_Z: - fVertexPlane = xVoxl_GetFloatZ(vertex); - break; - default: - eResult = Surf_tErr_InvalidObject; - goto error; - } - - /* get the distance from the vertex to the iteration plane. if it's - less than some amount, use this face. */ - if (fabs(fVertexPlane - this->mfIterPlane) <= this->mfLongestEdge) { - bFaceFound = TRUE; - } - else { - this->mnCurFace++; - } - } - - /* if not found, we're at the last face. */ - if (this->mnCurFace >= this->mSurface->nfaces) { - eResult = Surf_tErr_LastFace; - goto cleanup; - } - - /* now we have a face to check. set the vertex to 0. */ - this->mnCurVertex = 0; - } - - /* get the current face. */ - face = &(this->maFaces[this->mnCurFace]); - - /* get the index of the last vertex. */ - nNeighborVertex = this->mnCurVertex - 1; - if (nNeighborVertex < 0) { - nNeighborVertex = VERTICES_PER_FACE - 1; - } - - /* get this vertex and the last one */ - vertex = &(face->mVoxel[iSet][this->mnCurVertex]); - neighborVertex = &(face->mVoxel[iSet][nNeighborVertex]); - - /* copy them out */ - xVoxl_Copy(oNextVoxel, vertex); - xVoxl_Copy(oNeighborVoxel, neighborVertex); - - /* if they want the indices, copy those too. */ - if (NULL != onNextIndex) { - *onNextIndex = face->mnVertexIndex[iSet][this->mnCurVertex]; - } - if (NULL != onNeighborIndex) { - *onNeighborIndex = face->mnVertexIndex[iSet][nNeighborVertex]; - } - - /* inc current vertex. if out of bounds, set to -1. will look for new - face next time. return Surf_tErr_LastVertex to let the client know - that this is the last vertex in the face. */ - this->mnCurVertex++; - if (this->mnCurVertex >= VERTICES_PER_FACE) { - this->mnCurVertex = -1; - eResult = Surf_tErr_LastVertex; - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetNextAndNeighborVertex: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_CopyGeometryInformation(mriSurfaceRef this, VOL_GEOM *ioVolumeGeometry) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - DebugEnterFunction( - ("Surf_CopyGeometryInformation( this=%p, " - "ioVolumeGeometry=%p )", - this, - ioVolumeGeometry)); - - DebugNote(("Verifying volume")); - eResult = Surf_Verify(this); - DebugAssertThrow((eResult == Surf_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != ioVolumeGeometry), eResult, Surf_tErr_InvalidParameter); - - /* Copy the information out. */ - memmove(ioVolumeGeometry, &(this->mSurface->vg), sizeof(VOL_GEOM)); - - DebugCatch; - DebugCatchError(eResult, Surf_tErr_NoErr, Surf_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Surf_tErr Surf_TransformToVolumeGeometry(mriSurfaceRef this, VOL_GEOM *iVolumeGeometry) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - int eMRIS = ERROR_NONE; - MRI *mri = NULL; - - DebugEnterFunction( - ("Surf_TransformToVolumeGeometry( this=%p, " - "iVolumeGeometry=%p )", - this, - iVolumeGeometry)); - - DebugNote(("Verifying volume")); - eResult = Surf_Verify(this); - DebugAssertThrow((eResult == Surf_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != iVolumeGeometry), eResult, Surf_tErr_InvalidParameter); - - /* Make a fake MRI from the volume geometry we got. */ - DebugNote(("Allocting fake header.")); - mri = MRIallocHeader( - iVolumeGeometry->width, iVolumeGeometry->height, iVolumeGeometry->depth, MRI_VOLUME_TYPE_UNKNOWN, 1); - DebugAssertThrowX((NULL != mri), eResult, Surf_tErr_AllocationFailed); - - /* Copy geometry information to the fake MRI. */ - DebugNote(("Putting geometry in fake header with useVolGeomToMRI.")); - useVolGeomToMRI(iVolumeGeometry, mri); - - /* Do the transform. */ - DebugNote(("Running MRISsurf2surf")); - eMRIS = MRISsurf2surf(this->mSurface, mri, NULL); - DebugAssertThrowX((ERROR_NONE == eMRIS), eResult, Surf_tErr_ErrorAccesssingSurface); - - /* Since that changes the vertex positions, reconvert our client - space cache. Clear our converted flags first. */ - this->mabVertexSetConverted[Surf_tVertexSet_Main] = FALSE; - this->mabVertexSetConverted[Surf_tVertexSet_Original] = FALSE; - this->mabVertexSetConverted[Surf_tVertexSet_Pial] = FALSE; - - Surf_ConvertSurfaceToClientSpace_(this, Surf_tVertexSet_Main); - if (this->mabVertexSetLoaded[Surf_tVertexSet_Pial]) { - Surf_ConvertSurfaceToClientSpace_(this, Surf_tVertexSet_Pial); - } - if (this->mabVertexSetLoaded[Surf_tVertexSet_Original]) { - Surf_ConvertSurfaceToClientSpace_(this, Surf_tVertexSet_Original); - } - - DebugCatch; - DebugCatchError(eResult, Surf_tErr_NoErr, Surf_GetErrorString); - EndDebugCatch; - - if (NULL != mri) { - MRIfree(&mri); - } - - DebugExitFunction; - - return eResult; -} - -Surf_tErr Surf_GetNthVertex( - mriSurfaceRef this, Surf_tVertexSet iSet, int inIndex, xVoxelRef oVoxel, char *osDescription) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - vertex_type *vertex = NULL; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* verify the index */ - if (inIndex < 0 || inIndex >= this->mSurface->nvertices) { - eResult = Surf_tErr_InvalidParameter; - goto error; - } - - /* grab the voxel */ - vertex = &(this->mSurface->vertices[inIndex]); - if (NULL == vertex) { - eResult = Surf_tErr_ErrorAccesssingSurface; - goto error; - } - - /* get the voxel in client space */ - Surf_ConvertVertexToVoxel(vertex, iSet, this->mTransform, oVoxel); - - /* make a string of info if they want it */ - if (NULL != osDescription) { - sprintf(osDescription, - "RAS Coords: %.2f %.2f %.2f", - Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_X), - Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_Y), - Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_Z)); - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetNthVertex: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_GetClosestVertexVoxel( - mriSurfaceRef this, Surf_tVertexSet iSet, xVoxelRef iClientVoxel, xVoxelRef oClientVoxel, char *osDescription) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - xVoxel surfaceVoxel; - vertex_type *vertex = NULL; - int nIndex = 0; - float fDistance = 0; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* since we want to return results with the vertex index, it is better - to search for the closest vertex in the surface space, not in client - space. so convert the target point to surface space */ - Surf_ConvertVoxelToSurfaceSpace(iClientVoxel, this->mTransform, &surfaceVoxel); - - /* get the closest vertex. */ - Surf_GetClosestVertex(this, iSet, &surfaceVoxel, &vertex, &nIndex, &fDistance); - - /* convert it to client space */ - Surf_ConvertVertexToVoxel(vertex, iSet, this->mTransform, oClientVoxel); - - /* make a string of info */ - if (NULL != osDescription) { - sprintf(osDescription, - "Index: %d Distance: %.2f RAS Coords: %.2f %.2f %.2f", - nIndex, - fDistance, - Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_X), - Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_Y), - Surf_GetVertexCoord(vertex, iSet, Surf_tOrientation_Z)); - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetClosestVertex: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -float Surf_GetVertexCoord(vertex_type *iVertex, Surf_tVertexSet iSet, Surf_tOrientation iOrientation) -{ - switch (iSet) { - case Surf_tVertexSet_Main: - switch (iOrientation) { - case Surf_tOrientation_X: - return iVertex->x; - break; - case Surf_tOrientation_Y: - return iVertex->y; - break; - case Surf_tOrientation_Z: - return iVertex->z; - break; - default: - return -1; - } - break; - case Surf_tVertexSet_Original: - switch (iOrientation) { - case Surf_tOrientation_X: - return iVertex->origx; - break; - case Surf_tOrientation_Y: - return iVertex->origy; - break; - case Surf_tOrientation_Z: - return iVertex->origz; - break; - default: - return -1; - } - break; - case Surf_tVertexSet_Pial: - switch (iOrientation) { - case Surf_tOrientation_X: - return iVertex->cx; - break; - case Surf_tOrientation_Y: - return iVertex->cy; - break; - case Surf_tOrientation_Z: - return iVertex->cz; - break; - default: - return -1; - } - break; - default: - return -1; - } - return -1; -} - -Surf_tErr Surf_SetVertexValue( - mriSurfaceRef this, Surf_tVertexSet iVertexSet, Surf_tValueSet iValueSet, xVoxelRef iClientVoxel, float iValue) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - xVoxel surfaceVoxel; - VERTEX *vertex = NULL; - int nVno = 0; - float fDistance = 0; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Get the closest vertex to this voxel. First get the voxel in - surface space, then find the closest vertex. */ - Surf_ConvertVoxelToSurfaceSpace(iClientVoxel, this->mTransform, &surfaceVoxel); - Surf_GetClosestVertex(this, iVertexSet, &surfaceVoxel, &vertex, &nVno, &fDistance); - if (NULL == vertex) { - eResult = Surf_tErr_ErrorAccesssingSurface; - goto error; - } - - /* Now set the value in the vertex. */ - switch (iValueSet) { - case Surf_tValueSet_Val: - vertex->val = iValue; - fprintf(stderr, - "vertex %d (%.2f,%.2f,%.2f, d=%.2f) set to %.2f\n", - nVno, - vertex->x, - vertex->y, - vertex->z, - fDistance, - iValue); - break; - default: - return Surf_tErr_InvalidParameter; - break; - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_SetVertexValue: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_GetVertexValue( - mriSurfaceRef this, Surf_tVertexSet iVertexSet, Surf_tValueSet iValueSet, xVoxelRef iClientVoxel, float *opValue) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - xVoxel surfaceVoxel; - VERTEX *vertex = NULL; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Get the closest vertex to this voxel. First get the voxel in - surface space, then find the closest vertex. */ - Surf_ConvertVoxelToSurfaceSpace(iClientVoxel, this->mTransform, &surfaceVoxel); - Surf_GetClosestVertex(this, iVertexSet, &surfaceVoxel, &vertex, NULL, NULL); - if (NULL == vertex) { - eResult = Surf_tErr_ErrorAccesssingSurface; - goto error; - } - - /* Now get the value in the vertex. */ - switch (iValueSet) { - case Surf_tValueSet_Val: - *opValue = vertex->val; - break; - default: - return Surf_tErr_InvalidParameter; - break; - } - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetVertexValue: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_GetVertexAnnotationByIndex(mriSurfaceRef this, int iVertexIndex, int *oAnnotation) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Verify the index. */ - if (iVertexIndex < 0 || iVertexIndex >= this->mSurface->nvertices) { - eResult = Surf_tErr_InvalidParameter; - goto error; - } - - /* Return the annotation value. */ - *oAnnotation = this->mSurface->vertices[iVertexIndex].annotation; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetVertexAnnotationByIndex: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_GetDistance(mriSurfaceRef this, xVoxelRef iClientVoxel1, xVoxelRef iClientVoxel2, float *ofDistance) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - xVoxel surfaceVoxel1; - xVoxel surfaceVoxel2; - float fDistanceX = 0; - float fDistanceY = 0; - float fDistanceZ = 0; - float fDistance; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Get both voxels in surface space, then calc the distance. */ - Surf_ConvertVoxelToSurfaceSpace(iClientVoxel1, this->mTransform, &surfaceVoxel1); - Surf_ConvertVoxelToSurfaceSpace(iClientVoxel2, this->mTransform, &surfaceVoxel2); - - fDistanceX = xVoxl_GetFloatX(&surfaceVoxel1) - xVoxl_GetFloatX(&surfaceVoxel2); - fDistanceY = xVoxl_GetFloatY(&surfaceVoxel1) - xVoxl_GetFloatY(&surfaceVoxel2); - fDistanceZ = xVoxl_GetFloatZ(&surfaceVoxel1) - xVoxl_GetFloatZ(&surfaceVoxel2); - - fDistance = sqrt(fDistanceX * fDistanceX + fDistanceY * fDistanceY + fDistanceZ * fDistanceZ); - - /* return the distance. */ - *ofDistance = fDistance; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetVertexValue: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_GetMRIS(mriSurfaceRef this, MRIS **opSurface) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* pass back the surface. */ - *opSurface = this->mSurface; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetMRIS: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_GetSurfaceSetName(Surf_tVertexSet iSet, char *osName) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - if (iSet < 0 || iSet >= Surf_knNumVertexSets || NULL == osName) { - eResult = Surf_tErr_InvalidParameter; - goto error; - } - - strcpy(osName, Surf_ksaVertexSets[iSet]); - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_GetSurfaceSetName: %s\n", eResult, Surf_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -Surf_tErr Surf_UsesRealRAS(mriSurfaceRef this, tBoolean *obUseRealRAS) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Return the useRealRAS flag. */ - *obUseRealRAS = this->mSurface->useRealRAS; - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_UsesRealRAS: %s\n", eResult, Surf_GetErrorString(eResult))); - } -cleanup: - - return eResult; -} - -Surf_tErr Surf_AverageVertexPositions(mriSurfaceRef this, int inNumAverages) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - int eMRIS = NO_ERROR; - - eResult = Surf_Verify(this); - if (Surf_tErr_NoErr != eResult) { - goto error; - } - - /* Call the MRIS function. */ - eMRIS = MRISaverageVertexPositions(this->mSurface, inNumAverages); - if (NO_ERROR != eMRIS) { - goto error; - } - - /* Since that changes the vertex positions, reconvert our client - space cache. */ - Surf_ConvertSurfaceToClientSpace_(this, Surf_tVertexSet_Main); - - goto cleanup; - -error: - - if (Surf_tErr_NoErr != eResult) { - DebugPrint(("Error %d in Surf_AverageVertexPositions: %s\n", eResult, Surf_GetErrorString(eResult))); - } - - if (NO_ERROR != eMRIS) { - DebugPrint(("Error %d (from MRIS) in Surf_AverageVertexPositions\n", eMRIS)); - } - -cleanup: - - return eResult; -} - -void Surf_GetClosestVertex(mriSurfaceRef this, - Surf_tVertexSet iSet, - xVoxelRef iSurfaceVoxel, - vertex_type **opVertex, - int *onIndex, - float *ofDistance) -{ - vertex_type *currentVertex = NULL; - int nVertex = 0; - int nBestVertex = -1; - float dx = 0; - float dy = 0; - float dz = 0; - float fDistance = 0; - float fLowestDistance = 0; - - /* start high */ - fLowestDistance = 256 * 256 * 256; - - /* for every vertex... */ - for (nVertex = 0; nVertex < this->mSurface->nvertices; nVertex++) { - /* get the vertex */ - currentVertex = &(this->mSurface->vertices[nVertex]); - - /* calc distance */ - dx = xVoxl_GetFloatX(iSurfaceVoxel) - Surf_GetVertexCoord(currentVertex, iSet, Surf_tOrientation_X); - dy = xVoxl_GetFloatY(iSurfaceVoxel) - Surf_GetVertexCoord(currentVertex, iSet, Surf_tOrientation_Y); - dz = xVoxl_GetFloatZ(iSurfaceVoxel) - Surf_GetVertexCoord(currentVertex, iSet, Surf_tOrientation_Z); - fDistance = dx * dx + dy * dy + dz * dz; - - /* save the lowest */ - if (fDistance < fLowestDistance) { - fLowestDistance = fDistance; - nBestVertex = nVertex; - } - } - - if (-1 == nBestVertex) { - goto error; - } - - /* get the best vertex and convert it to client space */ - *opVertex = &(this->mSurface->vertices[nBestVertex]); - - /* return the index if they want it. */ - if (NULL != onIndex) { - *onIndex = nBestVertex; - } - - /* find and return the real distance if they want it. */ - if (NULL != ofDistance) { - *ofDistance = sqrt(fLowestDistance); - } - - goto cleanup; - -error: - - *opVertex = NULL; - -cleanup: - - return; -} - -void Surf_ConvertVertexToVoxel(vertex_type *iVertex, Surf_tVertexSet iSet, mriTransformRef iTransform, xVoxelRef oVoxel) -{ - /* if we don't have a transform, just copy vertex into voxel */ - if (NULL == iTransform) { - oVoxel->mfX = ((iSet == Surf_tVertexSet_Main) ? iVertex->x - : (iSet == Surf_tVertexSet_Original) ? iVertex->origx : iVertex->cx); - oVoxel->mfY = ((iSet == Surf_tVertexSet_Main) ? iVertex->y - : (iSet == Surf_tVertexSet_Original) ? iVertex->origy : iVertex->cy); - oVoxel->mfZ = ((iSet == Surf_tVertexSet_Main) ? iVertex->z - : (iSet == Surf_tVertexSet_Original) ? iVertex->origz : iVertex->cz); -#if 0 - xVoxl_SetFloat( oVoxel, - Surf_GetVertexCoord( iVertex, iSet, Surf_tOrientation_X ), - Surf_GetVertexCoord( iVertex, iSet, Surf_tOrientation_Y ), - Surf_GetVertexCoord( iVertex, iSet, Surf_tOrientation_Z )); -#endif - } - else { -/* stuff the vertex into a voxel */ -#if 0 - xVoxl_SetFloat( &sTmpVertex, - Surf_GetVertexCoord( iVertex, iSet, Surf_tOrientation_X ), - Surf_GetVertexCoord( iVertex, iSet, Surf_tOrientation_Y ), - Surf_GetVertexCoord( iVertex, iSet, Surf_tOrientation_Z )); -#endif - - sTmpVertex.mfX = - ((iSet == Surf_tVertexSet_Main) ? iVertex->x - : (iSet == Surf_tVertexSet_Original) ? iVertex->origx : iVertex->cx); - sTmpVertex.mfY = - ((iSet == Surf_tVertexSet_Main) ? iVertex->y - : (iSet == Surf_tVertexSet_Original) ? iVertex->origy : iVertex->cy); - sTmpVertex.mfZ = - ((iSet == Surf_tVertexSet_Main) ? iVertex->z - : (iSet == Surf_tVertexSet_Original) ? iVertex->origz : iVertex->cz); - - /* transform voxel */ - // Trns_ConvertBtoA(iTransform, &sTmpVertex, oVoxel); - Trns_ConvertBRAStoB(iTransform, &sTmpVertex, oVoxel); -#if 0 - printf("vertex: (%.2f, %.2f, %.2f), localVox: (%.2f, %.2f, %.2f)\n", - sTmpVertex.mfX, sTmpVertex.mfY, sTmpVertex.mfZ, - oVoxel->mfX, oVoxel->mfY, oVoxel->mfZ); -#endif - } -} - -void Surf_ConvertVoxelToSurfaceSpace(xVoxelRef iVoxel, mriTransformRef iTransform, xVoxelRef oSurfVox) -{ -#if 0 - static MATRIX * BtoRAS = NULL; - static MATRIX * tmp1 = NULL; - static MATRIX * tmp2 = NULL; -#endif - - /* if we don't have a transform, just copy vertex into voxel */ - if (NULL == iTransform) { - xVoxl_Copy(oSurfVox, iVoxel); - } - else { - /* transform voxel */ - /* RKT: In the opposite of this function, CovertVertexToVoxel, we - use CovertBRAStoB, so we'll use ConvertBtoRAS here. Even though - at some point we should probably fix this. */ - // Trns_ConvertAtoB( iTransform, iVoxel, oSurfVox ); - Trns_ConvertBtoRAS(iTransform, iVoxel, oSurfVox); - -#if 0 - /* RKT: This doesn't work because tkmedit.c messes with the BtoRAS - of the conversion matrix, so we'll calc it here manually. */ - /* RKT: Somehow I got it working with needing to calc a new - BtoRAS. */ - if ( NULL == BtoRAS ) - { - BtoRAS = MatrixInverse( iTransform->mRAStoB, NULL ); - tmp1 = MatrixAlloc( 4, 1, MATRIX_REAL ); - tmp2 = MatrixAlloc( 4, 1, MATRIX_REAL ); - - DebugPrint(("iTransform->mBtoRAS\n")); - MatrixPrint(stderr,iTransform->mBtoRAS); - DebugPrint(("calc'd BtoRAS\n")); - MatrixPrint(stderr,BtoRAS); - } - - *MATRIX_RELT(tmp1,1,1) = xVoxl_GetFloatX( iVoxel ); - *MATRIX_RELT(tmp1,2,1) = xVoxl_GetFloatY( iVoxel ); - *MATRIX_RELT(tmp1,3,1) = xVoxl_GetFloatZ( iVoxel ); - *MATRIX_RELT(tmp1,4,1) = 1.0; - - MatrixMultiply( BtoRAS, tmp1, tmp2 ); - - xVoxl_SetFloat( oSurfVox, - *MATRIX_RELT(tmp2,1,1), - *MATRIX_RELT(tmp2,2,1), - *MATRIX_RELT(tmp2,3,1) ); -#endif - } -} - -Surf_tErr Surf_Verify(mriSurfaceRef this) -{ - Surf_tErr eResult = Surf_tErr_NoErr; - - /* check for null ptr */ - if (NULL == this) { - eResult = Surf_tErr_InvalidObject; - goto cleanup; - } - - /* check signature */ - if (Surf_kSignature != this->mSignature) { - eResult = Surf_tErr_InvalidSignature; - goto cleanup; - } - -cleanup: - - return eResult; -} - -char *Surf_GetErrorString(Surf_tErr ieCode) -{ - Surf_tErr eCode = ieCode; - - if (ieCode < 0 || ieCode >= Surf_knNumErrorCodes) { - eCode = Surf_tErr_InvalidErrorCode; - } - - return Surf_ksaErrorStrings[eCode]; -} diff --git a/utils/mriTransform.c b/utils/mriTransform.cpp similarity index 68% rename from utils/mriTransform.c rename to utils/mriTransform.cpp index c029d626b66..43f72a31205 100644 --- a/utils/mriTransform.c +++ b/utils/mriTransform.cpp @@ -30,8 +30,7 @@ #include "mriTransform.h" -char *Trns_ksaErrorStrings[Trns_knNumErrorCodes] = { - +const char *Trns_ksaErrorStrings[Trns_knNumErrorCodes] = { "No error.", "Invalid pointer to object.", "Invalid signature.", @@ -44,34 +43,34 @@ char *Trns_ksaErrorStrings[Trns_knNumErrorCodes] = { Trns_tErr Trns_New(mriTransformRef *opTransform) { Trns_tErr eResult = Trns_tErr_NoErr; - mriTransformRef this = NULL; + mriTransformRef ref = NULL; /* allocate us */ - this = (mriTransformRef)malloc(sizeof(mriTransform)); - if (NULL == this) { + ref = (mriTransformRef)malloc(sizeof(mriTransform)); + if (NULL == ref) { eResult = Trns_tErr_AllocationFailed; goto error; } /* set signature */ - this->mSignature = Trns_kSignature; + ref->mSignature = Trns_kSignature; /* set our matrices to null. */ - this->mAtoRAS = NULL; - this->mBtoRAS = NULL; - this->mARAStoBRAS = NULL; - this->mRAStoA = NULL; - this->mRAStoB = NULL; - this->mBRAStoARAS = NULL; - this->mAtoB = NULL; - this->mBtoA = NULL; + ref->mAtoRAS = NULL; + ref->mBtoRAS = NULL; + ref->mARAStoBRAS = NULL; + ref->mRAStoA = NULL; + ref->mRAStoB = NULL; + ref->mBRAStoARAS = NULL; + ref->mAtoB = NULL; + ref->mBtoA = NULL; /* allocate our temp matricies */ - this->mCoord1 = MatrixAlloc(4, 1, MATRIX_REAL); - this->mCoord2 = MatrixAlloc(4, 1, MATRIX_REAL); + ref->mCoord1 = MatrixAlloc(4, 1, MATRIX_REAL); + ref->mCoord2 = MatrixAlloc(4, 1, MATRIX_REAL); /* return us. */ - *opTransform = this; + *opTransform = ref; goto cleanup; @@ -89,52 +88,52 @@ Trns_tErr Trns_New(mriTransformRef *opTransform) Trns_tErr Trns_NewFromLTA(mriTransformRef *opTransform, char *isLTAFileName) { Trns_tErr eResult = Trns_tErr_NoErr; - mriTransformRef this = NULL; + mriTransformRef ref = NULL; LTA *LTATransform = NULL; MATRIX *identity = NULL; /* allocate us */ - this = (mriTransformRef)malloc(sizeof(mriTransform)); - if (NULL == this) { + ref = (mriTransformRef)malloc(sizeof(mriTransform)); + if (NULL == ref) { eResult = Trns_tErr_AllocationFailed; goto error; } /* set signature */ - this->mSignature = Trns_kSignature; + ref->mSignature = Trns_kSignature; /* set our matrices to null. */ - this->mAtoRAS = NULL; - this->mBtoRAS = NULL; - this->mARAStoBRAS = NULL; - this->mRAStoA = NULL; - this->mRAStoB = NULL; - this->mBRAStoARAS = NULL; - this->mAtoB = NULL; - this->mBtoA = NULL; + ref->mAtoRAS = NULL; + ref->mBtoRAS = NULL; + ref->mARAStoBRAS = NULL; + ref->mRAStoA = NULL; + ref->mRAStoB = NULL; + ref->mBRAStoARAS = NULL; + ref->mAtoB = NULL; + ref->mBtoA = NULL; /* try to read a transform and make sure we got it */ DebugNote(("Trying to read transform file %s", isLTAFileName)); LTATransform = LTAreadEx(isLTAFileName); DebugAssertThrowX((NULL != LTATransform), eResult, Trns_tErr_LTAImportFailed); - this->type = LTATransform->type; /* if RAS will be converted + ref->type = LTATransform->type; /* if RAS will be converted to voxel later */ /* copy the matrix out of it */ - Trns_CopyARAStoBRAS(this, LTATransform->xforms[0].m_L); + Trns_CopyARAStoBRAS(ref, LTATransform->xforms[0].m_L); /* copy identities for the rest */ identity = MatrixIdentity(4, NULL); - Trns_CopyAtoRAS(this, identity); - Trns_CopyBtoRAS(this, identity); + Trns_CopyAtoRAS(ref, identity); + Trns_CopyBtoRAS(ref, identity); /* allocate our temp matricies */ - this->mCoord1 = MatrixAlloc(4, 1, MATRIX_REAL); - this->mCoord2 = MatrixAlloc(4, 1, MATRIX_REAL); + ref->mCoord1 = MatrixAlloc(4, 1, MATRIX_REAL); + ref->mCoord2 = MatrixAlloc(4, 1, MATRIX_REAL); /* return us. */ - *opTransform = this; + *opTransform = ref; goto cleanup; @@ -160,51 +159,51 @@ Trns_tErr Trns_NewFromLTA(mriTransformRef *opTransform, char *isLTAFileName) Trns_tErr Trns_Delete(mriTransformRef *iopTransform) { Trns_tErr eResult = Trns_tErr_NoErr; - mriTransformRef this = NULL; + mriTransformRef ref = NULL; /* get us. */ - this = *iopTransform; + ref = *iopTransform; /* verify us. */ - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* delete any matricies we have. */ - if (NULL != this->mAtoRAS) { - MatrixFree(&(this->mAtoRAS)); + if (NULL != ref->mAtoRAS) { + MatrixFree(&(ref->mAtoRAS)); } - if (NULL != this->mBtoRAS) { - MatrixFree(&(this->mBtoRAS)); + if (NULL != ref->mBtoRAS) { + MatrixFree(&(ref->mBtoRAS)); } - if (NULL != this->mARAStoBRAS) { - MatrixFree(&(this->mARAStoBRAS)); + if (NULL != ref->mARAStoBRAS) { + MatrixFree(&(ref->mARAStoBRAS)); } - if (NULL != this->mRAStoA) { - MatrixFree(&(this->mRAStoA)); + if (NULL != ref->mRAStoA) { + MatrixFree(&(ref->mRAStoA)); } - if (NULL != this->mRAStoB) { - MatrixFree(&(this->mRAStoB)); + if (NULL != ref->mRAStoB) { + MatrixFree(&(ref->mRAStoB)); } - if (NULL != this->mBRAStoARAS) { - MatrixFree(&(this->mBRAStoARAS)); + if (NULL != ref->mBRAStoARAS) { + MatrixFree(&(ref->mBRAStoARAS)); } - if (NULL != this->mAtoB) { - MatrixFree(&(this->mAtoB)); + if (NULL != ref->mAtoB) { + MatrixFree(&(ref->mAtoB)); } - if (NULL != this->mBtoA) { - MatrixFree(&(this->mBtoA)); + if (NULL != ref->mBtoA) { + MatrixFree(&(ref->mBtoA)); } - MatrixFree(&(this->mCoord1)); - MatrixFree(&(this->mCoord2)); + MatrixFree(&(ref->mCoord1)); + MatrixFree(&(ref->mCoord2)); /* trash our sig */ - this->mSignature = 0x1; + ref->mSignature = 0x1; /* delete us */ - free(this); - this = NULL; + free(ref); + ref = NULL; /* return null. */ *iopTransform = NULL; @@ -222,12 +221,12 @@ Trns_tErr Trns_Delete(mriTransformRef *iopTransform) return eResult; } -Trns_tErr Trns_DeepClone(mriTransformRef this, mriTransformRef *opTransform) +Trns_tErr Trns_DeepClone(mriTransformRef ref, mriTransformRef *opTransform) { Trns_tErr eResult = Trns_tErr_NoErr; mriTransformRef clone = NULL; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -239,14 +238,14 @@ Trns_tErr Trns_DeepClone(mriTransformRef this, mriTransformRef *opTransform) } /* copy any of our matrices that are defined */ - if (NULL != this->mAtoRAS) { - Trns_CopyAtoRAS(clone, this->mAtoRAS); + if (NULL != ref->mAtoRAS) { + Trns_CopyAtoRAS(clone, ref->mAtoRAS); } - if (NULL != this->mBtoRAS) { - Trns_CopyBtoRAS(clone, this->mBtoRAS); + if (NULL != ref->mBtoRAS) { + Trns_CopyBtoRAS(clone, ref->mBtoRAS); } - if (NULL != this->mARAStoBRAS) { - Trns_CopyARAStoBRAS(clone, this->mARAStoBRAS); + if (NULL != ref->mARAStoBRAS) { + Trns_CopyARAStoBRAS(clone, ref->mARAStoBRAS); } /* return the clone. */ @@ -265,20 +264,20 @@ Trns_tErr Trns_DeepClone(mriTransformRef this, mriTransformRef *opTransform) return eResult; } -Trns_tErr Trns_CopyAtoRAS(mriTransformRef this, MATRIX *iAtoRAS) +Trns_tErr Trns_CopyAtoRAS(mriTransformRef ref, MATRIX *iAtoRAS) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } - /* create a copy of this matrix */ - this->mAtoRAS = MatrixCopy(iAtoRAS, NULL); + /* create a copy of ref matrix */ + ref->mAtoRAS = MatrixCopy(iAtoRAS, NULL); /* calc the rest of our matricies */ - eResult = Trns_CalcMatricies_(this); + eResult = Trns_CalcMatricies_(ref); if (eResult != Trns_tErr_NoErr) { Trns_Signal("Trns_CopyAtoRAS", __LINE__, eResult); eResult = Trns_tErr_NoErr; @@ -297,20 +296,20 @@ Trns_tErr Trns_CopyAtoRAS(mriTransformRef this, MATRIX *iAtoRAS) return eResult; } -Trns_tErr Trns_CopyBtoRAS(mriTransformRef this, MATRIX *iBtoRAS) +Trns_tErr Trns_CopyBtoRAS(mriTransformRef ref, MATRIX *iBtoRAS) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } - /* create a copy of this matrix */ - this->mBtoRAS = MatrixCopy(iBtoRAS, NULL); + /* create a copy of ref matrix */ + ref->mBtoRAS = MatrixCopy(iBtoRAS, NULL); /* calc the rest of our matricies */ - eResult = Trns_CalcMatricies_(this); + eResult = Trns_CalcMatricies_(ref); if (eResult != Trns_tErr_NoErr) { Trns_Signal("Trns_CopyBtoRAS", __LINE__, eResult); eResult = Trns_tErr_NoErr; @@ -329,20 +328,20 @@ Trns_tErr Trns_CopyBtoRAS(mriTransformRef this, MATRIX *iBtoRAS) return eResult; } -Trns_tErr Trns_CopyARAStoBRAS(mriTransformRef this, MATRIX *iARAStoBRAS) +Trns_tErr Trns_CopyARAStoBRAS(mriTransformRef ref, MATRIX *iARAStoBRAS) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } - /* create a copy of this matrix */ - this->mARAStoBRAS = MatrixCopy(iARAStoBRAS, NULL); + /* create a copy of ref matrix */ + ref->mARAStoBRAS = MatrixCopy(iARAStoBRAS, NULL); /* calc the rest of our matricies */ - eResult = Trns_CalcMatricies_(this); + eResult = Trns_CalcMatricies_(ref); if (eResult != Trns_tErr_NoErr) { Trns_Signal("Trns_CopyARAStoBRAS", __LINE__, eResult); eResult = Trns_tErr_NoErr; @@ -361,17 +360,17 @@ Trns_tErr Trns_CopyARAStoBRAS(mriTransformRef this, MATRIX *iARAStoBRAS) return eResult; } -Trns_tErr Trns_GetAtoRAS(mriTransformRef this, MATRIX **opMatrix) +Trns_tErr Trns_GetAtoRAS(mriTransformRef ref, MATRIX **opMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* return the matrix */ - *opMatrix = this->mAtoRAS; + *opMatrix = ref->mAtoRAS; goto cleanup; @@ -386,17 +385,17 @@ Trns_tErr Trns_GetAtoRAS(mriTransformRef this, MATRIX **opMatrix) return eResult; } -Trns_tErr Trns_GetBtoRAS(mriTransformRef this, MATRIX **opMatrix) +Trns_tErr Trns_GetBtoRAS(mriTransformRef ref, MATRIX **opMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* return the matrix */ - *opMatrix = this->mBtoRAS; + *opMatrix = ref->mBtoRAS; goto cleanup; @@ -411,17 +410,17 @@ Trns_tErr Trns_GetBtoRAS(mriTransformRef this, MATRIX **opMatrix) return eResult; } -Trns_tErr Trns_GetARAStoBRAS(mriTransformRef this, MATRIX **opMatrix) +Trns_tErr Trns_GetARAStoBRAS(mriTransformRef ref, MATRIX **opMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* return the matrix */ - *opMatrix = this->mARAStoBRAS; + *opMatrix = ref->mARAStoBRAS; goto cleanup; @@ -435,17 +434,17 @@ Trns_tErr Trns_GetARAStoBRAS(mriTransformRef this, MATRIX **opMatrix) return eResult; } -Trns_tErr Trns_GetAtoB(mriTransformRef this, MATRIX **opMatrix) +Trns_tErr Trns_GetAtoB(mriTransformRef ref, MATRIX **opMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* return the matrix */ - *opMatrix = this->mAtoB; + *opMatrix = ref->mAtoB; goto cleanup; @@ -459,17 +458,17 @@ Trns_tErr Trns_GetAtoB(mriTransformRef this, MATRIX **opMatrix) return eResult; } -Trns_tErr Trns_GetBtoA(mriTransformRef this, MATRIX **opMatrix) +Trns_tErr Trns_GetBtoA(mriTransformRef ref, MATRIX **opMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* return the matrix */ - *opMatrix = this->mBtoA; + *opMatrix = ref->mBtoA; goto cleanup; @@ -488,7 +487,7 @@ Trns_tErr Trns_GetBtoA(mriTransformRef this, MATRIX **opMatrix) fprintf(stderr, "%s\n", l); \ MatrixPrint(stderr, m); -Trns_tErr Trns_ApplyTransform(mriTransformRef this, MATRIX *iTransform) +Trns_tErr Trns_ApplyTransform(mriTransformRef ref, MATRIX *iTransform) { Trns_tErr eResult = Trns_tErr_NoErr; MATRIX *mTranslation = NULL; @@ -503,7 +502,7 @@ Trns_tErr Trns_ApplyTransform(mriTransformRef this, MATRIX *iTransform) MATRIX *mTmp2 = NULL; MATRIX *mNew = NULL; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -521,12 +520,12 @@ Trns_tErr Trns_ApplyTransform(mriTransformRef this, MATRIX *iTransform) mTmp2 = MatrixAlloc(4, 4, MATRIX_REAL); mNewScale = MatrixAlloc(4, 4, MATRIX_REAL); - // mp("orig",this->mARAStoBRAS); + // mp("orig",ref->mARAStoBRAS); /* get our matrix components */ - Trns_ExtractTranslationMatrix(this->mARAStoBRAS, mTranslation); - Trns_ExtractRotationMatrix(this->mARAStoBRAS, mRotation); - Trns_ExtractScaleMatrix(this->mARAStoBRAS, mScale); + Trns_ExtractTranslationMatrix(ref->mARAStoBRAS, mTranslation); + Trns_ExtractRotationMatrix(ref->mARAStoBRAS, mRotation); + Trns_ExtractScaleMatrix(ref->mARAStoBRAS, mScale); // mp("t",mTranslation); // mp("r",mRotation); // mp("s",mScale); @@ -574,7 +573,7 @@ Trns_tErr Trns_ApplyTransform(mriTransformRef this, MATRIX *iTransform) MatrixMultiply(mNewTranslation, mTmp2, mNew); /* set the new matrix */ - eResult = Trns_CopyARAStoBRAS(this, mNew); + eResult = Trns_CopyARAStoBRAS(ref, mNew); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -657,8 +656,8 @@ Trns_tErr Trns_ExtractRotationMatrix(MATRIX *iTransform, MATRIX *oRotation) *MATRIX_RELT(mTmp, 2, 4) = 0; *MATRIX_RELT(mTmp, 3, 4) = 0; - /* we want to cancel out the scale portion of this matrix. so now we'll - extract the scale matrix from this matrix */ + /* we want to cancel out the scale portion of ref matrix. so now we'll + extract the scale matrix from ref matrix */ mScale = MatrixAlloc(4, 4, MATRIX_REAL); Trns_ExtractScaleMatrix(mTmp, mScale); @@ -733,14 +732,14 @@ Trns_tErr Trns_ExtractScaleMatrix(MATRIX *iTransform, MATRIX *oScale) return Trns_tErr_NoErr; } -Trns_tErr Trns_Translate(mriTransformRef this, float ifAmount, tAxis iAxis) +Trns_tErr Trns_Translate(mriTransformRef ref, float ifAmount, tAxis iAxis) { Trns_tErr eResult = Trns_tErr_NoErr; MATRIX *mTransform = NULL; MATRIX *mOld = NULL; MATRIX *mNew = NULL; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -766,11 +765,11 @@ Trns_tErr Trns_Translate(mriTransformRef this, float ifAmount, tAxis iAxis) } /* compose the new matrix with the old one */ - MatrixCopy(this->mARAStoBRAS, mOld); + MatrixCopy(ref->mARAStoBRAS, mOld); MatrixMultiply(mOld, mTransform, mNew); /* set the new matrix */ - eResult = Trns_CopyARAStoBRAS(this, mNew); + eResult = Trns_CopyARAStoBRAS(ref, mNew); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -798,7 +797,7 @@ Trns_tErr Trns_Translate(mriTransformRef this, float ifAmount, tAxis iAxis) return eResult; } -Trns_tErr Trns_Rotate(mriTransformRef this, float ifDegrees, tAxis iAxis) +Trns_tErr Trns_Rotate(mriTransformRef ref, float ifDegrees, tAxis iAxis) { Trns_tErr eResult = Trns_tErr_NoErr; MATRIX *mTransform = NULL; @@ -806,7 +805,7 @@ Trns_tErr Trns_Rotate(mriTransformRef this, float ifDegrees, tAxis iAxis) MATRIX *mNew = NULL; float fRadians = 0; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -832,11 +831,11 @@ Trns_tErr Trns_Rotate(mriTransformRef this, float ifDegrees, tAxis iAxis) } /* compose the new matrix with the old one */ - MatrixCopy(this->mARAStoBRAS, mOld); + MatrixCopy(ref->mARAStoBRAS, mOld); MatrixMultiply(mOld, mTransform, mNew); /* set the new matrix */ - eResult = Trns_CopyARAStoBRAS(this, mNew); + eResult = Trns_CopyARAStoBRAS(ref, mNew); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -854,14 +853,14 @@ Trns_tErr Trns_Rotate(mriTransformRef this, float ifDegrees, tAxis iAxis) return eResult; } -Trns_tErr Trns_Scale(mriTransformRef this, float ifFactor, tAxis iAxis) +Trns_tErr Trns_Scale(mriTransformRef ref, float ifFactor, tAxis iAxis) { Trns_tErr eResult = Trns_tErr_NoErr; MATRIX *mTransform = NULL; MATRIX *mOld = NULL; MATRIX *mNew = NULL; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -887,11 +886,11 @@ Trns_tErr Trns_Scale(mriTransformRef this, float ifFactor, tAxis iAxis) } /* compose the new matrix with the old one */ - MatrixCopy(this->mARAStoBRAS, mOld); + MatrixCopy(ref->mARAStoBRAS, mOld); MatrixMultiply(mOld, mTransform, mNew); /* set the new matrix */ - eResult = Trns_CopyARAStoBRAS(this, mNew); + eResult = Trns_CopyARAStoBRAS(ref, mNew); if (Trns_tErr_NoErr != eResult) { goto error; } @@ -909,33 +908,33 @@ Trns_tErr Trns_Scale(mriTransformRef this, float ifFactor, tAxis iAxis) return eResult; } -Trns_tErr Trns_ConvertAtoB(mriTransformRef this, xVoxelRef iAVoxel, xVoxelRef oBVoxel) +Trns_tErr Trns_ConvertAtoB(mriTransformRef ref, xVoxelRef iAVoxel, xVoxelRef oBVoxel) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mAtoB) { + if (NULL == ref->mAtoB) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* set our coord matrix */ - *MATRIX_RELT(this->mCoord1, 1, 1) = xVoxl_GetFloatX(iAVoxel); - *MATRIX_RELT(this->mCoord1, 2, 1) = xVoxl_GetFloatY(iAVoxel); - *MATRIX_RELT(this->mCoord1, 3, 1) = xVoxl_GetFloatZ(iAVoxel); - *MATRIX_RELT(this->mCoord1, 4, 1) = 1; + *MATRIX_RELT(ref->mCoord1, 1, 1) = xVoxl_GetFloatX(iAVoxel); + *MATRIX_RELT(ref->mCoord1, 2, 1) = xVoxl_GetFloatY(iAVoxel); + *MATRIX_RELT(ref->mCoord1, 3, 1) = xVoxl_GetFloatZ(iAVoxel); + *MATRIX_RELT(ref->mCoord1, 4, 1) = 1; /* do the transform */ - MatrixMultiply(this->mAtoB, this->mCoord1, this->mCoord2); + MatrixMultiply(ref->mAtoB, ref->mCoord1, ref->mCoord2); /* set the voxel to the matrix */ xVoxl_SetFloat( - oBVoxel, *MATRIX_RELT(this->mCoord2, 1, 1), *MATRIX_RELT(this->mCoord2, 2, 1), *MATRIX_RELT(this->mCoord2, 3, 1)); + oBVoxel, *MATRIX_RELT(ref->mCoord2, 1, 1), *MATRIX_RELT(ref->mCoord2, 2, 1), *MATRIX_RELT(ref->mCoord2, 3, 1)); goto cleanup; @@ -950,35 +949,35 @@ Trns_tErr Trns_ConvertAtoB(mriTransformRef this, xVoxelRef iAVoxel, xVoxelRef oB return eResult; } -Trns_tErr Trns_ConvertAtoRAS(mriTransformRef this, xVoxelRef iAVoxel, xVoxelRef oRASVoxel) +Trns_tErr Trns_ConvertAtoRAS(mriTransformRef ref, xVoxelRef iAVoxel, xVoxelRef oRASVoxel) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mAtoRAS) { + if (NULL == ref->mAtoRAS) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* set our coord matrix */ - *MATRIX_RELT(this->mCoord1, 1, 1) = xVoxl_GetFloatX(iAVoxel); - *MATRIX_RELT(this->mCoord1, 2, 1) = xVoxl_GetFloatY(iAVoxel); - *MATRIX_RELT(this->mCoord1, 3, 1) = xVoxl_GetFloatZ(iAVoxel); - *MATRIX_RELT(this->mCoord1, 4, 1) = 1; + *MATRIX_RELT(ref->mCoord1, 1, 1) = xVoxl_GetFloatX(iAVoxel); + *MATRIX_RELT(ref->mCoord1, 2, 1) = xVoxl_GetFloatY(iAVoxel); + *MATRIX_RELT(ref->mCoord1, 3, 1) = xVoxl_GetFloatZ(iAVoxel); + *MATRIX_RELT(ref->mCoord1, 4, 1) = 1; /* do the transform */ - MatrixMultiply(this->mAtoRAS, this->mCoord1, this->mCoord2); + MatrixMultiply(ref->mAtoRAS, ref->mCoord1, ref->mCoord2); /* set the voxel to the matrix */ xVoxl_SetFloat(oRASVoxel, - *MATRIX_RELT(this->mCoord2, 1, 1), - *MATRIX_RELT(this->mCoord2, 2, 1), - *MATRIX_RELT(this->mCoord2, 3, 1)); + *MATRIX_RELT(ref->mCoord2, 1, 1), + *MATRIX_RELT(ref->mCoord2, 2, 1), + *MATRIX_RELT(ref->mCoord2, 3, 1)); goto cleanup; @@ -993,33 +992,33 @@ Trns_tErr Trns_ConvertAtoRAS(mriTransformRef this, xVoxelRef iAVoxel, xVoxelRef return eResult; } -Trns_tErr Trns_ConvertBtoA(mriTransformRef this, xVoxelRef iBVoxel, xVoxelRef oAVoxel) +Trns_tErr Trns_ConvertBtoA(mriTransformRef ref, xVoxelRef iBVoxel, xVoxelRef oAVoxel) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mBtoA) { + if (NULL == ref->mBtoA) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* set our coord matrix */ - *MATRIX_RELT(this->mCoord1, 1, 1) = xVoxl_GetFloatX(iBVoxel); - *MATRIX_RELT(this->mCoord1, 2, 1) = xVoxl_GetFloatY(iBVoxel); - *MATRIX_RELT(this->mCoord1, 3, 1) = xVoxl_GetFloatZ(iBVoxel); - *MATRIX_RELT(this->mCoord1, 4, 1) = 1; + *MATRIX_RELT(ref->mCoord1, 1, 1) = xVoxl_GetFloatX(iBVoxel); + *MATRIX_RELT(ref->mCoord1, 2, 1) = xVoxl_GetFloatY(iBVoxel); + *MATRIX_RELT(ref->mCoord1, 3, 1) = xVoxl_GetFloatZ(iBVoxel); + *MATRIX_RELT(ref->mCoord1, 4, 1) = 1; /* do the transform */ - MatrixMultiply(this->mBtoA, this->mCoord1, this->mCoord2); + MatrixMultiply(ref->mBtoA, ref->mCoord1, ref->mCoord2); /* set the voxel to the matrix */ xVoxl_SetFloat( - oAVoxel, *MATRIX_RELT(this->mCoord2, 1, 1), *MATRIX_RELT(this->mCoord2, 2, 1), *MATRIX_RELT(this->mCoord2, 3, 1)); + oAVoxel, *MATRIX_RELT(ref->mCoord2, 1, 1), *MATRIX_RELT(ref->mCoord2, 2, 1), *MATRIX_RELT(ref->mCoord2, 3, 1)); goto cleanup; @@ -1034,35 +1033,35 @@ Trns_tErr Trns_ConvertBtoA(mriTransformRef this, xVoxelRef iBVoxel, xVoxelRef oA return eResult; } -Trns_tErr Trns_ConvertBtoRAS(mriTransformRef this, xVoxelRef iBVoxel, xVoxelRef oRASVoxel) +Trns_tErr Trns_ConvertBtoRAS(mriTransformRef ref, xVoxelRef iBVoxel, xVoxelRef oRASVoxel) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mBtoRAS) { + if (NULL == ref->mBtoRAS) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* set our coord matrix */ - *MATRIX_RELT(this->mCoord1, 1, 1) = xVoxl_GetFloatX(iBVoxel); - *MATRIX_RELT(this->mCoord1, 2, 1) = xVoxl_GetFloatY(iBVoxel); - *MATRIX_RELT(this->mCoord1, 3, 1) = xVoxl_GetFloatZ(iBVoxel); - *MATRIX_RELT(this->mCoord1, 4, 1) = 1; + *MATRIX_RELT(ref->mCoord1, 1, 1) = xVoxl_GetFloatX(iBVoxel); + *MATRIX_RELT(ref->mCoord1, 2, 1) = xVoxl_GetFloatY(iBVoxel); + *MATRIX_RELT(ref->mCoord1, 3, 1) = xVoxl_GetFloatZ(iBVoxel); + *MATRIX_RELT(ref->mCoord1, 4, 1) = 1; /* do the transform */ - MatrixMultiply(this->mBtoRAS, this->mCoord1, this->mCoord2); + MatrixMultiply(ref->mBtoRAS, ref->mCoord1, ref->mCoord2); /* set the voxel to the matrix */ xVoxl_SetFloat(oRASVoxel, - *MATRIX_RELT(this->mCoord2, 1, 1), - *MATRIX_RELT(this->mCoord2, 2, 1), - *MATRIX_RELT(this->mCoord2, 3, 1)); + *MATRIX_RELT(ref->mCoord2, 1, 1), + *MATRIX_RELT(ref->mCoord2, 2, 1), + *MATRIX_RELT(ref->mCoord2, 3, 1)); goto cleanup; @@ -1077,33 +1076,33 @@ Trns_tErr Trns_ConvertBtoRAS(mriTransformRef this, xVoxelRef iBVoxel, xVoxelRef return eResult; } -Trns_tErr Trns_ConvertBRAStoB(mriTransformRef this, xVoxelRef iBRASVoxel, xVoxelRef oBVoxel) +Trns_tErr Trns_ConvertBRAStoB(mriTransformRef ref, xVoxelRef iBRASVoxel, xVoxelRef oBVoxel) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mRAStoB) { + if (NULL == ref->mRAStoB) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* set our coord matrix */ - *MATRIX_RELT(this->mCoord1, 1, 1) = xVoxl_GetFloatX(iBRASVoxel); - *MATRIX_RELT(this->mCoord1, 2, 1) = xVoxl_GetFloatY(iBRASVoxel); - *MATRIX_RELT(this->mCoord1, 3, 1) = xVoxl_GetFloatZ(iBRASVoxel); - *MATRIX_RELT(this->mCoord1, 4, 1) = 1; + *MATRIX_RELT(ref->mCoord1, 1, 1) = xVoxl_GetFloatX(iBRASVoxel); + *MATRIX_RELT(ref->mCoord1, 2, 1) = xVoxl_GetFloatY(iBRASVoxel); + *MATRIX_RELT(ref->mCoord1, 3, 1) = xVoxl_GetFloatZ(iBRASVoxel); + *MATRIX_RELT(ref->mCoord1, 4, 1) = 1; /* do the transform */ - MatrixMultiply(this->mRAStoB, this->mCoord1, this->mCoord2); + MatrixMultiply(ref->mRAStoB, ref->mCoord1, ref->mCoord2); /* set the voxel to the matrix */ xVoxl_SetFloat( - oBVoxel, *MATRIX_RELT(this->mCoord2, 1, 1), *MATRIX_RELT(this->mCoord2, 2, 1), *MATRIX_RELT(this->mCoord2, 3, 1)); + oBVoxel, *MATRIX_RELT(ref->mCoord2, 1, 1), *MATRIX_RELT(ref->mCoord2, 2, 1), *MATRIX_RELT(ref->mCoord2, 3, 1)); goto cleanup; @@ -1118,23 +1117,23 @@ Trns_tErr Trns_ConvertBRAStoB(mriTransformRef this, xVoxelRef iBRASVoxel, xVoxel return eResult; } -Trns_tErr Trns_ConvertMatrixAtoB(mriTransformRef this, MATRIX *iAMatrix, MATRIX *oBMatrix) +Trns_tErr Trns_ConvertMatrixAtoB(mriTransformRef ref, MATRIX *iAMatrix, MATRIX *oBMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mAtoB) { + if (NULL == ref->mAtoB) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* do the transform */ - MatrixMultiply(this->mAtoB, iAMatrix, oBMatrix); + MatrixMultiply(ref->mAtoB, iAMatrix, oBMatrix); goto cleanup; @@ -1149,23 +1148,23 @@ Trns_tErr Trns_ConvertMatrixAtoB(mriTransformRef this, MATRIX *iAMatrix, MATRIX return eResult; } -Trns_tErr Trns_ConvertMatrixAtoRAS(mriTransformRef this, MATRIX *iAMatrix, MATRIX *oRASMatrix) +Trns_tErr Trns_ConvertMatrixAtoRAS(mriTransformRef ref, MATRIX *iAMatrix, MATRIX *oRASMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mAtoRAS) { + if (NULL == ref->mAtoRAS) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* do the transform */ - MatrixMultiply(this->mAtoRAS, iAMatrix, oRASMatrix); + MatrixMultiply(ref->mAtoRAS, iAMatrix, oRASMatrix); goto cleanup; @@ -1180,23 +1179,23 @@ Trns_tErr Trns_ConvertMatrixAtoRAS(mriTransformRef this, MATRIX *iAMatrix, MATRI return eResult; } -Trns_tErr Trns_ConvertMatrixBtoA(mriTransformRef this, MATRIX *iBMatrix, MATRIX *oAMatrix) +Trns_tErr Trns_ConvertMatrixBtoA(mriTransformRef ref, MATRIX *iBMatrix, MATRIX *oAMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mBtoA) { + if (NULL == ref->mBtoA) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* do the transform */ - MatrixMultiply(this->mBtoA, iBMatrix, oAMatrix); + MatrixMultiply(ref->mBtoA, iBMatrix, oAMatrix); goto cleanup; @@ -1211,23 +1210,23 @@ Trns_tErr Trns_ConvertMatrixBtoA(mriTransformRef this, MATRIX *iBMatrix, MATRIX return eResult; } -Trns_tErr Trns_ConvertMatrixBtoRAS(mriTransformRef this, MATRIX *iBMatrix, MATRIX *oRASMatrix) +Trns_tErr Trns_ConvertMatrixBtoRAS(mriTransformRef ref, MATRIX *iBMatrix, MATRIX *oRASMatrix) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* if we don't have our trans matricies, return an error. */ - if (NULL == this->mBtoRAS) { + if (NULL == ref->mBtoRAS) { eResult = Trns_tErr_TransformationMatrixNotInited; goto error; } /* do the transform */ - MatrixMultiply(this->mBtoRAS, iBMatrix, oRASMatrix); + MatrixMultiply(ref->mBtoRAS, iBMatrix, oRASMatrix); goto cleanup; @@ -1244,33 +1243,33 @@ Trns_tErr Trns_ConvertMatrixBtoRAS(mriTransformRef this, MATRIX *iBMatrix, MATRI /* don't use the next function when copying mAtoB or mBtoA */ /* they will be replaced by recalculated ones */ -Trns_tErr Trns_CalcMatricies_(mriTransformRef this) +Trns_tErr Trns_CalcMatricies_(mriTransformRef ref) { Trns_tErr eResult = Trns_tErr_NoErr; MATRIX *tmp = NULL; /* for each of our first three matricies, if we have them, calc an inverse. */ - if (NULL != this->mAtoRAS) { - this->mRAStoA = MatrixInverse(this->mAtoRAS, NULL); + if (NULL != ref->mAtoRAS) { + ref->mRAStoA = MatrixInverse(ref->mAtoRAS, NULL); } - if (NULL != this->mBtoRAS) { - this->mRAStoB = MatrixInverse(this->mBtoRAS, NULL); + if (NULL != ref->mBtoRAS) { + ref->mRAStoB = MatrixInverse(ref->mBtoRAS, NULL); } - if (NULL != this->mARAStoBRAS) { - this->mBRAStoARAS = MatrixInverse(this->mARAStoBRAS, NULL); + if (NULL != ref->mARAStoBRAS) { + ref->mBRAStoARAS = MatrixInverse(ref->mARAStoBRAS, NULL); } /* if we have everything now, calc the composed conversions */ - if (NULL != this->mAtoRAS && NULL != this->mRAStoA && NULL != this->mBtoRAS && NULL != this->mRAStoB && - NULL != this->mARAStoBRAS && NULL != this->mBRAStoARAS) { + if (NULL != ref->mAtoRAS && NULL != ref->mRAStoA && NULL != ref->mBtoRAS && NULL != ref->mRAStoB && + NULL != ref->mARAStoBRAS && NULL != ref->mBRAStoARAS) { /* a_index -> a_ras -> b_ras -> b_index */ - tmp = MatrixMultiply(this->mARAStoBRAS, this->mAtoRAS, NULL); - this->mAtoB = MatrixMultiply(this->mRAStoB, tmp, NULL); + tmp = MatrixMultiply(ref->mARAStoBRAS, ref->mAtoRAS, NULL); + ref->mAtoB = MatrixMultiply(ref->mRAStoB, tmp, NULL); /* b_index -> b_ras -> a_ras -> a_index */ - tmp = MatrixMultiply(this->mBRAStoARAS, this->mBtoRAS, NULL); - this->mBtoA = MatrixMultiply(this->mRAStoA, tmp, NULL); + tmp = MatrixMultiply(ref->mBRAStoARAS, ref->mBtoRAS, NULL); + ref->mBtoA = MatrixMultiply(ref->mRAStoA, tmp, NULL); } goto cleanup; @@ -1287,18 +1286,18 @@ Trns_tErr Trns_CalcMatricies_(mriTransformRef this) return eResult; } -Trns_tErr Trns_Verify(mriTransformRef this) +Trns_tErr Trns_Verify(mriTransformRef ref) { Trns_tErr eResult = Trns_tErr_NoErr; /* check for null ptr */ - if (NULL == this) { + if (NULL == ref) { eResult = Trns_tErr_InvalidPtr; goto cleanup; } /* check signature */ - if (Trns_kSignature != this->mSignature) { + if (Trns_kSignature != ref->mSignature) { eResult = Trns_tErr_InvalidSignature; goto cleanup; } @@ -1308,12 +1307,12 @@ Trns_tErr Trns_Verify(mriTransformRef this) return eResult; } -void Trns_Signal(char *isFuncName, int inLineNum, Trns_tErr ieCode) +void Trns_Signal(const char *isFuncName, int inLineNum, Trns_tErr ieCode) { DebugPrint(("Signal in %s, line %d: %d, %s", isFuncName, inLineNum, ieCode, Trns_GetErrorString(ieCode))); } -char *Trns_GetErrorString(Trns_tErr ieCode) +const char *Trns_GetErrorString(Trns_tErr ieCode) { Trns_tErr eCode = ieCode; @@ -1324,54 +1323,54 @@ char *Trns_GetErrorString(Trns_tErr ieCode) return Trns_ksaErrorStrings[eCode]; } -void Trns_DebugPrint_(mriTransformRef this) +void Trns_DebugPrint_(mriTransformRef ref) { - if (NULL != this->mAtoRAS) { + if (NULL != ref->mAtoRAS) { DebugPrint(("A to RAS:\n")); - MatrixPrint(stderr, this->mAtoRAS); + MatrixPrint(stderr, ref->mAtoRAS); } - if (NULL != this->mBtoRAS) { + if (NULL != ref->mBtoRAS) { DebugPrint(("B to RAS:\n")); - MatrixPrint(stderr, this->mBtoRAS); + MatrixPrint(stderr, ref->mBtoRAS); } - if (NULL != this->mARAStoBRAS) { + if (NULL != ref->mARAStoBRAS) { DebugPrint(("ARAS to BRAS:\n")); - MatrixPrint(stderr, this->mARAStoBRAS); + MatrixPrint(stderr, ref->mARAStoBRAS); } - if (NULL != this->mRAStoA) { + if (NULL != ref->mRAStoA) { DebugPrint(("RAS to A:\n")); - MatrixPrint(stderr, this->mRAStoA); + MatrixPrint(stderr, ref->mRAStoA); } - if (NULL != this->mRAStoB) { + if (NULL != ref->mRAStoB) { DebugPrint(("RAS to B:\n")); - MatrixPrint(stderr, this->mRAStoB); + MatrixPrint(stderr, ref->mRAStoB); } - if (NULL != this->mBRAStoARAS) { + if (NULL != ref->mBRAStoARAS) { DebugPrint(("BRAS to ARAS:\n")); - MatrixPrint(stderr, this->mBRAStoARAS); + MatrixPrint(stderr, ref->mBRAStoARAS); } - if (NULL != this->mAtoB) { + if (NULL != ref->mAtoB) { DebugPrint(("A to B:\n")); - MatrixPrint(stderr, this->mAtoB); + MatrixPrint(stderr, ref->mAtoB); } } -Trns_tErr Trns_GetType(mriTransformRef this, int *ptype) +Trns_tErr Trns_GetType(mriTransformRef ref, int *ptype) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } /* return the type */ - *ptype = this->type; + *ptype = ref->type; goto cleanup; @@ -1386,27 +1385,27 @@ Trns_tErr Trns_GetType(mriTransformRef this, int *ptype) return eResult; } -Trns_tErr Trns_CopyAtoB(mriTransformRef this, MATRIX *iAtoB) +Trns_tErr Trns_CopyAtoB(mriTransformRef ref, MATRIX *iAtoB) { Trns_tErr eResult = Trns_tErr_NoErr; - eResult = Trns_Verify(this); + eResult = Trns_Verify(ref); if (Trns_tErr_NoErr != eResult) { goto error; } - if (NULL != this->mAtoB) { - MatrixFree(&this->mAtoB); + if (NULL != ref->mAtoB) { + MatrixFree(&ref->mAtoB); } - if (NULL != this->mBtoA) { - MatrixFree(&this->mBtoA); + if (NULL != ref->mBtoA) { + MatrixFree(&ref->mBtoA); } - /* create a copy of this matrix */ - this->mAtoB = MatrixCopy(iAtoB, NULL); - this->mBtoA = MatrixInverse(iAtoB, NULL); + /* create a copy of ref matrix */ + ref->mAtoB = MatrixCopy(iAtoB, NULL); + ref->mBtoA = MatrixInverse(iAtoB, NULL); - DebugAssertThrowX((NULL != this->mBtoA), eResult, Trns_tErr_LTAImportFailed); + DebugAssertThrowX((NULL != ref->mBtoA), eResult, Trns_tErr_LTAImportFailed); goto cleanup; diff --git a/utils/mriVolume.c b/utils/mriVolume.c deleted file mode 100644 index 04409a71840..00000000000 --- a/utils/mriVolume.c +++ /dev/null @@ -1,3655 +0,0 @@ -/** - * @file mriVolume.c - * @brief early form of mri volume utils - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.94 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include - -#include "error.h" -#include "fsenv.h" -#include "macros.h" // FEQUAL -#include "mriTransform.h" -#include "mri_conform.h" -#include "proto.h" // nint -#include "xList.h" -#include "xUtilities.h" - -#include "mriVolume.h" - -// should be in transform.h if they aren't already - -char Volm_ksaErrorStrings[Volm_knNumErrorCodes][Volm_knErrStringLen] = { - "No error.", - "Invalid signature.", - "Invalid parameter.", - "Invalid index.", - "Memory allocation failed.", - "Couldn't read volume.", - "Couldn't copy volume.", - "Couldn't read transform.", - "Couldn't copy transform.", - "Couldn't normalize volume.", - "Couldn't export volume to COR format.", - "MRI volume not present.", - "Scanner transform not present.", - "Index to RAS transform not present.", - "Flood user function can only return Continue or Stop", - "While trying to find a suitable destination volume for the display transform, couldn't find FREESURFER_HOME " - "environment variable.", - "While trying to find a suitable destination volume for the display transform, couldn't find " - "FREESURFER_HOME/average/mni305.cor.mgz.", - "Error reading FREESURFER_HOME/average/mni305.cor.mgz while trying to population destination information in " - "the display transform."}; - -Volm_tErr Volm_New(mriVolumeRef *opVolume) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - mriVolumeRef this = NULL; - MATRIX *tmpMatrix = NULL; - - DebugEnterFunction(("Volm_New( opVolume=%p )", opVolume)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((opVolume != NULL), eResult, Volm_tErr_InvalidParamater); - - /* allocate us. */ - DebugNote(("Allocating storage for this")); - this = (mriVolumeRef)malloc(sizeof(mriVolume)); - DebugAssertThrowX((NULL != this), eResult, Volm_tErr_AllocationFailed); - - /* init members to defaults */ - DebugNote(("Setting members to default values")); - this->mSignature = Volm_kSignature; - this->mnDimensionX = 0; - this->mnDimensionY = 0; - this->mnDimensionZ = 0; - this->mnDimensionFrame = 1; - this->mpMriValues = NULL; - this->mpSnapshot = NULL; - this->mpMaxValuesX = NULL; - this->mpMaxValuesY = NULL; - this->mpMaxValuesZ = NULL; - this->mSampleType = Volm_tSampleType_Nearest; - this->mMRIIdxToAnaIdxTransform = NULL; - this->mDisplayTransform = NULL; - this->mScannerTransform = NULL; - memset(this->msSubjectName, 0, sizeof(this->msSubjectName)); - memset(this->msVolumeName, 0, sizeof(this->msVolumeName)); - memset(this->msOriginalPath, 0, sizeof(this->msOriginalPath)); - this->mfColorBrightness = Volm_kfDefaultBrightness; - this->mfColorContrast = Volm_kfDefaultContrast; - this->mfColorMin = 0; - this->mfColorMax = 0; - memset(this->mafColorTable, 0, sizeof(this->mafColorTable)); - memset(this->manColorTable, 0, sizeof(this->manColorTable)); - - /* make our color table with default values */ - eResult = Volm_MakeColorTable(this); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - /* make our tal transforms */ - Trns_New(&this->mMNITalLtzToRealTalTransform); - tmpMatrix = MatrixIdentity(4, NULL); - stuff_four_by_four(tmpMatrix, 0.99, 0, 0, 0, 0.00, 0.9688, 0.042, 0, 0.00, -0.0485, 0.839, 0, 0.00, 0, 0, 1); - Trns_CopyARAStoBRAS(this->mMNITalLtzToRealTalTransform, tmpMatrix); - MatrixIdentity(4, tmpMatrix); - Trns_CopyAtoRAS(this->mMNITalLtzToRealTalTransform, tmpMatrix); - Trns_CopyBtoRAS(this->mMNITalLtzToRealTalTransform, tmpMatrix); - - Trns_New(&this->mMNITalGtzToRealTalTransform); - MatrixIdentity(4, tmpMatrix); - stuff_four_by_four(tmpMatrix, 0.99, 0, 0, 0, 0.00, 0.9688, 0.046, 0, 0.00, -0.0485, 0.9189, 0, 0.00, 0, 0, 1); - Trns_CopyARAStoBRAS(this->mMNITalGtzToRealTalTransform, tmpMatrix); - MatrixIdentity(4, tmpMatrix); - Trns_CopyAtoRAS(this->mMNITalGtzToRealTalTransform, tmpMatrix); - Trns_CopyBtoRAS(this->mMNITalGtzToRealTalTransform, tmpMatrix); - - /* Make our temp vars. */ - this->mpTmpScreenIdx = VectorAlloc(4, MATRIX_REAL); - this->mpTmpMRIIdx = VectorAlloc(4, MATRIX_REAL); - - /* return us. */ - *opVolume = this; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - - if (NULL != this) { - Volm_Delete(&this); - } - - EndDebugCatch; - - DebugExitFunction; - - if (NULL != tmpMatrix) { - MatrixFree(&tmpMatrix); - } - - return eResult; -} - -Volm_tErr Volm_Delete(mriVolumeRef *iopVolume) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - mriVolumeRef this = NULL; - - DebugEnterFunction(("Volm_Delete( iopVolume=%p )", iopVolume)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != iopVolume), eResult, Volm_tErr_InvalidParamater); - - /* get this and verify it */ - this = *iopVolume; - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* free member data */ - if (NULL != this->mpMriValues) { - MRIfree(&(this->mpMriValues)); - } - if (NULL != this->mpSnapshot) { - free(this->mpSnapshot); - } - if (NULL != this->mpMaxValuesX) { - free(this->mpMaxValuesX); - } - if (NULL != this->mpMaxValuesY) { - free(this->mpMaxValuesY); - } - if (NULL != this->mpMaxValuesZ) { - free(this->mpMaxValuesZ); - } - if (NULL != this->mDisplayTransform) { - TransformFree(&(this->mDisplayTransform)); - } - if (NULL != this->mMNITalLtzToRealTalTransform) { - Trns_Delete(&(this->mMNITalLtzToRealTalTransform)); - } - if (NULL != this->mMNITalGtzToRealTalTransform) { - Trns_Delete(&(this->mMNITalGtzToRealTalTransform)); - } - if (NULL != this->mScannerTransform) { - Trns_Delete(&(this->mScannerTransform)); - } - if (NULL != this->mpTmpScreenIdx) { - MatrixFree(&this->mpTmpScreenIdx); - } - if (NULL != this->mpTmpMRIIdx) { - MatrixFree(&this->mpTmpMRIIdx); - } - - /* free us */ - free(this); - - /* return null */ - *iopVolume = NULL; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_DeepClone(mriVolumeRef this, mriVolumeRef *opVolume) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - Trns_tErr eTransform = Trns_tErr_NoErr; - mriVolumeRef clone = NULL; - - DebugEnterFunction(("Volm_DeepClone( this=%p, opVolume=%p )", this, opVolume)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != opVolume), eResult, Volm_tErr_InvalidParamater); - - /* allocate a clone */ - DebugNote(("Creating clone")); - eResult = Volm_New(&clone); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - /* Copy simple data */ - clone->mnDimensionX = this->mnDimensionX; - clone->mnDimensionY = this->mnDimensionY; - clone->mnDimensionZ = this->mnDimensionZ; - clone->mnDimensionFrame = this->mnDimensionFrame; - clone->mSampleType = this->mSampleType; - clone->mfColorBrightness = this->mfColorBrightness; - clone->mfColorContrast = this->mfColorContrast; - clone->mfColorMin = this->mfColorMin; - clone->mfColorMax = this->mfColorMax; - clone->mfMinValue = this->mfMinValue; - clone->mfMaxValue = this->mfMaxValue; - - /* copy mri volumes */ - DebugNote(("Cloning normalized volume")); - clone->mpMriValues = MRIcopy(this->mpMriValues, NULL); - DebugAssertThrowX((NULL != clone->mpMriValues), eResult, Volm_tErr_CouldntCopyVolume); - - /* copy the transforms */ - if (NULL != this->mMRIIdxToAnaIdxTransform) { - DebugNote(("Copying MRI index to ana idx transform")); - eTransform = Trns_DeepClone(this->mMRIIdxToAnaIdxTransform, &(clone->mMRIIdxToAnaIdxTransform)); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, Volm_tErr_CouldntCopyTransform); - } - if (NULL != this->mDisplayTransform) { - DebugNote(("Copying display transform")); - clone->mDisplayTransform = TransformCopy(this->mDisplayTransform, NULL); - DebugAssertThrowX((NULL != clone->mDisplayTransform), eResult, Volm_tErr_CouldntCopyTransform); - } - if (NULL != this->mMNITalLtzToRealTalTransform) { - DebugNote(("Copying real tal ltz transform")); - eTransform = Trns_DeepClone(this->mMNITalLtzToRealTalTransform, &(clone->mMNITalLtzToRealTalTransform)); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, Volm_tErr_CouldntCopyTransform); - } - if (NULL != this->mMNITalGtzToRealTalTransform) { - DebugNote(("Copying real tal gtz transform")); - eTransform = Trns_DeepClone(this->mMNITalGtzToRealTalTransform, &(clone->mMNITalGtzToRealTalTransform)); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, Volm_tErr_CouldntCopyTransform); - } - if (NULL != this->mScannerTransform) { - DebugNote(("Copying scanner transform")); - eTransform = Trns_DeepClone(this->mScannerTransform, &(clone->mScannerTransform)); - DebugAssertThrowX((Trns_tErr_NoErr == eTransform), eResult, Volm_tErr_CouldntCopyTransform); - } - - /* copy the strings */ - xUtil_strncpy(clone->msSubjectName, this->msSubjectName, sizeof(clone->msSubjectName)); - xUtil_strncpy(clone->msVolumeName, this->msVolumeName, sizeof(clone->msVolumeName)); - xUtil_strncpy(clone->msOriginalPath, this->msOriginalPath, sizeof(clone->msOriginalPath)); - - /* allocate and copy color tables */ - memmove(clone->mafColorTable, this->mafColorTable, sizeof(this->manColorTable)); - memmove(clone->manColorTable, this->manColorTable, sizeof(this->mafColorTable)); - - /* Copy the resample information then calc the resample matrices, - that will point the m_resample{} matrices to the right place in - the clone. */ - clone->mResampleMethod = this->mResampleMethod; - clone->mResampleToRAS = MatrixCopy(this->mResampleToRAS, NULL); - clone->mResampleToRASOrig = MatrixCopy(this->mResampleToRASOrig, NULL); - clone->mResampleToRASInverse = MatrixCopy(this->mResampleToRASInverse, NULL); - clone->mResampleToSlice = MatrixCopy(this->mResampleToSlice, NULL); - clone->mResampleToSliceOrig = MatrixCopy(this->mResampleToSliceOrig, NULL); - clone->mResampleToSliceInverse = MatrixCopy(this->mResampleToSliceInverse, NULL); - - Volm_SetResampleMethod(clone, clone->mResampleMethod); - - /* return the clone */ - *opVolume = clone; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - - if (NULL != clone) { - Volm_Delete(&clone); - } - - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_CreateFromVolume(mriVolumeRef this, mriVolumeRef iVolume) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - int nDimensionX = 0; - int nDimensionY = 0; - int nDimensionZ = 0; - int nType = 0; - int nDimensionFrames = 0; - MRI *mriVolume = NULL; - - DebugEnterFunction(("Volm_CreateFromVolume( this=%p, iVolume=%p )", this, iVolume)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != iVolume), eResult, Volm_tErr_InvalidParamater); - - /* Get the necessary parameters we need to create a new MRI from the - volume we got passed in. */ - DebugNote(("Getting volume dimensions")); - eResult = Volm_GetDimensions(iVolume, &nDimensionX, &nDimensionY, &nDimensionZ); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - DebugNote(("Getting number of frames")); - eResult = Volm_GetNumberOfFrames(iVolume, &nDimensionFrames); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - DebugNote(("Getting volume type")); - eResult = Volm_GetType(iVolume, &nType); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* Create a new MRI of that size. */ - DebugNote(("Creating the mri with dimensions %d,%d,%d type %d nframes %d", - nDimensionX, - nDimensionY, - nDimensionZ, - nType, - nDimensionFrames)); - mriVolume = MRIallocSequence(nDimensionX, nDimensionY, nDimensionZ, nType, nDimensionFrames); - DebugAssertThrowX((NULL != mriVolume), eResult, Volm_tErr_CouldntReadVolume); - MRIcopyHeader(iVolume->mpMriValues, mriVolume); - DebugAssertThrowX((NULL != mriVolume), eResult, Volm_tErr_CouldntReadVolume); - - /* Set from the new MRI. */ - DebugNote(("Setting from MRI")); - eResult = Volm_SetFromMRI_(this, mriVolume); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* Set the subject name from the original and set the volume name - and path to blanks. */ - DebugNote(("Copying original subject name")); - Volm_CopySubjectName(iVolume, this->msSubjectName, sizeof(this->msSubjectName)); - DebugNote(("Setting volume name to empty")); - xUtil_strncpy(this->msVolumeName, "", sizeof(this->msVolumeName)); - DebugNote(("Setting path to empty")); - xUtil_strncpy(this->msOriginalPath, "", sizeof(this->msOriginalPath)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ImportData(mriVolumeRef this, char *isSource) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - MRI *mriVolume = NULL; - - DebugEnterFunction(("Volm_ImportData( this=%p, isSource=%s )", this, isSource)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != isSource), eResult, Volm_tErr_InvalidParamater); - - /* attempt to read the volume in */ - DebugNote(("Importing volume with MRIread")); - mriVolume = MRIread(isSource); - DebugAssertThrowX((NULL != mriVolume), eResult, Volm_tErr_CouldntReadVolume); - - DebugNote(("Setting from MRI")); - eResult = Volm_SetFromMRI_(this, mriVolume); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* save the volume source */ - DebugNote(("Copying original path")); - xUtil_strncpy(this->msOriginalPath, isSource, sizeof(this->msOriginalPath)); - - /* get the subject and volume name */ - eResult = Volm_ExtractAndSetSubjectName(this, isSource); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - eResult = Volm_ExtractAndSetVolumeName(this, isSource); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetFromMRI_(mriVolumeRef this, MRI *iMRI) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - MATRIX *identity = NULL; - MATRIX *scannerTransform = NULL; - MATRIX *m_resample; - MATRIX *m_resample_inv; - - DebugEnterFunction(("Volm_SetFromMRI_( this=%p, iMRI=%p )", this, iMRI)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != iMRI), eResult, Volm_tErr_InvalidParamater); - - /* Clear old volume if we have one. */ - if (NULL != this->mpMriValues && this->mpMriValues != iMRI) { - MRIfree(&this->mpMriValues); - } - - /* Get the reange. */ - MRIvalRange(iMRI, &this->mfMinValue, &this->mfMaxValue); - - /* Set the color min/max to these values. */ - this->mfColorMin = this->mfMinValue; - this->mfColorMax = this->mfMaxValue; - - /* Grab the dimensions and number of frames. */ - this->mnDimensionX = iMRI->width; - this->mnDimensionY = iMRI->height; - this->mnDimensionZ = iMRI->depth; - this->mnDimensionFrame = iMRI->nframes; - - /* set the volumes in this */ - this->mpMriValues = iMRI; - - /* Initialize the resample matrix. */ - DebugNote(("Computing norming matrix ")); - m_resample = MRIgetConformMatrix(iMRI); - DebugAssertThrowX((NULL != m_resample), eResult, Volm_tErr_CouldntNormalizeVolume); - DebugNote(("Setting resample RAS matrix")); - this->mResampleToRAS = m_resample; - DebugNote(("Calculating inverse of resample matrix")); - m_resample_inv = MatrixInverse(m_resample, NULL); - DebugNote(("Setting inverse resample RAS matrix")); - this->mResampleToRASInverse = m_resample_inv; - DebugNote(("Copying original resample RAS matrix")); - this->mResampleToRASOrig = MatrixCopy(m_resample, NULL); - - /* Calculate the resample matrices that don't use the RAS - transform. This just does the pixel size transform. */ - DebugNote(("Setting resample to slice matrix")); - this->mResampleToSlice = MatrixIdentity(4, NULL); - stuff_four_by_four(this->mResampleToSlice, - 1.0 / this->mpMriValues->xsize, - 0, - 0, - 0, - 0, - 1.0 / this->mpMriValues->ysize, - 0, - 0, - 0, - 0, - 1.0 / this->mpMriValues->zsize, - 0, - 0, - 0, - 0, - 1); - DebugNote(("Calculating inverse of resample to slice matrix")); - this->mResampleToSliceInverse = MatrixInverse(this->mResampleToSlice, NULL); - DebugNote(("Copying original resample to slice matrix")); - this->mResampleToSliceOrig = MatrixCopy(this->mResampleToSlice, NULL); - - /* grab the scanner transform and copy it into our transform */ - if (NULL != this->mScannerTransform) { - DebugNote(("Deleting existing scanner transform")); - Trns_Delete(&(this->mScannerTransform)); - } - DebugNote(("Creating scanner transform")); - Trns_New(&this->mScannerTransform); - DebugNote(("Getting scanner transform matrix")); - scannerTransform = extract_i_to_r(iMRI); - DebugAssertThrowX((NULL != scannerTransform), eResult, Volm_tErr_AllocationFailed); - DebugNote(("Copying scanner transform matrix into transform")); - Trns_CopyARAStoBRAS(this->mScannerTransform, scannerTransform); - identity = MatrixIdentity(4, NULL); - DebugNote(("Copying identity matrix into scanner transform")); - Trns_CopyAtoRAS(this->mScannerTransform, identity); - Trns_CopyBtoRAS(this->mScannerTransform, identity); - - /* Set the initial resample method. */ - Volm_SetResampleMethod(this, Volm_tResampleMethod_RAS); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - if (NULL != scannerTransform) { - MatrixFree(&scannerTransform); - } - if (NULL != identity) { - MatrixFree(&identity); - } - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_CalculateMRIIdxToAnaIdx_(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - MATRIX *identity = NULL; - MATRIX *idxToRASTransform = NULL; - MATRIX *BtoRAS = NULL; - - DebugEnterFunction(("Volm_CalculateMRIIdxToAnaIdx_( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - - /* This function creates a matrix that in which A is MRI Idx and B - is conformed idx or Ana idx. The RAS space is scanner RAS - space. Then you can use A->RAS and RAS->A to convert between - scanner RAS and MRI idx, and B->RAS and RAS->B to convert between - scanner RAS and Ana Idx. - - Furthermore, this transform is never used in mriVolume.c, as we - now use the MRIworldToVoxel etc functions. But this transform is - used by tkmedit, esp in the functional transform code. - - Here's the Tosa diagram. - - - extract_i_to_r() - = MRIxfmCRS2XYZ() - - "MRI Idx" or (i,j,k) (A) --------> RAS - | - | Identity - | - V - "Ana Idx" or conformed (B) --------> RAS - - extract_i_to_r * m_resample - = MRIxfmCRS2XYZ() * MRIGetConformMtx() - - */ - - /* Delete existing transform. */ - if (NULL != this->mMRIIdxToAnaIdxTransform) { - DebugNote(("Deleting existing MRI idx to ana idx transform")); - Trns_Delete(&(this->mMRIIdxToAnaIdxTransform)); - } - - /* Build the idxToRAS transform. */ - DebugNote(("Creating MRI idx to ana idx transform")); - Trns_New(&this->mMRIIdxToAnaIdxTransform); - - identity = MatrixIdentity(4, NULL); - - /* AtoRAS is extract_i_to_r. This goes from MRI Idx or (i,j,k) to - scanner RAS. This includes the voxel size calculation. */ - DebugNote(("Getting idx to ras matrix")); - idxToRASTransform = extract_i_to_r(this->mpMriValues); - DebugAssertThrowX((NULL != idxToRASTransform), eResult, Volm_tErr_AllocationFailed); - DebugNote(("Copying idx to ras transform matrix into AtoRAS")); - Trns_CopyAtoRAS(this->mMRIIdxToAnaIdxTransform, idxToRASTransform); - - /* ARSToBRAS is identity. */ - DebugNote(("Copying identity matrix into ARAStoBRAS")); - Trns_CopyARAStoBRAS(this->mMRIIdxToAnaIdxTransform, identity); - - /* BtoRAS = AtoRAS * m_resample */ - /* = extract_i_to_r * m_resample */ - /* = MRIxfmCRS2XYZ() * MRIGetConformMtx() */ - /* This goes from Ana Idx or conformed index to scanner RAS. */ - DebugNote(("Copying calc'd matrix into BtoRAS")); - BtoRAS = MatrixMultiply(idxToRASTransform, this->m_resample, NULL); - Trns_CopyBtoRAS(this->mMRIIdxToAnaIdxTransform, BtoRAS); - - DebugNote(("Freeing BtoRAS tmp matrix")); - MatrixFree(&BtoRAS); - - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - if (NULL != identity) { - MatrixFree(&identity); - } - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetMaxValueAtMRIIdx_(mriVolumeRef this, xVoxelRef iMRIIdx, mri_tOrientation iOrientation, float *oValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetMaxValueAtMRIIdx_( this=%p, iMRIIdx=%p, " - "iOrientation=%d, oValue=%p )", - this, - iMRIIdx, - iOrientation, - oValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - if (NULL == this->mpMaxValuesX) { - Volm_FindMaxValues(this); - } - - switch (iOrientation) { - case mri_tOrientation_Sagittal: - *oValue = this->mpMaxValuesX[xVoxl_GetY(iMRIIdx)][xVoxl_GetZ(iMRIIdx)]; - break; - case mri_tOrientation_Horizontal: - *oValue = this->mpMaxValuesY[xVoxl_GetX(iMRIIdx)][xVoxl_GetZ(iMRIIdx)]; - break; - case mri_tOrientation_Coronal: - *oValue = this->mpMaxValuesZ[xVoxl_GetX(iMRIIdx)][xVoxl_GetY(iMRIIdx)]; - break; - default: - *oValue = 0; - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ExportNormToCOR(mriVolumeRef this, char *isPath) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - char sPath[mri_knPathLen] = ""; - int eMRI = NO_ERROR; - - DebugEnterFunction(("Volm_ExportNormToCOR( this=%p, isPath=%s )", this, isPath)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* if out isPath is null, use the original path. */ - if (NULL == isPath) { - xUtil_strncpy(sPath, this->msOriginalPath, sizeof(sPath)); - } - else { - xUtil_strncpy(sPath, isPath, sizeof(sPath)); - } - - /* write the volume */ - DebugNote(("Writing volume with MRIwriteType")); -#if 0 - eMRI = MRIwriteType( this->mpMriValues, sPath,MRI_CORONAL_SLICE_DIRECTORY ); -#else - eMRI = MRIwrite(this->mpMriValues, sPath); -#endif - DebugAssertThrowX((NO_ERROR == eMRI), eResult, Volm_tErr_CouldntExportVolumeToCOR); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_Save(mriVolumeRef this, char *isFileName, tBoolean ibSaveFileName) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - char sFileName[mri_knPathLen] = ""; - int eMRI = NO_ERROR; - - DebugEnterFunction(("Volm_Save( this=%p, isFileName=%s, ibSaveFileName )", this, isFileName, ibSaveFileName)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* if out isFileName is null, use the original. */ - if (NULL == isFileName) { - xUtil_strncpy(sFileName, this->msOriginalPath, sizeof(sFileName)); - } - else { - xUtil_strncpy(sFileName, isFileName, sizeof(sFileName)); - } - - /* write the volume */ - DebugNote(("Writing volume with MRIwrite")); - eMRI = MRIwrite(this->mpMriValues, sFileName); - DebugAssertThrowX((NO_ERROR == eMRI), eResult, Volm_tErr_CouldntExportVolumeToCOR); - - /* Save the filename if they want. */ - if (NULL != isFileName && ibSaveFileName) { - DebugNote(("Saving file name")); - xUtil_strncpy(this->msOriginalPath, isFileName, sizeof(this->msOriginalPath)); - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_LoadDisplayTransform(mriVolumeRef this, char *isFileName) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - TRANSFORM *transform = NULL; - int eTransform = ERROR_NONE; - LTA *lta = NULL; - FSENV *fsenv = NULL; - char sMNI305FileName[1000] = ""; - int eStat; - struct stat statMNI305; - MRI *MNI305volume = NULL; - - DebugEnterFunction(("Volm_LoadDisplayTransform( this=%p, isFileName=%s )", this, isFileName)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != isFileName), eResult, Volm_tErr_InvalidParamater); - - /* try to read a transform and make sure we got it */ - DebugNote(("Reading transform from %s", isFileName)); - transform = TransformRead(isFileName); - DebugAssertThrowX((NULL != transform), eResult, Trns_tErr_LTAImportFailed); - - /* If this is an RAS_TO_RAS, take a look at the valid flags for - source and dest. If they aren't valid, we have to provide some - data. */ - if (transform->type == LINEAR_RAS_TO_RAS) { - lta = (LTA *)transform->xform; - - /* If the source is invalid, we can provide the data from this MRI - volume. */ - if (!lta->xforms[0].src.valid) { - fprintf(stderr, "INFO: Setting transform source geometry data to MRI volume's geometry\n"); - - getVolGeom(this->mpMriValues, &(lta->xforms[0].src)); - } - - /* If the dest is invalid, and the file name is talairach.xfm, we - can provide the volume from - $FREESURFER_HOME/average/mni305.cor.mgz if it's available. */ - if (!lta->xforms[0].dst.valid && NULL != strstr(isFileName, "talairach.xfm")) { - fprintf(stderr, "INFO: Setting transform dest geometry data to mni305's geometry\n"); - - /* Get FREESURFER_HOME. */ - fsenv = FSENVgetenv(); - DebugAssertThrowX((NULL != fsenv), eResult, Volm_tErr_FsenvNotFoundWhileSearchingForTransformDest); - DebugAssertThrowX( - (NULL != fsenv->FREESURFER_HOME), eResult, Volm_tErr_FsenvNotFoundWhileSearchingForTransformDest); - - /* Build the file name. */ - snprintf(sMNI305FileName, sizeof(sMNI305FileName), "%s/average/mni305.cor.mgz", fsenv->FREESURFER_HOME); - - /* Make sure the file exists. */ - eStat = stat(sMNI305FileName, &statMNI305); - DebugAssertThrowX((0 == eStat), eResult, Volm_tErr_MNI305NotFoundWhilePopulatingTramsformDest); - - /* Load it and read the header. */ - MNI305volume = MRIreadHeader(sMNI305FileName, MRI_VOLUME_TYPE_UNKNOWN); - DebugAssertThrowX((NULL != MNI305volume), eResult, Volm_tErr_ErrorReadingMNI305WhilePopulatingTramsformDest); - - /* Copy the geometry data. */ - getVolGeom(MNI305volume, &(lta->xforms[0].dst)); - } - } - - /* This doesn't invert the transform (as you might think), but - calculates the inverses that we'll use later. */ - eTransform = TransformInvert(transform, this->mpMriValues); - if (0 != eTransform) { - fprintf(stderr, "TransformInvert returned %d\n", eTransform); - } - - /* Success! Out with the old and in with the new. */ - if (NULL != this->mDisplayTransform) { - TransformFree(&this->mDisplayTransform); - } - this->mDisplayTransform = transform; - - // TransformRas2Vox(transform, this->mpMriValues, this->mpMriValues) ; - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - if (NULL != fsenv) { - FSENVfree(&fsenv); - } - if (NULL != MNI305volume) { - MRIfree(&MNI305volume); - } - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_UnloadDisplayTransform(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_UnloadDisplayTransform( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* if we already have a transform, delete it */ - if (NULL != this->mDisplayTransform) { - TransformFree(&(this->mDisplayTransform)); - this->mDisplayTransform = NULL; - } - - MatrixCopy(this->m_resample_orig, this->m_resample); - DebugNote(("Calculating inverse of resample matrix")); - MatrixInverse(this->m_resample, this->m_resample_inv); - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_CopyGeometryInformation(mriVolumeRef this, VOL_GEOM *ioVolumeGeometry) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_CopyGeometryInformation( this=%p, " - "ioVolumeGeometry=%p )", - this, - ioVolumeGeometry)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != ioVolumeGeometry), eResult, Volm_tErr_InvalidParamater); - - /* Copy the information out. */ - getVolGeom(this->mpMriValues, ioVolumeGeometry); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -void Volm_GetIntColorAtIdx(mriVolumeRef this, xVoxelRef iIdx, xColor3nRef oColor) -{ - float x, y, z; - float value = 0; - int colorIdx = 0; - xVoxel disp; - - /* transform idx to display transform */ - if (NULL != this->mDisplayTransform) { - /* Transform using the inverse of the display transform. */ - TransformSampleInverse(this->mDisplayTransform, xVoxl_ExpandFloat(iIdx), &x, &y, &z); - xVoxl_SetFloat(&disp, x, y, z); - - if (Volm_VerifyIdx_(this, &disp) == Volm_tErr_NoErr) { - Volm_GetSampledValueAtIdx_(this, &disp, &value); - } - } - else { - /* Get the sampled value. Cap it to the color min and max. If in - between that, calculate the color index between 0 and 255. */ - Volm_GetSampledValueAtIdx_(this, iIdx, &value); - } - - if (value <= this->mfColorMin) { - colorIdx = 0; - } - else if (value >= this->mfColorMax) { - colorIdx = 255; - } - else { - colorIdx = (int)(Volm_knNumColorTableEntries * (value - this->mfColorMin) / (this->mfColorMax - this->mfColorMin)); - } - - *oColor = this->manColorTable[colorIdx]; -} - -void Volm_GetMaxIntColorAtIdx(mriVolumeRef this, xVoxelRef iIdx, mri_tOrientation iOrientation, xColor3nRef oColor) -{ - xVoxel MRI; - float value = 0; - int colorIdx = 0; - - Volm_ConvertIdxToMRIIdx(this, iIdx, &MRI); - - Volm_GetMaxValueAtMRIIdx_(this, &MRI, iOrientation, &value); - - colorIdx = (int)(255.0 * (value - this->mfMinValue) / (this->mfMaxValue - this->mfMinValue)); - *oColor = this->manColorTable[colorIdx]; -} - -Volm_tErr Volm_GetDimensions(mriVolumeRef this, int *onDimensionX, int *onDimensionY, int *onDimensionZ) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetDimensions( this=%p, onDimension=%p,%p,%p )", this, onDimensionX, onDimensionY, onDimensionZ)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX( - (onDimensionX != NULL) && (onDimensionY != NULL) && (onDimensionZ != NULL), eResult, Volm_tErr_InvalidParamater); - - /* return the dimension */ - DebugNote(("Returning the dimension")); - *onDimensionX = this->mnDimensionX; - *onDimensionY = this->mnDimensionY; - *onDimensionZ = this->mnDimensionZ; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetNumberOfFrames(mriVolumeRef this, int *onDimensionFrames) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetNumberOfFrames( this=%p, " - "onDimensionFrames=%p )", - this, - onDimensionFrames)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((onDimensionFrames != NULL), eResult, Volm_tErr_InvalidParamater); - - /* return the dimension */ - DebugNote(("Returning the dimension")); - *onDimensionFrames = this->mnDimensionFrame; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetType(mriVolumeRef this, int *onType) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_GetType( this=%p, onType=%p )", this, onType)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((onType != NULL), eResult, Volm_tErr_InvalidParamater); - - /* Make sure we have a volume */ - DebugAssertThrowX((NULL != this->mpMriValues), eResult, Volm_tErr_MRIVolumeNotPresent); - - /* return the dimension */ - DebugNote(("Returning the type")); - *onType = this->mpMriValues->type; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetValueMinMax(mriVolumeRef this, float *ofMin, float *ofMax) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_GetValueMinMax( this=%p, ofMin=%p, ofMax )", this, ofMin, ofMax)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((ofMin != NULL), eResult, Volm_tErr_InvalidParamater); - DebugAssertThrowX((ofMax != NULL), eResult, Volm_tErr_InvalidParamater); - - /* return the min and max */ - DebugNote(("Returning the min")); - *ofMin = this->mfMinValue; - *ofMax = this->mfMaxValue; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetResampleMethod(mriVolumeRef this, Volm_tResampleMethod *oMethod) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetResampleMethod( this=%p, " - "oMethod=%p )", - this, - oMethod)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((oMethod != NULL), eResult, Volm_tErr_InvalidParamater); - - /* return the method */ - DebugNote(("Returning the method")); - *oMethod = this->mResampleMethod; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetResampleMethod(mriVolumeRef this, Volm_tResampleMethod iMethod) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_SetResampleMethod( this=%p, iMethod=%d )", this, (int)iMethod)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iMethod >= 0 && iMethod < Volm_knNumResampleMethods), eResult, Volm_tErr_InvalidParamater); - - /* Set the resample method. */ - this->mResampleMethod = iMethod; - - /* Point the matrices correctly. */ - switch (this->mResampleMethod) { - case Volm_tResampleMethod_RAS: - this->m_resample = this->mResampleToRAS; - this->m_resample_orig = this->mResampleToRASOrig; - this->m_resample_inv = this->mResampleToRASInverse; - break; - case Volm_tResampleMethod_Slice: - this->m_resample = this->mResampleToSlice; - this->m_resample_orig = this->mResampleToSliceOrig; - this->m_resample_inv = this->mResampleToSliceInverse; - break; - default: - break; - } - - /* Recalc the mri idx to and idx transform. */ - Volm_CalculateMRIIdxToAnaIdx_(this); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetSampleType(mriVolumeRef this, Volm_tSampleType *oType) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetSampleType( this=%p, " - "oType=%p )", - this, - oType)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((oType != NULL), eResult, Volm_tErr_InvalidParamater); - - /* return the type */ - DebugNote(("Returning the type")); - *oType = this->mSampleType; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetSampleType(mriVolumeRef this, Volm_tSampleType iType) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_SetSampleType( this=%p, iType=%d )", this, (int)iType)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iType >= 0 && iType < Volm_knNumSampleTypes), eResult, Volm_tErr_InvalidParamater); - - /* Set the sample type. */ - this->mSampleType = iType; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetValueAtIdx(mriVolumeRef this, xVoxelRef iIdx, float *oValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetValueAtIdx( this=%p, iIdx=%p, " - "oValue=%p )", - this, - iIdx, - oValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iIdx != NULL && oValue != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyIdx_(this, iIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* return the value */ - DebugNote(("Fetching the value at (%d,%d,%d) and returning it", xVoxl_ExpandInt(iIdx))); - Volm_GetValueAtIdx_(this, iIdx, oValue); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetValueAtIdxUnsafe(mriVolumeRef this, xVoxelRef iIdx, float *oValue) -{ - Volm_GetValueAtIdx_(this, iIdx, oValue); - - return Volm_tErr_NoErr; -} - -Volm_tErr Volm_SetValueAtIdx(mriVolumeRef this, xVoxelRef iIdx, float iValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_SetValueAtIdx( this=%p, iIdx=%p, " - "iValue=%d )", - this, - iIdx, - (int)iValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iIdx != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyIdx_(this, iIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* set the value */ - DebugNote(("Setting the norm value")); - Volm_SetValueAtIdx_(this, iIdx, iValue); - - /* update our min max. */ - if (iValue > this->mfMaxValue) { - this->mfMaxValue = iValue; - } - if (iValue < this->mfMinValue) { - this->mfMinValue = iValue; - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetValueAtIdxFrame(mriVolumeRef this, xVoxelRef iIdx, int iFrame, float *oValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetValueAtIdxFrame( this=%p, iIdx=%p, iFrame=%d," - "oValue=%p )", - this, - iIdx, - iFrame, - oValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iIdx != NULL && oValue != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyIdx_(this, iIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - eResult = Volm_VerifyFrame_(this, iFrame); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* return the value */ - DebugNote(("Fetching the value at (%d,%d,%d) frame %d and returning it", xVoxl_ExpandInt(iIdx), iFrame)); - Volm_GetValueAtIdxFrame_(this, iIdx, iFrame, oValue); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetValueAtIdxFrameUnsafe(mriVolumeRef this, xVoxelRef iIdx, int iFrame, float *oValue) -{ - Volm_GetValueAtIdxFrame_(this, iIdx, iFrame, oValue); - - return Volm_tErr_NoErr; -} - -Volm_tErr Volm_SetValueAtIdxFrame(mriVolumeRef this, xVoxelRef iIdx, int iFrame, float iValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_SetValueAtIdx( this=%p, iIdx=%p, " - "iValue=%d )", - this, - iIdx, - (int)iValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iIdx != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyIdx_(this, iIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - eResult = Volm_VerifyFrame_(this, iFrame); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* set the value */ - DebugNote(("Setting the value")); - Volm_SetValueAtIdxFrame_(this, iIdx, iFrame, iValue); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetValueAtMRIIdx(mriVolumeRef this, xVoxelRef iMRIIdx, float *oValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetValueAtMRIIdx( this=%p, iMRIIdx=%p, " - "oValue=%p )", - this, - iMRIIdx, - oValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iMRIIdx != NULL && oValue != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyMRIIdx_(this, iMRIIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* return the value */ - Volm_GetValueAtMRIIdx_(this, iMRIIdx, oValue); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetValueAtMRIIdx(mriVolumeRef this, xVoxelRef iMRIIdx, float iValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_SetValueAtIdx( this=%p, iMRIIdx=%p, " - "iValue=%d )", - this, - iMRIIdx, - (int)iValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iMRIIdx != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyMRIIdx_(this, iMRIIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* set the value */ - Volm_SetValueAtMRIIdx_(this, iMRIIdx, iValue); - - /* update our min max. */ - if (iValue > this->mfMaxValue) { - this->mfMaxValue = iValue; - } - if (iValue < this->mfMinValue) { - this->mfMinValue = iValue; - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_HasTalTransform(mriVolumeRef this, tBoolean *obHasTransform) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_HasTalTransform( this=%p, obHasTransform=%p)", this, obHasTransform)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((obHasTransform != NULL), eResult, Volm_tErr_InvalidParamater); - - /* Return true if we have a tal transform, false if not. */ - if (NULL != this->mpMriValues->linear_transform) { - *obHasTransform = TRUE; - } - else - { - *obHasTransform = FALSE; - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertIdxToRAS(mriVolumeRef this, xVoxelRef iIdx, xVoxelRef oRAS) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - xVoxel mriIdx; - double rasX = 0; - double rasY = 0; - double rasZ = 0; - - DebugEnterFunction(("Volm_ConvertIdxToRAS( this=%p, iIdx=%p, oRAS=%p )", this, iIdx, oRAS)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iIdx != NULL && oRAS != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyIdx_(this, iIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* First convert the incoming screen idx to our local MRI idx. */ - DebugNote(("Converting scresshen idx to MRI idx")); - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &mriIdx); - - /* convert idx to ras */ - DebugNote(("Converting idx (%.2f, %.2f, %.2f) to RAS with MRIvoxelToWorld", xVoxl_ExpandFloat(&mriIdx))); - MRIvoxelToWorld(this->mpMriValues, xVoxl_ExpandFloat(&mriIdx), &rasX, &rasY, &rasZ); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(oRAS, (float)rasX, (float)rasY, (float)rasZ); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertRASToIdx(mriVolumeRef this, xVoxelRef iRAS, xVoxelRef oIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - double idxX = 0; - double idxY = 0; - double idxZ = 0; - xVoxel mriIdx; - - DebugEnterFunction(("Volm_ConvertRASToIdx( this=%p, iRAS=%p, oIdx=%p )", this, iRAS, oIdx)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iRAS != NULL && oIdx != NULL), eResult, Volm_tErr_InvalidParamater); - - /* convert ras to MRI idx */ - DebugNote(("Converting RAS (%.2f, %.2f, %.2f) to idx with MRIworldToVoxel", xVoxl_ExpandFloat(iRAS))); - MRIworldToVoxel(this->mpMriValues, xVoxl_ExpandFloat(iRAS), &idxX, &idxY, &idxZ); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(&mriIdx, (float)idxX, (float)idxY, (float)idxZ); - - /* Then convert from local MRI idx to screen idx. */ - DebugNote(("Converting MRI idx to screen idx")); - Volm_ConvertMRIIdxToScreenIdx_(this, &mriIdx, oIdx); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertIdxToMNITal(mriVolumeRef this, xVoxelRef iIdx, xVoxelRef oMNITal) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - xVoxel scannerRAS; - double talX = 0; - double talY = 0; - double talZ = 0; - - DebugEnterFunction( - ("Volm_ConvertIdxToMNITal( this=%p, iIdx=%p, " - "oMNITal=%p )", - this, - iIdx, - oMNITal)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - -#if 0 - DebugNote( ("Checking parameters") ); - DebugAssertThrowX( (iIdx != NULL && oMNITal != NULL), - eResult, Volm_tErr_InvalidParamater ); - eResult = Volm_VerifyIdx_( this, iIdx ); - DebugAssertThrow( (eResult == Volm_tErr_NoErr) ); -#endif - - /* Convert the index coords to scanner RAS coords. */ - Volm_ConvertIdxToScanner(this, iIdx, &scannerRAS); - - /* Transform them to MNI talaiarch with the transform in the MRI. */ - transform_point(this->mpMriValues->linear_transform, xVoxl_ExpandFloat(&scannerRAS), &talX, &talY, &talZ); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(oMNITal, (float)talX, (float)talY, (float)talZ); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertIdxToTal(mriVolumeRef this, xVoxelRef iIdx, xVoxelRef oTal) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - xVoxel scannerRAS; - double talX = 0; - double talY = 0; - double talZ = 0; - xVoxel tal; - - DebugEnterFunction( - ("Volm_ConvertIdxToTal( this=%p, iIdx=%p, " - "oTal=%p )", - this, - iIdx, - oTal)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - -#if 0 - DebugNote( ("Checking parameters") ); - DebugAssertThrowX( (iIdx != NULL && oTal != NULL), - eResult, Volm_tErr_InvalidParamater ); - eResult = Volm_VerifyIdx_( this, iIdx ); - DebugAssertThrow( (eResult == Volm_tErr_NoErr) ); -#endif - - /* Convert the index coords to scanner RAS coords. */ - Volm_ConvertIdxToScanner(this, iIdx, &scannerRAS); - - /* Transform them to MNI talaiarch with the transform in the MRI. */ - transform_point(this->mpMriValues->linear_transform, xVoxl_ExpandFloat(&scannerRAS), &talX, &talY, &talZ); - - /* convert to real tal. switch on the z to see which transform to use. */ - xVoxl_SetFloat(&tal, talX, talY, talZ); - if (xVoxl_GetFloatZ(&tal) > 0) { - DebugNote(("Converting to real tal with >0 transform")); - Trns_ConvertAtoB(this->mMNITalGtzToRealTalTransform, &tal, oTal); - } - else { - DebugNote(("Converting to real tal with <0 transform")); - Trns_ConvertAtoB(this->mMNITalLtzToRealTalTransform, &tal, oTal); - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertTalToIdx(mriVolumeRef this, xVoxelRef iTal, xVoxelRef oIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - double idxX = 0; - double idxY = 0; - double idxZ = 0; - xVoxel mniTal; - int eMRI = 0; - - DebugEnterFunction( - ("Volm_ConvertTalToIdx( this=%p, iTal=%p, " - "oIdx=%p )", - this, - iTal, - oIdx)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iTal != NULL && oIdx != NULL), eResult, Volm_tErr_InvalidParamater); - - /* convert to mni tal. switch on the z to see which transform to use. */ - if (xVoxl_GetFloatZ(iTal) > 0) { - DebugNote(("Converting to mni tal with >0 transform")); - Trns_ConvertBtoA(this->mMNITalGtzToRealTalTransform, iTal, &mniTal); - } - else { - DebugNote(("Converting to mni tal with <=0 transform")); - Trns_ConvertBtoA(this->mMNITalLtzToRealTalTransform, iTal, &mniTal); - } - - /* convert tal to idx */ - DebugNote( - ("Converting tal (%.2f, %.2f, %.2f) to idx with " - "MRItalairachToVoxel", - xVoxl_ExpandFloat(&mniTal))); - eMRI = MRItalairachToVoxel(this->mpMriValues, xVoxl_ExpandFloat(&mniTal), &idxX, &idxY, &idxZ); - DebugAssertThrowX((eMRI == NO_ERROR), eResult, Volm_tErr_CouldntReadVolume); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(oIdx, (float)idxX, (float)idxY, (float)idxZ); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertIdxToScanner(mriVolumeRef this, xVoxelRef iIdx, xVoxelRef oScanner) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - xVoxel mriIdx; - - DebugEnterFunction( - ("Volm_ConvertIdxToScanner( this=%p, iIdx=%p, " - "oScanner=%p )", - this, - iIdx, - oScanner)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* make sure we have the scanner transform */ - DebugAssertThrowX((NULL != this->mScannerTransform), eResult, Volm_tErr_ScannerTransformNotPresent); - - /* First convert the incoming screen idx to our local MRI idx. */ - DebugNote(("Converting screen idx to MRI idx")); - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &mriIdx); - - /* convert idx to scanner */ - DebugNote(("Converting idx (%.2f, %.2f, %.2f) to scanner", xVoxl_ExpandFloat(&mriIdx))); - Trns_ConvertAtoB(this->mScannerTransform, &mriIdx, oScanner); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertMRIIdxToScanner(mriVolumeRef this, xVoxelRef iMRIIdx, xVoxelRef oScanner) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_ConvertIdxToScanner( this=%p, iMRIIdx=%p, " - "oScanner=%p )", - this, - iMRIIdx, - oScanner)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* make sure we have the scanner transform */ - DebugAssertThrowX((NULL != this->mScannerTransform), eResult, Volm_tErr_ScannerTransformNotPresent); - - /* convert idx to scanner */ - DebugNote(("Converting idx (%.2f, %.2f, %.2f) to scanner", xVoxl_ExpandFloat(iMRIIdx))); - Trns_ConvertAtoB(this->mScannerTransform, iMRIIdx, oScanner); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertIdxToMRIIdx(mriVolumeRef this, xVoxelRef iIdx, xVoxelRef oMRIIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_ConvertIdxToMRIIdx( this=%p, iIdx=%p, " - "oMRIIdx=%p )", - this, - iIdx, - oMRIIdx)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - -#if 0 - DebugNote( ("Checking parameters") ); - DebugAssertThrowX( (iIdx != NULL && oMRIIdx != NULL), - eResult, Volm_tErr_InvalidParamater ); - eResult = Volm_VerifyIdx_( this, iIdx ); - DebugAssertThrow( (eResult == Volm_tErr_NoErr) ); -#endif - - /* Convert the incoming screen idx to our local MRI idx. */ - DebugNote(("Converting screen idx to MRI idx")); - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, oMRIIdx); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertMRIIdxToIdx(mriVolumeRef this, xVoxelRef iMRIIdx, xVoxelRef oIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_ConvertMRIIdxToIdx( this=%p, iMRIIdx=%p, " - "oIdx=%p )", - this, - iMRIIdx, - oIdx)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - -#if 0 - DebugNote( ("Checking parameters") ); - DebugAssertThrowX( (iIdx != NULL && oMRIIdx != NULL), - eResult, Volm_tErr_InvalidParamater ); - eResult = Volm_VerifyIdx_( this, iIdx ); - DebugAssertThrow( (eResult == Volm_tErr_NoErr) ); -#endif - - /* Convert the incoming local MRI to screen idx. */ - DebugNote(("Converting MRI idx to screen idx")); - Volm_ConvertMRIIdxToScreenIdx_(this, iMRIIdx, oIdx); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertMRIIdxToRAS(mriVolumeRef this, xVoxelRef iMRIIdx, xVoxelRef oRAS) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - double rasX = 0; - double rasY = 0; - double rasZ = 0; - - DebugEnterFunction(("Volm_ConvertIdxToRAS( this=%p, iMRIIdx=%p, oRAS=%p )", this, iMRIIdx, oRAS)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iMRIIdx != NULL && oRAS != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyMRIIdx_(this, iMRIIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* Convert idx to ras */ - DebugNote(("Converting idx to RAS with MRIvoxelToWorld")); - MRIvoxelToWorld(this->mpMriValues, xVoxl_ExpandFloat(iMRIIdx), &rasX, &rasY, &rasZ); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(oRAS, (float)rasX, (float)rasY, (float)rasZ); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertRASToMRIIdx(mriVolumeRef this, xVoxelRef iRAS, xVoxelRef oMRIIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - double idxX = 0; - double idxY = 0; - double idxZ = 0; - - DebugEnterFunction(("Volm_ConvertRASToIdx( this=%p, iRAS=%p, oMRIIdx=%p )", this, iRAS, oMRIIdx)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iRAS != NULL && oMRIIdx != NULL), eResult, Volm_tErr_InvalidParamater); - - /* convert ras to MRI idx */ - DebugNote(("Converting RAS to mri idx with MRIworldToVoxel")); - MRIworldToVoxel(this->mpMriValues, xVoxl_ExpandFloat(iRAS), &idxX, &idxY, &idxZ); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(oMRIIdx, (float)idxX, (float)idxY, (float)idxZ); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertMRIIdxToSurfaceRAS(mriVolumeRef this, xVoxelRef iMRIIdx, xVoxelRef oSurfaceRAS) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - double rasX = 0; - double rasY = 0; - double rasZ = 0; - - DebugEnterFunction( - ("Volm_ConvertIdxToSurfaceRAS( this=%p, iMRIIdx=%p, " - "oRAS=%p )", - this, - iMRIIdx, - oSurfaceRAS)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iMRIIdx != NULL && oSurfaceRAS != NULL), eResult, Volm_tErr_InvalidParamater); - eResult = Volm_VerifyMRIIdx_(this, iMRIIdx); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* Convert idx to ras */ - DebugNote(("Converting idx to surface RAS with MRIvoxelToSurfaceRAS")); - MRIvoxelToSurfaceRAS(this->mpMriValues, xVoxl_ExpandFloat(iMRIIdx), &rasX, &rasY, &rasZ); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(oSurfaceRAS, (float)rasX, (float)rasY, (float)rasZ); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ConvertSurfaceRASToMRIIdx(mriVolumeRef this, xVoxelRef iSurfaceRAS, xVoxelRef oMRIIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - double idxX = 0; - double idxY = 0; - double idxZ = 0; - - DebugEnterFunction( - ("Volm_ConvertRASToIdx( this=%p, iSurfaceRAS=%p, " - "oMRIIdx=%p )", - this, - iSurfaceRAS, - oMRIIdx)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iSurfaceRAS != NULL && oMRIIdx != NULL), eResult, Volm_tErr_InvalidParamater); - - /* convert ras to MRI idx */ - DebugNote(("Converting surface RAS to mri idx with MRIsurfaceRASToVoxel")); - MRIsurfaceRASToVoxel(this->mpMriValues, xVoxl_ExpandFloat(iSurfaceRAS), &idxX, &idxY, &idxZ); - - /* stuff results */ - DebugNote(("Stuffing result into xVoxel")); - xVoxl_SetFloat(oMRIIdx, (float)idxX, (float)idxY, (float)idxZ); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetMRIIdxToAnaIdxTransform(mriVolumeRef this, mriTransformRef *opTransform) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_GetMRIIdxToAnaIdxTransform( this=%p, " - "opTransform=%p )", - this, - opTransform)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != opTransform), eResult, Volm_tErr_InvalidParamater); - - /* make sure we have the transform */ - DebugAssertThrowX((NULL != this->mMRIIdxToAnaIdxTransform), eResult, Volm_tErr_IdxToRASTransformNotPresent); - - /* return a pointer to it */ - *opTransform = this->mMRIIdxToAnaIdxTransform; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_Flood(mriVolumeRef this, Volm_tFloodParams *iParams) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - xList_tErr eList = xList_tErr_NoErr; - xListRef list = NULL; - int nSize = 0; - tBoolean *visited = NULL; - xVoxelRef curVoxel = NULL; - void *pCurVoxel = NULL; - xVoxelRef newVoxel = NULL; - Volm_tVisitCommand eVisit = Volm_tVisitComm_Continue; - int nVisitedIndex = 0; - int nZ = 0; - int nBeginX = 0; - int nEndX = 0; - int nBeginY = 0; - int nEndY = 0; - int nBeginZ = 0; - int nEndZ = 0; - int nY = 0; - int nX = 0; - xVoxel idx; - float fValue = 0; - float fDistance = 0; -#ifdef Solaris - int i = 0; -#endif - - DebugEnterFunction(("Volm_Flood( this=%p, iParams=%p )", this, iParams)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((iParams->mfSourceValue >= this->mfMinValue && iParams->mfSourceValue <= this->mfMaxValue), - eResult, - Volm_tErr_InvalidParamater); - if (NULL == iParams->mComparatorFunc) { - DebugAssertThrowX((iParams->mComparatorType > Volm_tValueComparator_Invalid && - iParams->mComparatorType < Volm_knNumValueComparators), - eResult, - Volm_tErr_InvalidParamater); - } - if (FALSE == iParams->mb3D) { - DebugAssertThrowX((iParams->mOrientation > mri_tOrientation_None && iParams->mOrientation < mri_knNumOrientations), - eResult, - Volm_tErr_InvalidParamater); - } - DebugAssertThrowX((iParams->mpFunction != NULL), eResult, Volm_tErr_InvalidParamater); - - /* Init a volume to keep track of visited voxels */ - DebugNote(("Allocating visited volume")); - nSize = this->mnDimensionX * this->mnDimensionY * this->mnDimensionZ; - visited = (tBoolean *)malloc(sizeof(tBoolean) * nSize); - DebugAssertThrowX((NULL != visited), eResult, Volm_tErr_AllocationFailed); - - DebugNote(("Zeroing visited volume")); - memset(visited, 0, nSize * sizeof(tBoolean)); - - /* Initialize the list of voxels. Create a new voxel, copy our - source into it, and put it in the list. */ - xList_New(&list); - xVoxl_New(&newVoxel); - xVoxl_Copy(newVoxel, &iParams->mSourceIdx); - xList_PushItem(list, newVoxel); - - /* Start going through the list. */ - pCurVoxel = NULL; - eList = xList_tErr_NoErr; - while (xList_tErr_NoErr == eList) { - /* Try to pop a voxel off the list. If we get one... */ - eList = xList_PopItem(list, &pCurVoxel); - if (eList == xList_tErr_NoErr && NULL != pCurVoxel) { - /* To avoid type punning, which is bad. */ - curVoxel = (xVoxelRef)pCurVoxel; - - /* Make sure it's in bounds. */ - if (Volm_tErr_NoErr != Volm_VerifyMRIIdx_(this, curVoxel)) { - continue; - } - - /* If we've already been here, continue. If not, mark our visited - volume and continue. */ - nVisitedIndex = xVoxl_ExpandToIndex(curVoxel, this->mnDimensionZ, this->mnDimensionY); - if (visited[nVisitedIndex]) { - continue; - } - visited[nVisitedIndex] = TRUE; - - /* Get the value and do the comparison. If we have a type and - not a function, just look at the values. Otherwise call the - comparator function they gave us. If it's okay, go on, if - not, continue. */ - Volm_GetValueAtMRIIdx_(this, curVoxel, &fValue); - if (NULL != iParams->mComparatorFunc) { - /* Call the comparator function they gave us. If it returns - false, continue. */ - if (FALSE == iParams->mComparatorFunc(curVoxel, fValue, iParams->mComparatorFuncData)) { - continue; - } - } - else { - /* Compare ths source value and the original value. */ - switch (iParams->mComparatorType) { - case Volm_tValueComparator_LTE: - if (!(fValue <= iParams->mfSourceValue + iParams->mfFuzziness)) { - continue; - } - break; - case Volm_tValueComparator_EQ: - if (!(iParams->mfSourceValue - iParams->mfFuzziness <= fValue && - fValue <= iParams->mfSourceValue + iParams->mfFuzziness)) { - continue; - } - break; - case Volm_tValueComparator_GTE: - if (!(fValue >= iParams->mfSourceValue - iParams->mfFuzziness)) { - continue; - } - break; - default: - break; - } - } - - /* Check distance if >0. if it's over our max distance, exit. */ - if (iParams->mfMaxDistance > 0) { - fDistance = sqrt(((xVoxl_GetX(curVoxel) - xVoxl_GetX(&(iParams->mSourceIdx))) * - (xVoxl_GetX(curVoxel) - xVoxl_GetX(&(iParams->mSourceIdx)))) + - ((xVoxl_GetY(curVoxel) - xVoxl_GetY(&(iParams->mSourceIdx))) * - (xVoxl_GetY(curVoxel) - xVoxl_GetY(&(iParams->mSourceIdx)))) + - ((xVoxl_GetZ(curVoxel) - xVoxl_GetZ(&(iParams->mSourceIdx))) * - (xVoxl_GetZ(curVoxel) - xVoxl_GetZ(&(iParams->mSourceIdx))))); - if (fDistance > iParams->mfMaxDistance) { - continue; - } - } - - /* This is good, so call the user function. Handle their return code. */ - eVisit = iParams->mpFunction(curVoxel, fValue, iParams->mpFunctionData); - switch (eVisit) { - case Volm_tVisitComm_SkipRestOfRow: - case Volm_tVisitComm_SkipRestOfPlane: - DebugThrowX(eResult, Volm_tErr_FloodVisitCommandNotSupported); - break; - case Volm_tVisitComm_Stop: - goto cleanup; - break; - default: - break; - } - - /* Calc our bounds */ - nBeginX = MAX(xVoxl_GetX(curVoxel) - 1, 0); - nEndX = MIN(xVoxl_GetX(curVoxel) + 1, this->mnDimensionX); - nBeginY = MAX(xVoxl_GetY(curVoxel) - 1, 0); - nEndY = MIN(xVoxl_GetY(curVoxel) + 1, this->mnDimensionY); - nBeginZ = MAX(xVoxl_GetZ(curVoxel) - 1, 0); - nEndZ = MIN(xVoxl_GetZ(curVoxel) + 1, this->mnDimensionZ); - - /* If we're not in 3d, limit one of them based on the orientation */ - if (!iParams->mb3D) { - switch (iParams->mOrientation) { - case mri_tOrientation_Coronal: - nBeginZ = nEndZ = xVoxl_GetZ(curVoxel); - break; - case mri_tOrientation_Horizontal: - nBeginY = nEndY = xVoxl_GetY(curVoxel); - break; - case mri_tOrientation_Sagittal: - nBeginX = nEndX = xVoxl_GetX(curVoxel); - break; - default: - goto cleanup; - break; - } - } - - /* Check the surrounding voxels. For each one, create a new - voxel and add it to the list. */ - for (nZ = nBeginZ; nZ <= nEndZ; nZ++) { - for (nY = nBeginY; nY <= nEndY; nY++) { - for (nX = nBeginX; nX <= nEndX; nX++) { - xVoxl_Set(&idx, nX, nY, nZ); - if (Volm_VerifyIdx_(this, &idx) == Volm_tErr_NoErr) { - xVoxl_New(&newVoxel); - xVoxl_Set(newVoxel, nX, nY, nZ); - xList_PushItem(list, newVoxel); - } - } - } - } - /* Delete the current voxel. */ - xVoxl_Delete(&curVoxel); - } - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - if (NULL != visited) { - DebugNote(("Freeing visited volume")); - free(visited); - } - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_VisitAllVoxels(mriVolumeRef this, Volm_tVisitFunction iFunc, void *ipData) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - Volm_tVisitCommand eVisit = Volm_tVisitComm_Continue; - tBoolean bGo = TRUE; - xVoxel idx; - float value = 0; - - DebugEnterFunction(("Volm_tVisitFunction( this=%p, iFunc=%p, ipData=%p )", this, iFunc, ipData)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != iFunc), eResult, Volm_tErr_InvalidParamater); - - /* go thru the volume. get the value and if it matches our index, - add it to the selection. */ - xVoxl_Set(&idx, 0, 0, 0); - bGo = TRUE; - while (bGo) { - Volm_GetValueAtIdx_(this, &idx, &value); - eVisit = iFunc(&idx, value, ipData); - - /* look at the result code they gave us. see if they want us to continue - or skip a row. if skip, increment the voxel coordinate to the end. the - next call to Increment will pop it over into to the next - row or plane. */ - switch (eVisit) { - case Volm_tVisitComm_Continue: - bGo = xVoxl_IncrementUntilLimits(&idx, this->mnDimensionX - 1, this->mnDimensionY - 1, this->mnDimensionZ - 1); - continue; - break; - case Volm_tVisitComm_SkipRestOfRow: - idx.mfX = this->mnDimensionX - 1; - bGo = xVoxl_IncrementUntilLimits(&idx, this->mnDimensionX - 1, this->mnDimensionY - 1, this->mnDimensionZ - 1); - break; - case Volm_tVisitComm_SkipRestOfPlane: - idx.mfX = this->mnDimensionX - 1; - idx.mfY = this->mnDimensionY - 1; - bGo = xVoxl_IncrementUntilLimits(&idx, this->mnDimensionX - 1, this->mnDimensionY - 1, this->mnDimensionZ - 1); - break; - case Volm_tVisitComm_Stop: - bGo = FALSE; - break; - default: - break; - } - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_FindMaxValues(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - float value = 0; - int nX = 0; - int nY = 0; - int nZ = 0; - xVoxel MRI; -#ifdef Solaris - int i = 0; -#endif - - DebugEnterFunction(("Volm_FindMaxValues( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* make sure we have our normalized volume */ - DebugAssertThrowX((NULL != this->mpMriValues), eResult, Volm_tErr_MRIVolumeNotPresent); - - /* Allocate our buffers. */ - if (NULL != this->mpMaxValuesX) { - free(this->mpMaxValuesX); - } - if (NULL != this->mpMaxValuesY) { - free(this->mpMaxValuesY); - } - if (NULL != this->mpMaxValuesZ) { - free(this->mpMaxValuesZ); - } - - this->mpMaxValuesX = (float **)calloc(this->mnDimensionY, sizeof(float *)); - DebugAssertThrowX((NULL != this->mpMaxValuesX), eResult, Volm_tErr_AllocationFailed); - for (nY = 0; nY < this->mnDimensionY; nY++) { - this->mpMaxValuesX[nY] = (float *)calloc(this->mnDimensionZ, sizeof(float *)); - DebugAssertThrowX((NULL != this->mpMaxValuesX[nY]), eResult, Volm_tErr_AllocationFailed); - } - - this->mpMaxValuesY = (float **)calloc(this->mnDimensionX, sizeof(float *)); - DebugAssertThrowX((NULL != this->mpMaxValuesY), eResult, Volm_tErr_AllocationFailed); - for (nX = 0; nX < this->mnDimensionX; nX++) { - this->mpMaxValuesY[nX] = (float *)calloc(this->mnDimensionZ, sizeof(float *)); - DebugAssertThrowX((NULL != this->mpMaxValuesY[nX]), eResult, Volm_tErr_AllocationFailed); - } - - this->mpMaxValuesZ = (float **)calloc(this->mnDimensionX, sizeof(float *)); - DebugAssertThrowX((NULL != this->mpMaxValuesZ), eResult, Volm_tErr_AllocationFailed); - for (nX = 0; nX < this->mnDimensionX; nX++) { - this->mpMaxValuesZ[nX] = (float *)calloc(this->mnDimensionY, sizeof(float *)); - DebugAssertThrowX((NULL != this->mpMaxValuesZ[nX]), eResult, Volm_tErr_AllocationFailed); - } - - /* Go through the volume and select high values. */ - for (nZ = 0; nZ < this->mnDimensionZ; nZ++) { - for (nY = 0; nY < this->mnDimensionY; nY++) { - for (nX = 0; nX < this->mnDimensionX; nX++) { - xVoxl_Set(&MRI, nX, nY, nZ); - Volm_GetValueAtMRIIdx_(this, &MRI, &value); - if (value > this->mpMaxValuesX[nY][nZ]) { - this->mpMaxValuesX[nY][nZ] = value; - } - if (value > this->mpMaxValuesY[nX][nZ]) { - this->mpMaxValuesY[nX][nZ] = value; - } - if (value > this->mpMaxValuesZ[nX][nY]) { - this->mpMaxValuesZ[nX][nY] = value; - } - } - } - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_MakeColorTable(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - float min = 0; - float max = 0; - float thresh = 0; - float squash = 0; - int entry = 0; - float value = 0; - float fComponent = 0; - - DebugEnterFunction(("Volm_MakeColorTable( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* for each value... */ - min = this->mfColorMin; - max = this->mfColorMax; - thresh = this->mfColorBrightness; - squash = this->mfColorContrast; - if (FEQUAL(min, max)) { - for (entry = 0; entry < Volm_knNumColorTableEntries; entry++) { - this->mafColorTable[entry].mfRed = 0; - this->mafColorTable[entry].mfGreen = 0; - this->mafColorTable[entry].mfBlue = 0; - this->manColorTable[entry].mnRed = 0; - this->manColorTable[entry].mnGreen = 0; - this->manColorTable[entry].mnBlue = 0; - } - } - else { - for (entry = 0; entry < Volm_knNumColorTableEntries; entry++) { - /* Get the corresponding value for this entry, where entry 0 = min - and entry Volm_knNumColorTableEntries = max. */ - value = ((entry * (max - min)) / Volm_knNumColorTableEntries) + min; - - /* This is a standard sigma 1 / (1+ exp((x-thresh)*-squash) ) - where x=(value-min)/(max-min) to normalize it to 0-1 within the - range of min->max. This function will populate the 256 - lookuptable entries with intensity values from min->max so - that by lowering the range of min->max, you increase the - granularity of intensities in the visible values. */ - fComponent = (1.0 / (1.0 + exp((((value - min) / (max - min)) - thresh) * -squash))); - - /* set the float color */ - this->mafColorTable[entry].mfRed = fComponent; - this->mafColorTable[entry].mfGreen = fComponent; - this->mafColorTable[entry].mfBlue = fComponent; - - /* normalize to 0 - 255 pixel value */ - fComponent = (float)fComponent * 255.0; - - /* set the integer color */ - this->manColorTable[entry].mnRed = (int)fComponent; - this->manColorTable[entry].mnGreen = (int)fComponent; - this->manColorTable[entry].mnBlue = (int)fComponent; - } - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetBrightnessAndContrast(mriVolumeRef this, float ifBrightness, float ifContrast) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_SetBrightnessAndContrast( this=%p, " - "ifBrightness=%.2f, ifContrast=%.2f )", - this, - ifBrightness, - ifContrast)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* set the values */ - this->mfColorBrightness = ifBrightness; - this->mfColorContrast = ifContrast; - - /* recalc the color table */ - eResult = Volm_MakeColorTable(this); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetColorMinMax(mriVolumeRef this, float ifMin, float ifMax) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_SetColorMinMax( this=%p, " - "ifMin=%.2f, ifMax=%.2f )", - this, - ifMin, - ifMax)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - -/* No longer make the check so that a script can set the values - outside of the bounds to be consistent over different volumes. */ -#if 0 - DebugNote( ("Checking if min is okay") ); - DebugAssertThrowX( (rint(ifMin) >= rint(this->mfMinValue) && - rint(ifMin) <= rint(this->mfMaxValue)), - eResult, Volm_tErr_InvalidParamater ); - DebugNote( ("Checking if max is okay") ); - DebugAssertThrowX( (rint(ifMax) >= rint(this->mfMinValue) && - rint(ifMax) <= rint(this->mfMaxValue)), - eResult, Volm_tErr_InvalidParamater ); -#endif - - /* set the values */ - this->mfColorMin = ifMin; - this->mfColorMax = ifMax; - - /* recalc the color table */ - eResult = Volm_MakeColorTable(this); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_GetBrightnessAndContrast(mriVolumeRef this, float *ofBrightness, float *ofContrast) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_getBrightnessAndContrast( this=%p, " - "ofBrightness=%p, ofContrast=%p )", - this, - ofBrightness, - ofContrast)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - DebugAssertThrowX((NULL != ofBrightness && NULL != ofContrast), eResult, Volm_tErr_InvalidParamater); - - /* return the values */ - *ofBrightness = this->mfColorBrightness; - *ofContrast = this->mfColorContrast; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SaveToSnapshot(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - int nSize = 0; - - DebugEnterFunction(("Volm_SaveToSnapshot( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* if we have snapshot data, delete it */ - if (NULL != this->mpSnapshot) { - free(this->mpSnapshot); - } - - /* make a buffer the same size as the slices buffer. */ - nSize = this->mpMriValues->width * this->mpMriValues->height * this->mpMriValues->depth; - switch (this->mpMriValues->type) { - case MRI_SHORT: - nSize *= sizeof(short); - break; - case MRI_FLOAT: - nSize *= sizeof(float); - break; - case MRI_LONG: - nSize *= sizeof(long); - break; - case MRI_INT: - nSize *= sizeof(int); - break; - default: - break; - } - this->mpSnapshot = (float *)malloc(nSize); - DebugAssertThrowX((NULL != this->mpSnapshot), eResult, Volm_tErr_AllocationFailed); - - /* copy it in */ - memmove(this->mpSnapshot, this->mpMriValues->slices, nSize); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_RestoreFromSnapshot(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - int nSize = 0; - - DebugEnterFunction(("Volm_RestoreFromSnapshot( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* if we don't have a snapshot, return. */ - if (NULL == this->mpSnapshot) { - DebugGotoCleanup; - } - - /* copy the snapshot data into the norm volume buffer data */ - nSize = this->mpMriValues->width * this->mpMriValues->height * this->mpMriValues->depth; - switch (this->mpMriValues->type) { - case MRI_SHORT: - nSize *= sizeof(short); - break; - case MRI_FLOAT: - nSize *= sizeof(float); - break; - case MRI_LONG: - nSize *= sizeof(long); - break; - case MRI_INT: - nSize *= sizeof(int); - break; - default: - break; - } - memmove(this->mpMriValues->slices, this->mpSnapshot, nSize); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_Rotate(mriVolumeRef this, mri_tOrientation iAxis, float ifDegrees) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - MRI *newNorm = NULL; - float fRadians = 0; - - DebugEnterFunction(("Volm_Rotate( this=%p, iAxis=%d, ifDegrees=%.2f )", this, iAxis, ifDegrees)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* convert to radians */ - fRadians = (ifDegrees / 180.0) * M_PI; - - /* switch on the axis and pass to the approriate mri function */ - switch (iAxis) { - case mri_tOrientation_Coronal: - DebugNote(("Rotating normalized volume with MRIrotateY")); - newNorm = MRIrotateY(this->mpMriValues, NULL, fRadians); - break; - case mri_tOrientation_Horizontal: - DebugNote(("Rotating normalized volume with MRIrotateZ")); - newNorm = MRIrotateZ(this->mpMriValues, NULL, fRadians); - break; - case mri_tOrientation_Sagittal: - DebugNote(("Rotating normalized volume with MRIrotateX")); - newNorm = MRIrotateX(this->mpMriValues, NULL, fRadians); - break; - default: - DebugAssertThrowX((1), eResult, Volm_tErr_InvalidParamater); - break; - } - - /* reassign to the new volume */ - DebugNote(("Freeing old normalized volume and assigned rotated one")); - MRIfree(&this->mpMriValues); - this->mpMriValues = newNorm; - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_Threshold(mriVolumeRef this, float iThreshold, tBoolean ibAbove, float iNewValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - float value = 0; - xVoxel idx; - - DebugEnterFunction( - ("Volm_Threshold( this=%p, iThreshold=%d, ibAbove=%d, " - "iNewValue=%d )", - this, - (int)iThreshold, - (int)ibAbove, - (int)iNewValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* step through the volume... */ - xVoxl_Set(&idx, 0, 0, 0); - DebugNote(("Thresholding normalized volume")); - while (xVoxl_IncrementUntilLimits(&idx, this->mnDimensionX - 1, this->mnDimensionY - 1, this->mnDimensionZ - 1)) { - Volm_GetValueAtMRIIdx_(this, &idx, &value); - - /* if we're going above and this value is above the thresh, or if we're - going below and this value is below the thresh...*/ - if ((ibAbove && value > iThreshold) || (!ibAbove && value < iThreshold)) { - /* set the value to the new level. */ - Volm_SetValueAtMRIIdx_(this, &idx, iNewValue); - } - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_Flip(mriVolumeRef this, mri_tOrientation iAxis) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - float value = 0; - float flippedValue = 0; - xVoxel idx; - xVoxel flippedIdx; - int nXLimit = 0; - int nYLimit = 0; - int nZLimit = 0; - - flippedIdx.mfX = 0; - flippedIdx.mfY = 0; - flippedIdx.mfZ = 0; - - DebugEnterFunction(("Volm_Flip( this=%p, iAxis=%d )", this, (int)iAxis)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* get our limits */ - nXLimit = this->mnDimensionX - 1; - nYLimit = this->mnDimensionY - 1; - nZLimit = this->mnDimensionZ - 1; - switch (iAxis) { - case mri_tOrientation_Coronal: - nZLimit = (this->mnDimensionZ - 1) / 2; - break; - case mri_tOrientation_Sagittal: - nXLimit = (this->mnDimensionX - 1) / 2; - break; - case mri_tOrientation_Horizontal: - nYLimit = (this->mnDimensionY - 1) / 2; - break; - default: - DebugAssertThrowX((1), eResult, Volm_tErr_InvalidParamater); - break; - } - - /* step through the volume... */ - xVoxl_Set(&idx, 0, 0, 0); - DebugNote(("Flipping normalized volume")); - while (xVoxl_IncrementUntilLimits(&idx, nXLimit, nYLimit, nZLimit)) { - switch (iAxis) { - case mri_tOrientation_Coronal: - xVoxl_Set(&flippedIdx, xVoxl_GetX(&idx), xVoxl_GetY(&idx), this->mnDimensionZ - 1 - xVoxl_GetZ(&idx)); - break; - case mri_tOrientation_Sagittal: - xVoxl_Set(&flippedIdx, this->mnDimensionX - 1 - xVoxl_GetX(&idx), xVoxl_GetY(&idx), xVoxl_GetZ(&idx)); - break; - case mri_tOrientation_Horizontal: - xVoxl_Set(&flippedIdx, xVoxl_GetX(&idx), this->mnDimensionY - 1 - xVoxl_GetY(&idx), xVoxl_GetZ(&idx)); - break; - default: - DebugAssertThrowX((1), eResult, Volm_tErr_InvalidParamater); - break; - } - - /* swap the values */ - Volm_GetValueAtIdx_(this, &idx, &value); - Volm_GetValueAtIdx_(this, &flippedIdx, &flippedValue); - Volm_SetValueAtIdx_(this, &idx, flippedValue); - Volm_SetValueAtIdx_(this, &flippedIdx, value); - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetAllValues(mriVolumeRef this, float iNewValue) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_SetAllValues( this=%p, iNewValue=%d )", this, (int)iNewValue)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Calling MRIsetValues")); - MRIsetValues(this->mpMriValues, nint(iNewValue)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_CopySubjectName(mriVolumeRef this, char *oSubjectName, int inDestLen) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_CopySubjectName( this=%p, oSubjectName=%s, " - "inDestLen=%d )", - this, - oSubjectName, - inDestLen)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((oSubjectName != NULL), eResult, Volm_tErr_InvalidParamater); - - DebugNote(("Copying subject name")); - xUtil_strncpy(oSubjectName, this->msSubjectName, inDestLen); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_CopyVolumeName(mriVolumeRef this, char *oVolumeName, int inDestLen) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_CopyVolumeName( this=%p, oVolumeName=%s, " - "inDestLen=%d )", - this, - oVolumeName, - inDestLen)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((oVolumeName != NULL), eResult, Volm_tErr_InvalidParamater); - - DebugNote(("Copying volume name")); - xUtil_strncpy(oVolumeName, this->msVolumeName, inDestLen); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_CopySourceDir(mriVolumeRef this, char *oSourceDir, int inDestLen) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction( - ("Volm_CopySourceDir( this=%p, oSourceDir=%s, " - "inDestLen=%d )", - this, - oSourceDir, - inDestLen)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((oSourceDir != NULL), eResult, Volm_tErr_InvalidParamater); - - DebugNote(("Copying source dir")); - xUtil_strncpy(oSourceDir, this->msOriginalPath, inDestLen); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((1), eResult, Volm_tErr_InvalidParamater); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetSubjectName(mriVolumeRef this, char *isName) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_SetSubjectName( this=%p, isName=%s )", this, isName)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((isName != NULL), eResult, Volm_tErr_InvalidParamater); - - /* copy the name */ - xUtil_strncpy(this->msSubjectName, isName, mri_knSubjectNameLen); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetVolumeName(mriVolumeRef this, char *isName) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_SetVolumeName( this=%p, isName=%s )", this, isName)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((isName != NULL), eResult, Volm_tErr_InvalidParamater); - - /* copy the name */ - xUtil_strncpy(this->msVolumeName, isName, mri_knSubjectNameLen); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ExtractAndSetSubjectName(mriVolumeRef this, char *isSource) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - int nChar = 0; - int nWordChar = 0; - char *sWord = NULL; - char sName[256] = ""; - int nLastSlash = 0; - - DebugEnterFunction(("Volm_ExtractAndSetSubjectName( this=%p, isSource=%s)", this, isSource)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != isSource), eResult, Volm_tErr_InvalidParamater); - - /* look for /mri in the title */ - DebugNote(("Looking for /mri in source")); - sWord = strstr(isSource, "/mri"); - if (NULL != sWord) { - /* we're at the slash now. go to the slash before this one. while - we're not at the beginning.. */ - DebugNote(("Going to the slash before /mri")); - while (sWord != isSource) { - sWord -= sizeof(char); - if (*sWord == '/') { - break; - } - } - - /* inc past the slash and use the next part as the name */ - sWord += sizeof(char); - nWordChar = 0; - DebugNote(("Copying in the part after the slash before /mri to /mri")); - while (*sWord != '/' && *sWord != '\0') { - sName[nWordChar] = *sWord; - nWordChar++; - sWord += sizeof(char); - } - } - else { - /* look for 'subjects' in the title */ - DebugNote(("Looking for subjects/ in source")); - sWord = strstr(isSource, "subjects/"); - if (NULL != sWord) { - /* we're at the s in subjects now. scoot ahead to the slash. */ - DebugNote(("Scooting ahead to the slash")); - nChar = 0; - while (sWord[nChar] != '/' && sWord[nChar] != '\0') { - nChar++; - } - - /* if found, use the next part as the name */ - DebugNote(("Copying in chars from subjects/ to the next /")); - nWordChar = 0; - nChar++; /* get past the slash */ - while (sWord[nChar] != '/' && sWord[nChar] != '\0') { - sName[nWordChar] = sWord[nChar]; - nWordChar++; - nChar++; - } - } - else { - /* else just use the last part */ - nChar = 0; - DebugNote(("Scooting to last slash")); - while (isSource[nChar] != '\0') { - if (isSource[nChar] == '/') { - nLastSlash = nChar; - } - nChar++; - } - - /* if we got it, use it, else use the whole source. */ - if (isSource[nLastSlash] == '/') { - DebugNote(("Copying everything from last slash to end of source")); - xUtil_strncpy(sName, &(isSource[nLastSlash + 1]), sizeof(sName)); - } - else { - DebugNote(("Copying entire source")); - xUtil_strncpy(sName, isSource, sizeof(sName)); - } - } - } - - /* set the subject name */ - DebugNote(("Copying result into subject name")); - xUtil_strncpy(this->msSubjectName, sName, sizeof(this->msSubjectName)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_ExtractAndSetVolumeName(mriVolumeRef this, char *isSource) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - int nChar = 0; - int nLastSlash = 0; - - DebugEnterFunction(("Volm_ExtractAndSetVolumeName( this=%p, isSource=%s )", this, isSource)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugNote(("Checking parameters")); - DebugAssertThrowX((NULL != isSource), eResult, Volm_tErr_InvalidParamater); - - /* look for the last / */ - DebugNote(("Looking for last slash")); - while (isSource[nChar] != '\0') { - if (isSource[nChar] == '/') { - nLastSlash = nChar; - } - nChar++; - } - - /* if we got one, everything from there+1 into the subjectname, - otherwise just use the whole name */ - if (isSource[nLastSlash] == '/') { - DebugNote(("Copying in source name from char %d", nLastSlash + 1)); - xUtil_strncpy(this->msVolumeName, &(isSource[nLastSlash + 1]), sizeof(this->msVolumeName)); - } - else { - DebugNote(("Copying in whole source name")); - xUtil_strncpy(this->msVolumeName, isSource, sizeof(this->msVolumeName)); - } - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_SetMinVoxelSizeToOne(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - float scale, fov_x, fov_y, fov_z; - - DebugEnterFunction(("Volm_SetMinVoxelSizeToOne( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* Calculate the scale factor and size the xyzsize values. */ - scale = 1.0 / MIN(MIN(this->mpMriValues->xsize, this->mpMriValues->ysize), this->mpMriValues->zsize); - printf("scaling voxel sizes up by %2.2f\n", scale); - this->mpMriValues->xsize *= scale; - this->mpMriValues->ysize *= scale; - this->mpMriValues->zsize *= scale; - - /* Find the fov for each dimension. */ - fov_x = this->mpMriValues->xsize * this->mpMriValues->width; - fov_y = this->mpMriValues->ysize * this->mpMriValues->height; - fov_z = this->mpMriValues->zsize * this->mpMriValues->depth; - - /* Recalc the bounds. */ - this->mpMriValues->xend = fov_x / 2.0; - this->mpMriValues->xstart = -this->mpMriValues->xend; - this->mpMriValues->yend = fov_y / 2.0; - this->mpMriValues->ystart = -this->mpMriValues->yend; - this->mpMriValues->zend = fov_z / 2.0; - this->mpMriValues->zstart = -this->mpMriValues->zend; - - /* Find the overall fov. */ - this->mpMriValues->fov = (fov_x > fov_y ? (fov_x > fov_z ? fov_x : fov_z) : (fov_y > fov_z ? fov_y : fov_z)); - - /* Set from the newly fov'd MRI. */ - DebugNote(("Setting from MRI")); - eResult = Volm_SetFromMRI_(this, this->mpMriValues); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_Conform(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - MRI *conformed = NULL; - - DebugEnterFunction(("Volm_Conform( this=%p )", this)); - - DebugNote(("Verifying volume")); - eResult = Volm_Verify(this); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - /* Call the conform function. */ - DebugNote(("Conforming MRI")); - conformed = MRIconform(this->mpMriValues); - DebugAssertThrowX((NULL != conformed), eResult, Volm_tErr_CouldntReadVolume); - - /* Set from the newly conformed MRI. */ - DebugNote(("Setting from MRI")); - eResult = Volm_SetFromMRI_(this, conformed); - DebugAssertThrow((eResult == Volm_tErr_NoErr)); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -/* ======================================== BEGIN FUNCTION VERION OF MACROS */ -#ifndef VOLM_USE_MACROS - -void Volm_ConvertScreenIdxToMRIIdx_(mriVolumeRef this, xVoxelRef iScreenIdx, xVoxelRef oMRIIdx) -{ - /* Stuff the screen index. */ - DebugNote(("Stuffing iScreenIdx into vector")); - *MATRIX_RELT(this->mpTmpScreenIdx, 1, 1) = xVoxl_GetFloatX(iScreenIdx); - *MATRIX_RELT(this->mpTmpScreenIdx, 2, 1) = xVoxl_GetFloatY(iScreenIdx); - *MATRIX_RELT(this->mpTmpScreenIdx, 3, 1) = xVoxl_GetFloatZ(iScreenIdx); - *MATRIX_RELT(this->mpTmpScreenIdx, 4, 1) = 1.0; - - /* Multiple by the resample matrix. */ - DebugNote(("Multiplying screen index by resample matrix")); - MatrixMultiply(this->m_resample, this->mpTmpScreenIdx, this->mpTmpMRIIdx); - - /* Stuff the outgoing voxel */ - DebugNote(("Stuffing result vector into voxel")); - xVoxl_SetFloat(oMRIIdx, - *MATRIX_RELT(this->mpTmpMRIIdx, 1, 1), - *MATRIX_RELT(this->mpTmpMRIIdx, 1, 2), - *MATRIX_RELT(this->mpTmpMRIIdx, 1, 3)); - - DebugNote(("Checking mri idx")); - if ((xVoxl_GetX(oMRIIdx) < 0 || xVoxl_GetX(oMRIIdx) >= this->mnDimensionX || xVoxl_GetY(oMRIIdx) < 0 || - xVoxl_GetY(oMRIIdx) >= this->mnDimensionY || xVoxl_GetZ(oMRIIdx) < 0 || - xVoxl_GetZ(oMRIIdx) >= this->mnDimensionZ)) { - xVoxl_Set(oMRIIdx, 0, 0, 0); - } -} - -void Volm_ConvertMRIIdxToScreenIdx_(mriVolumeRef this, xVoxelRef iMRIIdx, xVoxelRef oScreenIdx) -{ - /* Stuff the mri index. */ - DebugNote(("Stuffing iMRIIdx into vector")); - *MATRIX_RELT(this->mpTmpMRIIdx, 1, 1) = xVoxl_GetFloatX(iMRIIdx); - *MATRIX_RELT(this->mpTmpMRIIdx, 2, 1) = xVoxl_GetFloatY(iMRIIdx); - *MATRIX_RELT(this->mpTmpMRIIdx, 3, 1) = xVoxl_GetFloatZ(iMRIIdx); - *MATRIX_RELT(this->mpTmpMRIIdx, 4, 1) = 1.0; - - /* Multiple by the inverse resample matrix. */ - DebugNote(("Multiplying mri index by inverse resample matrix")); - MatrixMultiply(this->m_resample_inv, this->mpTmpMRIIdx, this->mpTmpScreenIdx); - - /* Stuff the outgoing voxel */ - DebugNote(("Stuffing result vector into voxel")); - xVoxl_SetFloat(oScreenIdx, - *MATRIX_RELT(this->mpTmpScreenIdx, 1, 1), - *MATRIX_RELT(this->mpTmpScreenIdx, 1, 2), - *MATRIX_RELT(this->mpTmpScreenIdx, 1, 3)); - - DebugNote(("Checking screen idx")); - if ((xVoxl_GetX(oScreenIdx) < 0 || xVoxl_GetX(oScreenIdx) >= 256 || xVoxl_GetY(oScreenIdx) < 0 || - xVoxl_GetY(oScreenIdx) >= 256 || xVoxl_GetZ(oScreenIdx) < 0 || xVoxl_GetZ(oScreenIdx) >= 256)) { - xVoxl_Set(oScreenIdx, 0, 0, 0); - } -} - -void Volm_GetValueAtIdx_(mriVolumeRef this, xVoxelRef iIdx, float *oValue) -{ - int x, y, z; - - /* First convert to MRI index, and then switch on the volume data - type and use the proper MRIvox access function to get the - value. */ - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &this->mTmpVoxel); - - x = xVoxl_GetX(&this->mTmpVoxel); - y = xVoxl_GetY(&this->mTmpVoxel); - z = xVoxl_GetZ(&this->mTmpVoxel); - - switch (this->mpMriValues->type) { - case MRI_UCHAR: - *oValue = MRIvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)); - break; - case MRI_INT: - *oValue = MRIIvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)); - break; - case MRI_LONG: - *oValue = MRILvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)); - break; - case MRI_FLOAT: - *oValue = MRIFvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)); - break; - case MRI_SHORT: - *oValue = MRISvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)); - break; - default: - *oValue = 0; - break; - } -} - -void Volm_GetValueAtMRIIdx_(mriVolumeRef this, xVoxelRef iMRIIdx, float *oValue) -{ - switch (this->mpMriValues->type) { - case MRI_UCHAR: - *oValue = MRIvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)); - break; - case MRI_INT: - *oValue = MRIIvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)); - break; - case MRI_LONG: - *oValue = MRILvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)); - break; - case MRI_FLOAT: - *oValue = MRIFvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)); - break; - case MRI_SHORT: - *oValue = MRISvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)); - break; - default: - *oValue = 0; - break; - } -} - -void Volm_GetValueAtIdxFrame_(mriVolumeRef this, xVoxelRef iIdx, int iFrame, float *oValue) -{ - /* First convert to MRI index, and then switch on the volume data - type and use the proper MRIvox access function to get the - value. */ - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &this->mTmpVoxel); - - switch (this->mpMriValues->type) { - case MRI_UCHAR: - *oValue = MRIseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame); - break; - case MRI_INT: - *oValue = MRIIseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame); - break; - case MRI_LONG: - *oValue = MRILseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame); - break; - case MRI_FLOAT: - *oValue = MRIFseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame); - break; - case MRI_SHORT: - *oValue = MRISseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame); - break; - default: - *oValue = 0; - break; - } -} - -void Volm_GetSampledValueAtIdx_(mriVolumeRef this, xVoxelRef iIdx, float *oValue) -{ - double value; - - /* First convert to MRI index, then use the MRI access function to - get the sinc value. */ - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &this->mTmpVoxel); - - MRIsampleVolumeType(this->mpMriValues, - xVoxl_GetFloatX(&this->mTmpVoxel), - xVoxl_GetFloatY(&this->mTmpVoxel), - xVoxl_GetFloatZ(&this->mTmpVoxel), - &value, - (int)this->mSampleType); - - *oValue = (float)value; -} - -void Volm_GetSampledValueAtIdxFrame_(mriVolumeRef this, xVoxelRef iIdx, int iFrame, float *oValue) -{ - double value; - - /* First convert to MRI index, then use the MRI access function to - get the sinc value. */ - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &this->mTmpVoxel); - - MRIsampleVolumeFrameType(this->mpMriValues, - xVoxl_GetFloatX(&this->mTmpVoxel), - xVoxl_GetFloatY(&this->mTmpVoxel), - xVoxl_GetFloatZ(&this->mTmpVoxel), - iFrame, - (int)this->mSampleType, - &value); - - *oValue = (float)value; -} - -void Volm_SetValueAtIdx_(mriVolumeRef this, xVoxelRef iIdx, float iValue) -{ - /* First convert to MRI index, and then switch on the volume data - type and use the proper MRIvox access function to set the - value. */ - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &this->mTmpVoxel); - - switch (this->mpMriValues->type) { - default: - break; - case MRI_UCHAR: - MRIvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)) = - (BUFTYPE)iValue; - break; - case MRI_SHORT: - MRISvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)) = - (short)iValue; - break; - case MRI_FLOAT: - MRIFvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)) = - (float)iValue; - break; - case MRI_LONG: - MRILvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)) = - (long)iValue; - break; - case MRI_INT: - MRIIvox( - this->mpMriValues, xVoxl_GetX(&this->mTmpVoxel), xVoxl_GetY(&this->mTmpVoxel), xVoxl_GetZ(&this->mTmpVoxel)) = - (int)iValue; - break; - } -} - -void Volm_SetValueAtMRIIdx_(mriVolumeRef this, xVoxelRef iMRIIdx, float iValue) -{ - switch (this->mpMriValues->type) { - default: - break; - case MRI_UCHAR: - MRIvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)) = (BUFTYPE)iValue; - break; - case MRI_SHORT: - MRISvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)) = (short)iValue; - break; - case MRI_FLOAT: - MRIFvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)) = (float)iValue; - break; - case MRI_LONG: - MRILvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)) = (long)iValue; - break; - case MRI_INT: - MRIIvox(this->mpMriValues, xVoxl_GetX(iMRIIdx), xVoxl_GetY(iMRIIdx), xVoxl_GetZ(iMRIIdx)) = (int)iValue; - break; - } -} - -void Volm_SetValueAtIdxFrame_(mriVolumeRef this, xVoxelRef iIdx, int iFrame, float iValue) -{ - /* First convert to MRI index, and then switch on the volume data - type and use the proper MRIvox access function to set the - value. */ - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &this->mTmpVoxel); - - switch (this->mpMriValues->type) { - default: - break; - case MRI_UCHAR: - MRIseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame) = (BUFTYPE)iValue; - break; - case MRI_SHORT: - MRISseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame) = (short)iValue; - break; - case MRI_FLOAT: - MRIFseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame) = (float)iValue; - break; - case MRI_LONG: - MRILseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame) = (long)iValue; - break; - case MRI_INT: - MRIIseq_vox(this->mpMriValues, - xVoxl_GetX(&this->mTmpVoxel), - xVoxl_GetY(&this->mTmpVoxel), - xVoxl_GetZ(&this->mTmpVoxel), - iFrame) = (int)iValue; - break; - } -} -#endif /* VOLM_USE_MACROS */ -/* ======================================== END OF FUNCTION VERION OF MACROS */ - -Volm_tErr Volm_Verify(mriVolumeRef this) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugEnterFunction(("Volm_Verify( this=%p )", this)); - - DebugAssertThrowX((NULL != this), eResult, Volm_tErr_InvalidParamater); - DebugAssertThrowX((Volm_kSignature == this->mSignature), eResult, Volm_tErr_InvalidSignature); - - DebugCatch; - DebugCatchError(eResult, Volm_tErr_NoErr, Volm_GetErrorString); - DebugPrintStack; - EndDebugCatch; - - DebugExitFunction; - - return eResult; -} - -Volm_tErr Volm_VerifyIdx(mriVolumeRef this, xVoxelRef iIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - eResult = Volm_Verify(this); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - eResult = Volm_VerifyIdx_(this, iIdx); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - DebugCatch; - EndDebugCatch; - - return eResult; -} - -Volm_tErr Volm_VerifyIdx_(mriVolumeRef this, xVoxelRef iIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - xVoxel mriIdx; - - Volm_ConvertScreenIdxToMRIIdx_(this, iIdx, &mriIdx); - - DebugAssertThrowX((xVoxl_GetX(&mriIdx) >= 0 && xVoxl_GetRoundX(&mriIdx) < this->mnDimensionX && - xVoxl_GetY(&mriIdx) >= 0 && xVoxl_GetRoundY(&mriIdx) < this->mnDimensionY && - xVoxl_GetZ(&mriIdx) >= 0 && xVoxl_GetRoundZ(&mriIdx) < this->mnDimensionZ), - eResult, - Volm_tErr_InvalidIdx); - - DebugCatch; - EndDebugCatch; - return eResult; -} - -Volm_tErr Volm_VerifyMRIIdx_(mriVolumeRef this, xVoxelRef iMRIIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugAssertThrowX((xVoxl_GetX(iMRIIdx) >= 0 && xVoxl_GetRoundX(iMRIIdx) < this->mnDimensionX && - xVoxl_GetY(iMRIIdx) >= 0 && xVoxl_GetRoundY(iMRIIdx) < this->mnDimensionY && - xVoxl_GetZ(iMRIIdx) >= 0 && xVoxl_GetRoundZ(iMRIIdx) < this->mnDimensionZ), - eResult, - Volm_tErr_InvalidIdx); - - DebugCatch; - EndDebugCatch; - return eResult; -} - -Volm_tErr Volm_VerifyIdxInMRIBounds(mriVolumeRef this, xVoxelRef iScreenIdx) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - eResult = Volm_Verify(this); - DebugAssertThrow((Volm_tErr_NoErr == eResult)); - - /* Stuff the screen index. */ - DebugNote(("Stuffing iScreenIdx into vector")); - *MATRIX_RELT(this->mpTmpScreenIdx, 1, 1) = xVoxl_GetFloatX(iScreenIdx); - *MATRIX_RELT(this->mpTmpScreenIdx, 2, 1) = xVoxl_GetFloatY(iScreenIdx); - *MATRIX_RELT(this->mpTmpScreenIdx, 3, 1) = xVoxl_GetFloatZ(iScreenIdx); - *MATRIX_RELT(this->mpTmpScreenIdx, 4, 1) = 1.0; - - /* Multiple by the resample matrix. */ - DebugNote(("Multiplying screen index by resample matrix")); - MatrixMultiply(this->m_resample, this->mpTmpScreenIdx, this->mpTmpMRIIdx); - - /* Stuff the outgoing voxel */ - DebugNote(("Stuffing result vector into voxel")); - xVoxl_SetFloat(&this->mTmpVoxel, - *MATRIX_RELT(this->mpTmpMRIIdx, 1, 1), - *MATRIX_RELT(this->mpTmpMRIIdx, 1, 2), - *MATRIX_RELT(this->mpTmpMRIIdx, 1, 3)); - - DebugNote(("Checking mri idx")); - DebugAssertThrowX((xVoxl_GetX(&this->mTmpVoxel) >= 0 && xVoxl_GetRoundX(&this->mTmpVoxel) < this->mnDimensionX && - xVoxl_GetY(&this->mTmpVoxel) >= 0 && xVoxl_GetRoundY(&this->mTmpVoxel) < this->mnDimensionY && - xVoxl_GetZ(&this->mTmpVoxel) >= 0 && xVoxl_GetRoundZ(&this->mTmpVoxel) < this->mnDimensionZ), - eResult, - Volm_tErr_InvalidIdx); - - DebugCatch; - EndDebugCatch; - - return eResult; -} - -Volm_tErr Volm_VerifyFrame_(mriVolumeRef this, int iFrame) -{ - Volm_tErr eResult = Volm_tErr_NoErr; - - DebugAssertThrowX((iFrame >= 0 && iFrame < this->mnDimensionFrame), eResult, Volm_tErr_InvalidIdx); - - DebugCatch; - EndDebugCatch; - - return eResult; -} - -char *Volm_GetErrorString(Volm_tErr ieCode) -{ - Volm_tErr eCode = ieCode; - - if (ieCode < 0 || ieCode >= Volm_knNumErrorCodes) { - eCode = Volm_tErr_Invalid; - } - - return Volm_ksaErrorStrings[eCode]; -} diff --git a/utils/mri_conform.c b/utils/mri_conform.cpp similarity index 87% rename from utils/mri_conform.c rename to utils/mri_conform.cpp index 250714670bf..b9d0b0b0b32 100644 --- a/utils/mri_conform.c +++ b/utils/mri_conform.cpp @@ -144,22 +144,22 @@ MRI *MRIconform(MRI *mri) MRI *MRIconformedTemplate(MRI *mri, int conform_width, double conform_size, int KeepDC) { - MRI *template; + MRI *mri_template; char ostr[4]; int iLR, iIS, iAP, Nvox[3], FoV[3], conform_FoV, c; double delta[3], pad, step; MATRIX *K, *invK, *Smri, *Stemp; - template = MRIallocHeader(conform_width, conform_width, conform_width, MRI_UCHAR, mri->nframes); - MRIcopyHeader(mri, template); - MRIcopyPulseParameters(mri, template); - template->imnr0 = 1; - template->imnr1 = conform_width; - template->thick = conform_size; - template->ps = conform_size; - template->xsize = template->ysize = template->zsize = conform_size; - template->xstart = template->ystart = template->zstart = -conform_width / 2; - template->xend = template->yend = template->zend = conform_width / 2; + mri_template = MRIallocHeader(conform_width, conform_width, conform_width, MRI_UCHAR, mri->nframes); + MRIcopyHeader(mri, mri_template); + MRIcopyPulseParameters(mri, mri_template); + mri_template->imnr0 = 1; + mri_template->imnr1 = conform_width; + mri_template->thick = conform_size; + mri_template->ps = conform_size; + mri_template->xsize = mri_template->ysize = mri_template->zsize = conform_size; + mri_template->xstart = mri_template->ystart = mri_template->zstart = -conform_width / 2; + mri_template->xend = mri_template->yend = mri_template->zend = conform_width / 2; if (KeepDC) { conform_FoV = conform_width * conform_size; @@ -181,7 +181,7 @@ MRI *MRIconformedTemplate(MRI *mri, int conform_width, double conform_size, int delta[2] = mri->zsize; for (c = 0; c < 3; c++) FoV[c] = Nvox[c] * delta[c]; - // K maps voxels in mri to voxels in template + // K maps voxels in mri to voxels in mri_template K = MatrixAlloc(4, 4, MATRIX_REAL); K->rptr[4][4] = 1; @@ -227,7 +227,7 @@ MRI *MRIconformedTemplate(MRI *mri, int conform_width, double conform_size, int invK = MatrixInverse(K, NULL); Smri = MRIxfmCRS2XYZ(mri, 0); Stemp = MatrixMultiplyD(Smri, invK, NULL); - MRIsetVox2RASFromMatrix(template, Stemp); + MRIsetVox2RASFromMatrix(mri_template, Stemp); printf("K ---------------\n"); MatrixPrint(stdout, K); @@ -246,16 +246,16 @@ MRI *MRIconformedTemplate(MRI *mri, int conform_width, double conform_size, int } else { // replicates old method exactly - template->x_r = -1.0; - template->x_a = 0.0; - template->x_s = 0.0; - template->y_r = 0.0; - template->y_a = 0.0; - template->y_s = -1.0; - template->z_r = 0.0; - template->z_a = 1.0; - template->z_s = 0.0; + mri_template->x_r = -1.0; + mri_template->x_a = 0.0; + mri_template->x_s = 0.0; + mri_template->y_r = 0.0; + mri_template->y_a = 0.0; + mri_template->y_s = -1.0; + mri_template->z_r = 0.0; + mri_template->z_a = 1.0; + mri_template->z_s = 0.0; } - return (template); + return (mri_template); } diff --git a/utils/mri_fastmarching.cpp b/utils/mri_fastmarching.cpp index fb16e47819a..02ee37930d2 100644 --- a/utils/mri_fastmarching.cpp +++ b/utils/mri_fastmarching.cpp @@ -24,20 +24,17 @@ #include "fastmarching.h" -extern "C" MRI *MRIextractDistanceMap( - MRI *mri_src, MRI *mri_dst, int label, float max_distance, int mode, MRI *mri_mask) +MRI *MRIextractDistanceMap(MRI *mri_src, MRI *mri_dst, int label, float max_distance, int mode, MRI *mri_mask) { MRI *mri_distance = NULL; -#if 0 - int free_mri = 0 ; + // int free_mri = 0 ; - if (mri_src->type != MRI_FLOAT) - { - mri_src = MRIchangeType(mri_src, MRI_FLOAT, 0, 1, 1) ; - free_mri = 1 ; - } -#endif + // if (mri_src->type != MRI_FLOAT) + // { + // mri_src = MRIchangeType(mri_src, MRI_FLOAT, 0, 1, 1) ; + // free_mri = 1 ; + // } // make sure that the max distance is greater than 0 if (max_distance <= 0) { diff --git a/utils/mri_identify.c b/utils/mri_identify.cpp similarity index 98% rename from utils/mri_identify.c rename to utils/mri_identify.cpp index 57f88929178..37856f82a4a 100644 --- a/utils/mri_identify.c +++ b/utils/mri_identify.cpp @@ -35,7 +35,7 @@ #include "analyze.h" #include "fio.h" #include "machine.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mrisurf.h" #include "proto.h" #include "signa.h" @@ -52,7 +52,7 @@ int stricmp(char *str1, char *str2); char *type_to_string(int type) { char *typestring; - char *tmpstr; + const char *tmpstr; int lentmp; switch (type) { @@ -588,7 +588,7 @@ int is_cor(const char *fname) int is_brik(const char *fname) { - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot) { @@ -604,7 +604,7 @@ int is_siemens(const char *fname) { FILE *fp; char string[4]; - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot) { @@ -660,7 +660,7 @@ int is_genesis(const char *fname) { FILE *fp; long32 magic; - char *dot; + const char *dot; if (!strncmp(fname, "I.", 2)) return (1); @@ -719,7 +719,8 @@ int is_analyze(const char *fname) { FILE *fp; dsr hdr; - char hfname[STRLEN], *dot; + char hfname[STRLEN]; + const char *dot; long hdr_length; strcpy(hfname, fname); @@ -760,7 +761,7 @@ int is_mnc(const char *fname) { char buf[3]; FILE *fp; - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot) { @@ -830,7 +831,7 @@ int is_mgh(const char *fname) /*--------------------------------------*/ int is_bshort(const char *fname) { - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot) { dot++; @@ -842,7 +843,7 @@ int is_bshort(const char *fname) /*--------------------------------------*/ int is_bfloat(const char *fname) { - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot) { dot++; @@ -853,7 +854,7 @@ int is_bfloat(const char *fname) /*--------------------------------------*/ int is_bhdr(const char *fname) { - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot) { dot++; @@ -1011,7 +1012,7 @@ int is_sdt(const char *fname) int is_gdf(const char *fname) { - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot != NULL) { @@ -1024,7 +1025,7 @@ int is_gdf(const char *fname) int is_otl(const char *fname) { - char *dot; + const char *dot; dot = strrchr(fname, '.'); if (dot != NULL) { @@ -1083,7 +1084,7 @@ int is_nifti1(const char *fname) int is_nii(const char *fname) { - char *dot; + const char *dot; FILE *fp; char magic[4]; @@ -1124,7 +1125,7 @@ int is_nii(const char *fname) int is_nrrd(const char *fname) { - char *dot; + const char *dot; FILE *fp; char magic[4]; @@ -1132,7 +1133,7 @@ int is_nrrd(const char *fname) dot = strrchr(fname, '.'); if (dot != NULL) { - if ((strcmp(dot, ".nrrd") == 0) && (strlen(fname) == dot - fname + 5)) { + if ((strcmp(dot, ".nrrd") == 0) && ((signed)strlen(fname) == dot - fname + 5)) { return (TRUE); } } diff --git a/utils/mri_level_set.c b/utils/mri_level_set.cpp similarity index 100% rename from utils/mri_level_set.c rename to utils/mri_level_set.cpp diff --git a/utils/mri_tess.c b/utils/mri_tess.cpp similarity index 100% rename from utils/mri_tess.c rename to utils/mri_tess.cpp diff --git a/utils/mri_topology.c b/utils/mri_topology.cpp similarity index 100% rename from utils/mri_topology.c rename to utils/mri_topology.cpp diff --git a/utils/mri_transform.c b/utils/mri_transform.c deleted file mode 100644 index 901563d66e5..00000000000 --- a/utils/mri_transform.c +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file mri_transform.c - * @brief transform utils - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:45 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "mri_transform.h" - -static float mfStartX, mfEndX; -static float mfStartY, mfEndY; -static float mfStartZ, mfEndZ; -static float mfSizeX, mfSizeY, mfSizeZ; - -void trans_SetBounds(float ifStartX, float ifEndX, float ifStartY, float ifEndY, float ifStartZ, float ifEndZ) -{ - mfStartX = ifStartX; - mfEndX = ifEndX; - mfStartY = ifStartY; - mfEndY = ifEndY; - mfStartZ = ifStartZ; - mfEndZ = ifEndZ; -} - -void trans_SetResolution(float ifSizeX, float ifSizeY, float ifSizeZ) -{ - mfSizeX = ifSizeX; - mfSizeY = ifSizeY; - mfSizeZ = ifSizeZ; -} - -void trans_RASToVoxelIndex(double irRASX, double irRASY, double irRASZ, int *onVoxX, int *onVoxY, int *onVoxZ) -{ - double orVoxX, orVoxY, orVoxZ; - - trans_RASToVoxel(irRASX, irRASY, irRASZ, &orVoxX, &orVoxY, &orVoxZ); - *onVoxX = (int)orVoxX; - *onVoxY = (int)orVoxY; - *onVoxZ = (int)orVoxZ; -} - -void trans_RASToVoxel(double irRASX, double irRASY, double irRASZ, double *orVoxX, double *orVoxY, double *orVoxZ) -{ - /* we need to stay in the same type so - as not to typecast thee conversion to - int until right at the very end. */ - float fRASX, fRASY, fRASZ; - fRASX = (float)irRASX; - fRASY = (float)irRASY; - fRASZ = (float)irRASZ; - - *orVoxX = ((mfEndX - fRASX) / mfSizeX); - *orVoxY = ((-fRASZ - mfStartY) / mfSizeY); - *orVoxZ = ((fRASY - mfStartZ) / mfSizeZ); -} - -void trans_VoxelToRAS(double irVoxX, double irVoxY, double irVoxZ, double *orRASX, double *orRASY, double *orRASZ) -{ - *orRASX = (double)(mfEndX - (irVoxX * mfSizeX)); - *orRASY = (double)(mfStartZ + (irVoxZ * mfSizeZ)); - *orRASZ = (double)(-(mfStartY + (irVoxY * mfSizeY))); -} - -void trans_VoxelIndexToRAS(int inVoxX, int inVoxY, int inVoxZ, double *orRASX, double *orRASY, double *orRASZ) -{ - // double irVoxX, irVoxY, irVoxZ; - - // irVoxX = (double)inVoxX; - // irVoxY = (double)inVoxY; - // irVoxZ = (double)inVoxZ; - trans_VoxelToRAS(inVoxX, inVoxY, inVoxZ, orRASX, orRASY, orRASZ); -} diff --git a/utils/mriclass.c b/utils/mriclass.cpp similarity index 97% rename from utils/mriclass.c rename to utils/mriclass.cpp index 915bc118c9d..c22511901cf 100644 --- a/utils/mriclass.c +++ b/utils/mriclass.cpp @@ -31,8 +31,6 @@ #include #include -#include "artmap.h" -#include "backprop.h" #include "diag.h" #include "error.h" #include "gclass.h" @@ -68,8 +66,7 @@ typedef struct GLOBAL DATA -------------------------------------------------------*/ -char *class_names[GAUSSIAN_NCLASSES] = { - "CSF", "GREY MATTER", "THIN STRANDS", "BORDER PIXELS", "WHITE MATTER", "BRIGHT MATTER"}; +const char *class_names[GAUSSIAN_NCLASSES] = {"CSF", "GREY MATTER", "THIN STRANDS", "BORDER PIXELS", "WHITE MATTER", "BRIGHT MATTER"}; /*----------------------------------------------------- STATIC DATA @@ -86,7 +83,7 @@ static int mricTrainRBF(MRIC *mric, FILE *fp, int nfiles, int round); static int mricRetrainRBF(MRIC *mric, FILE *fp, int nfiles, int round); static int mricGetClassifierInput(VECTOR *v_inputs, int no, void *parm, int same_class, int *pclass); -static int mricGetClassObservation(GET_INPUT_PARMS *parms, VECTOR *v_obs, int obs_no, int class); +static int mricGetClassObservation(GET_INPUT_PARMS *parms, VECTOR *v_obs, int obs_no, int classnum); static int mricFillInputParms(MRIC *mric, FILE *fp, int round, GET_INPUT_PARMS *parms); /*----------------------------------------------------- @@ -134,7 +131,8 @@ int MRICfree(MRIC **pmric) MRIC *MRICalloc(int nrounds, int *types, int *features, void *parms) { MRIC *mric; - int f, ninputs, round; + unsigned f; + int ninputs, round; mric = (MRIC *)calloc(1, sizeof(MRIC)); if (!mric) ErrorExit(ERROR_NO_MEMORY, "MRICalloc(%d): could not allocate struct", nrounds); @@ -932,7 +930,7 @@ MRI *MRICbuildTargetImage(MRI *mri_src, MRI *mri_target, MRI *mri_wm, int lo_lim MRI *MRICupdatePriors(MRI *mri_target, MRI *mri_priors, int scale) { - int width, height, depth, x, y, z, class, w, h, d, xt, yt, zt; + int width, height, depth, x, y, z, classnum, w, h, d, xt, yt, zt; BUFTYPE *ptarget; double xrt, yrt, zrt; @@ -964,8 +962,8 @@ MRI *MRICupdatePriors(MRI *mri_target, MRI *mri_priors, int scale) xt = mri_priors->xi[nint(xrt / scale)]; yt = mri_priors->yi[nint(yrt / scale)]; zt = mri_priors->zi[nint(zrt / scale)]; - class = *ptarget++; - MRIFseq_vox(mri_priors, xt, yt, zt, class) = MRIFseq_vox(mri_priors, xt, yt, zt, class) + 1.0f; + classnum = *ptarget++; + MRIFseq_vox(mri_priors, xt, yt, zt, classnum) = MRIFseq_vox(mri_priors, xt, yt, zt, classnum) + 1.0f; MRIFseq_vox(mri_priors, xt, yt, zt, COUNT_IMAGE) = MRIFseq_vox(mri_priors, xt, yt, zt, COUNT_IMAGE) + 1.0f; } } @@ -983,7 +981,7 @@ MRI *MRICupdatePriors(MRI *mri_target, MRI *mri_priors, int scale) ------------------------------------------------------*/ int MRInormalizePriors(MRI *mri_priors) { - int width, height, depth, x, y, z, class; + int width, height, depth, x, y, z, classnum; float *pnorm, norm; width = mri_priors->width; @@ -1000,8 +998,8 @@ int MRInormalizePriors(MRI *mri_priors) for (x = 0; x < width; x++) { norm = *pnorm++; if (!FZERO(norm)) - for (class = 0; class < GAUSSIAN_NCLASSES; class ++) { - MRIFseq_vox(mri_priors, x, y, z, class) /= norm; + for (classnum = 0; classnum < GAUSSIAN_NCLASSES; classnum ++) { + MRIFseq_vox(mri_priors, x, y, z, classnum) /= norm; } } } @@ -1121,9 +1119,9 @@ int MRICcomputeStatistics(MRIC *mric, int round) Description ------------------------------------------------------*/ -char *MRICclassName(MRIC *mric, int round, int classno) +const char *MRICclassName(MRIC *mric, int round, int classno) { - char *class_name = "unknown"; + const char *class_name = "unknown"; switch (mric->type[round]) { default: @@ -1175,9 +1173,10 @@ int MRICdump(FILE *fp, MRIC *mric) Description ------------------------------------------------------*/ -char *MRICfeatureName(MRIC *mric, int round, int feature_number) +const char *MRICfeatureName(MRIC *mric, int round, int feature_number) { - int f, fno; + unsigned f; + int fno; /* first ninputs-1 correspond to inputs #s, rest to frames in priors */ @@ -1215,9 +1214,10 @@ char *MRICfeatureName(MRIC *mric, int round, int feature_number) Description ------------------------------------------------------*/ -char *MRICfeatureNumberToName(int feature_number) +const char *MRICfeatureNumberToName(int feature_number) { - int f, fno; + unsigned f; + int fno; /* find bit which corresponds to this # */ for (f = 0x001, fno = 0; f != MAX_FEATURE; f <<= 1) @@ -1264,7 +1264,8 @@ char *MRICfeatureNumberToName(int feature_number) ------------------------------------------------------*/ int MRICfeatureNumberCode(int feature_number) { - int f, fno; + unsigned f; + int fno; /* find bit which corresponds to this # */ for (f = 0x001, fno = 0; f != MAX_FEATURE; f <<= 1) @@ -1284,7 +1285,8 @@ int MRICfeatureNumberCode(int feature_number) ------------------------------------------------------*/ int MRICfeatureCode(MRIC *mric, int round, int feature_number) { - int f, fno; + unsigned f; + int fno; /* first ninputs-1 correspond to inputs #s, rest to frames in priors */ @@ -1304,7 +1306,8 @@ int MRICfeatureCode(MRIC *mric, int round, int feature_number) ------------------------------------------------------*/ int MRICfeatureNumber(MRIC *mric, int round, int feature_code) { - int f, fno; + unsigned f; + int fno; /* first ninputs-1 correspond to inputs #s, rest to frames in priors */ @@ -1607,7 +1610,7 @@ int MRICexamineTrainingSet(MRIC *mric, char *file_name, int round) ------------------------------------------------------*/ #define SCATTER_ROUND 0 -int MRICbuildScatterPlot(MRIC *mric, int class, MATRIX *m_scatter, char *training_file_name) +int MRICbuildScatterPlot(MRIC *mric, int classnum, MATRIX *m_scatter, char *training_file_name) { int obs_no = 0, i, x, y, nbins; // int half_bins, bin_offset; @@ -1654,7 +1657,7 @@ int MRICbuildScatterPlot(MRIC *mric, int class, MATRIX *m_scatter, char *trainin /* now fill in scatter plot */ mins = rbf->min_inputs; maxs = rbf->max_inputs; - while (mricGetClassObservation(&parms, v_obs, obs_no++, class) == NO_ERROR) { + while (mricGetClassObservation(&parms, v_obs, obs_no++, classnum) == NO_ERROR) { for (i = 0; i < rbf->ninputs; i++) { mn = mins[i]; mx = maxs[i]; @@ -1680,7 +1683,7 @@ int MRICbuildScatterPlot(MRIC *mric, int class, MATRIX *m_scatter, char *trainin Find the next observation for a given class. Stolen from rbf.c, but both really need it so.... ------------------------------------------------------*/ -static int mricGetClassObservation(GET_INPUT_PARMS *parms, VECTOR *v_obs, int desired_class_obs_no, int class) +static int mricGetClassObservation(GET_INPUT_PARMS *parms, VECTOR *v_obs, int desired_class_obs_no, int classnum) { int ret, classno, obs_no, class_obs_no; static int last_class = -1; @@ -1688,7 +1691,7 @@ static int mricGetClassObservation(GET_INPUT_PARMS *parms, VECTOR *v_obs, int de static int last_obs = -1; desired_class_obs_no++; /* it is a count - not an index */ - classno = class; + classno = classnum; if (classno == last_class && desired_class_obs_no > last_class_obs) { /* start at one past previous observation, not at start */ class_obs_no = last_class_obs; @@ -1699,7 +1702,7 @@ static int mricGetClassObservation(GET_INPUT_PARMS *parms, VECTOR *v_obs, int de do { ret = mricGetClassifierInput(v_obs, obs_no++, parms, 1, &classno); - if ((ret == NO_ERROR) && (classno == class)) class_obs_no++; + if ((ret == NO_ERROR) && (classno == classnum)) class_obs_no++; } while ((ret == NO_ERROR) && (class_obs_no < desired_class_obs_no)); if (ret == NO_ERROR) { diff --git a/utils/mricurv.c b/utils/mricurv.cpp similarity index 100% rename from utils/mricurv.c rename to utils/mricurv.cpp diff --git a/utils/mrifilter.c b/utils/mrifilter.cpp similarity index 99% rename from utils/mrifilter.c rename to utils/mrifilter.cpp index b9d68d9851c..c2d3e89886c 100644 --- a/utils/mrifilter.c +++ b/utils/mrifilter.cpp @@ -37,13 +37,12 @@ #include "fftutils.h" #include "filter.h" #include "macros.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mri.h" #include "mrinorm.h" #include "proto.h" #include "region.h" #include "talairachex.h" -#include "timer.h" #include "cma.h" #include "romp_support.h" @@ -6043,7 +6042,7 @@ MRI *MRI_Gaussian(int len, float std, int norm, int xsize, int ysize, int zsize) for (y = 0; y < len; y++) for (x = 0; x < len; x++) for (z = 0; z < len; z++) { - val = exp((2 - FFTdist(x, y, z, xsize, ysize, zsize, len)) / (2 * var)) / f; + val = exp((2 - FFTdist(x, y, z, len)) / (2 * var)) / f; MRIsetVoxVal(g, x, y, z, 0, val); } return (g); @@ -6442,8 +6441,7 @@ MRI *MRI_fft_lowpass(MRI *src, MRI *dst, int percent) for (z = 0; z < src_fft->depth; z++) for (y = 0; y < src_fft->height; y++) for (x = 0; x < src_fft->width; x++) { - if (FFTdist(x, y, z, src_fft->xsize, src_fft->ysize, src_fft->zsize, src_fft->depth) > - threshold * threshold) { + if (FFTdist(x, y, z, src_fft->depth) > threshold * threshold) { MRIsetVoxVal(src_fft, x, y, z, 2 * f, 0); } } @@ -6505,8 +6503,7 @@ MRI *MRI_fft_highpass(MRI *src, MRI *dst, int percent) for (z = 0; z < src_fft->depth; z++) for (y = 0; y < src_fft->height; y++) for (x = 0; x < src_fft->width; x++) { - if (FFTdist(x, y, z, src_fft->xsize, src_fft->ysize, src_fft->zsize, src_fft->depth) < - threshold * threshold) { + if (FFTdist(x, y, z, src_fft->depth) < threshold * threshold) { MRIsetVoxVal(src_fft, x, y, z, 2 * f, 0); } } @@ -6971,7 +6968,6 @@ MRI *MRInbrThresholdLabel(MRI *mri_src, MRI *mri_dst, int label, int out_label, MRI *MRImotionBlur2D(MRI *src, MB2D *mb, MRI *out) { int c; - struct timeb timer; if (src == out) { printf("ERROR: MRImotionBlur2D(): cannot be done in-place\n"); @@ -7020,8 +7016,6 @@ MRI *MRImotionBlur2D(MRI *src, MB2D *mb, MRI *out) MRIcopyHeader(src, mb->nd); MRIcopyHeader(src, mb->d0); - TimerStart(&timer); - // Fill the slice-based parameters ROMP_PF_begin #ifdef HAVE_OPENMP @@ -7172,8 +7166,6 @@ MRI *MRImotionBlur2D(MRI *src, MB2D *mb, MRI *out) ROMP_PFLB_end } // col ROMP_PF_end - - // printf(" motion blur took %6.4f sec\n",TimerStop(&timer)/1000.0);fflush(stdout); return (out); } @@ -7222,32 +7214,32 @@ MB2D *MB2Dcopy(MB2D *src, int CopyMRI, MB2D *copy) } /* - \fn MRI *MB2Dgrid(MRI *template, int skip, MRI *outvol) + \fn MRI *MB2Dgrid(MRI *mri_template, int skip, MRI *outvol) \brief Creates a grid of ones separated by skip. All the slices are the same. Good for testing MRImotionBlur2D(). */ -MRI *MB2Dgrid(MRI *template, int skip, MRI *outvol) +MRI *MB2Dgrid(MRI *mri_template, int skip, MRI *outvol) { int c, r, s, c0, r0, dc, dr, f; double radmax; if (outvol == NULL) { - outvol = MRIcloneBySpace(template, MRI_FLOAT, 1); + outvol = MRIcloneBySpace(mri_template, MRI_FLOAT, 1); if (outvol == NULL) return (NULL); } // Make sure it is 0 MRIconst(outvol->width, outvol->height, outvol->depth, 1, 0, outvol); - c0 = nint(template->width / 2.0); - r0 = nint(template->height / 2.0); - radmax = sqrt(2) * template->width / 2; + c0 = nint(mri_template->width / 2.0); + r0 = nint(mri_template->height / 2.0); + radmax = sqrt(2) * mri_template->width / 2; for (dc = -radmax; dc < radmax; dc += skip) { c = nint(c0 + dc); if (c < 0) continue; - if (c >= template->width) continue; + if (c >= mri_template->width) continue; for (dr = -radmax; dr < radmax; dr += skip) { r = r0 + dr; if (r < 0) continue; - if (r >= template->width) continue; + if (r >= mri_template->width) continue; for (s = 0; s < outvol->depth; s++) for (f = 0; f < outvol->nframes; f++) MRIsetVoxVal(outvol, c, r, s, f, 1); } // r diff --git a/utils/mriflood.c b/utils/mriflood.cpp similarity index 99% rename from utils/mriflood.c rename to utils/mriflood.cpp index 6e612cb3920..dcd6ff3e636 100644 --- a/utils/mriflood.c +++ b/utils/mriflood.cpp @@ -22,8 +22,6 @@ * */ -char *MRIFLOOD_VERSION = "$Revision: 1.41 $"; - #include #include #include @@ -75,7 +73,7 @@ static int likely(MRI *mri, int i, int j, int k) return 0; } -static void likelinessHistogram(MRI *mri, char *msg) +static void likelinessHistogram(MRI *mri, const char *msg) { int i, j, k; long Hist[] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; @@ -1439,11 +1437,7 @@ MRI *MRISfillInterior(MRI_SURFACE *mris, double resolution, MRI *mri_dst) MATRIX *crs, *xyz = NULL, *vox2sras = NULL, *m_vox2ras; MRI *mri_cosa, *mri_vlen, *mri_shell, *shellbb, *outsidebb; MRI_REGION *region; - struct timeb start; - - // printf("Using New MRISfillInterior()\n");fflush(stdout); - - TimerStart(&start); + Timer start; MRIScomputeMetricProperties(mris); @@ -1578,7 +1572,6 @@ MRI *MRISfillInterior(MRI_SURFACE *mris, double resolution, MRI *mri_dst) } } } - // printf(" shell done t = %g\n",TimerStop(&start)/1000.0) ; MRIS_freeRAS2VoxelMap(&map); MatrixFree(&crs); MatrixFree(&xyz); @@ -1608,10 +1601,8 @@ MRI *MRISfillInterior(MRI_SURFACE *mris, double resolution, MRI *mri_dst) MRIfree(&mri_shell); // Flood the outside (outside includes shell). This is the part that takes the longest. - // printf(" t = %g\n",TimerStop(&start)/1000.0) ; // printf(" flooding outside ");fflush(stdout); outsidebb = MRISfloodoutside(shellbb, NULL); - // printf(" t = %g\n",TimerStop(&start)/1000.0) ; fflush(stdout); /* Note: it is possible that there are voxels outside of the shell that do not get flooded because they form a hole and the flood @@ -1650,7 +1641,7 @@ MRI *MRISfillInterior(MRI_SURFACE *mris, double resolution, MRI *mri_dst) MRIfree(&outsidebb); // printf(" Found %d voxels in interior, volume = %g\n",nhits, // nhits*mri_dst->xsize*mri_dst->ysize*mri_dst->zsize); - if (Gdiag_no > 0) printf(" MRISfillInterior t = %g\n", TimerStop(&start) / 1000.0); + if (Gdiag_no > 0) printf(" MRISfillInterior t = %g\n", start.seconds()); return (mri_dst); } @@ -1666,7 +1657,8 @@ but is on the order of 20 times faster. int MRISfillInteriorRibbonTest(char *subject, int UseNew, FILE *fp) { FSENV *fsenv; - char tmpstr[4000], *hemistr = NULL, *surfname = NULL; + char tmpstr[4000]; + const char *hemistr = NULL, *surfname = NULL; MRI *ribbon; int hemi, surftype, c, r, s, nfp, nfn, ntp, v, vrib, wmval = 0, ctxval = 0; MRIS *surf; diff --git a/utils/mrihisto.c b/utils/mrihisto.cpp similarity index 99% rename from utils/mrihisto.c rename to utils/mrihisto.cpp index bd7ee43a03b..5ff45f2bad3 100644 --- a/utils/mrihisto.c +++ b/utils/mrihisto.cpp @@ -39,7 +39,7 @@ #include "filter.h" #include "label.h" #include "macros.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mri.h" #include "mrinorm.h" #include "proto.h" diff --git a/utils/mriio.c b/utils/mriio.cpp similarity index 98% rename from utils/mriio.c rename to utils/mriio.cpp index a78dab0707e..39757a9204e 100644 --- a/utils/mriio.c +++ b/utils/mriio.cpp @@ -44,8 +44,8 @@ #include #include +#include "machine.h" #include "mri.h" - #include "AFNI.h" #include "Bruker.h" #include "DICOMRead.h" @@ -59,9 +59,8 @@ #include "error.h" #include "fio.h" #include "gcamorph.h" -#include "gifti_local.h" +#include "gifti.h" #include "imautils.h" -#include "machine.h" #include "macros.h" #include "matfile.h" #include "math.h" @@ -78,8 +77,9 @@ #include "tags.h" #include "utils.h" #include "znzlib.h" - #include "romp_support.h" +#include "NrrdIO.h" + static int niiPrintHdr(FILE *fp, struct nifti_1_header *hdr); @@ -90,10 +90,6 @@ static int niiPrintHdr(FILE *fp, struct nifti_1_header *hdr); #define MM_PER_METER 1000.0f #define INFO_FNAME "COR-.info" -#ifdef Linux -extern void swab(const void *from, void *to, size_t n); -#endif - #if 0 static int NormalizeVector(float *v, int n); static MRI *mincRead2(const char *fname, int read_volume); @@ -164,8 +160,8 @@ static int niftiSformToMri(MRI *mri, struct nifti_1_header *hdr); static void swap_nifti_1_header(struct nifti_1_header *hdr); static MRI *MRISreadCurvAsMRI(const char *curvfile, int read_volume); -extern MRI *mriNrrdRead(const char *fname, int read_volume); -extern int mriNrrdWrite(MRI *mri, const char *fname); +static MRI *mriNrrdRead(const char *fname, int read_volume); +static int mriNrrdWrite(MRI *mri, const char *fname); /********************************************/ @@ -2247,7 +2243,7 @@ static MRI *siemensRead(const char *fname, int read_volume_flag) fseek(fp, 6144, SEEK_SET); for (i = 0; i < rows; i++) { - if (fread(&MRISvox(mri_raw, 0, i, file_n - n_low), sizeof(short), cols, fp) != cols){ + if (fread(&MRISvox(mri_raw, 0, i, file_n - n_low), sizeof(short), cols, fp) != (unsigned)cols){ ErrorPrintf(ERROR_BADFILE, "siemensRead(): could not read file"); } #if (BYTE_ORDER == LITTLE_ENDIAN) @@ -2298,7 +2294,7 @@ static MRI *mincRead(const char *fname, int read_volume) MRI *mri; Volume vol; VIO_Status status; - char *dim_names[4]; + const char *dim_names[4]; int dim_sizes[4]; int ndims; int dtype; @@ -2329,7 +2325,7 @@ static MRI *mincRead(const char *fname, int read_volume) } char *tmp = strcpyalloc(fname); - status = start_volume_input(tmp, 0, dim_names, NC_UNSPECIFIED, 0, 0, 0, TRUE, &vol, NULL, &input_info); + status = start_volume_input(tmp, 0, const_cast(dim_names), NC_UNSPECIFIED, 0, 0, 0, TRUE, &vol, NULL, &input_info); free(tmp); if (Gdiag & DIAG_VERBOSE_ON && DIAG_SHOW) { @@ -3099,7 +3095,7 @@ static int NormalizeVector(float *v, int n) static int mincWrite(MRI *mri, const char *fname) { Volume minc_volume; - char* dimension_names[4] = {"xspace", "yspace", "zspace", "time"}; + const char* dimension_names[4] = {"xspace", "yspace", "zspace", "time"}; nc_type nc_data_type; double min, max; float fmin, fmax; @@ -3260,9 +3256,9 @@ static int mincWrite(MRI *mri, const char *fname) max = (double)fmax; if (mri->nframes == 1) - minc_volume = create_volume(3, dimension_names, nc_data_type, signed_flag, min, max); + minc_volume = create_volume(3, const_cast(dimension_names), nc_data_type, signed_flag, min, max); else - minc_volume = create_volume(4, dimension_names, nc_data_type, signed_flag, min, max); + minc_volume = create_volume(4, const_cast(dimension_names), nc_data_type, signed_flag, min, max); /* di_(x,y,z) is the map from minc to orig */ /* minc dimension size is that of di_x, etc. */ @@ -3414,7 +3410,7 @@ static int bvolumeWrite(MRI *vol, const char *fname_passed, int type) MRI *mri; float min, max; int swap_bytes_flag, size, bufsize, endian = 0; - char *ext; + const char *ext; void *buf; /* check the type and set the extension and size*/ @@ -4251,7 +4247,7 @@ static MRI *bvolumeRead(const char *fname_passed, int read_volume, int type) int swap_bytes_flag; int slice, frame, row, k; int nread; - char *ext; + const char *ext; int size; float min, max; @@ -4327,7 +4323,7 @@ static MRI *bvolumeRead(const char *fname_passed, int read_volume, int type) if (swap_bytes_flag) { if (type == MRI_SHORT) - swab(mri->slices[k][row], mri->slices[k][row], mri->width * size); + swab(mri->slices[k][row], mri->slices[k][row], (size_t)(mri->width * size)); else byteswapbuffloat((void *)mri->slices[k][row], size * mri->width); } @@ -4908,7 +4904,6 @@ static MRI *genesisRead(const char *fname, int read_volume) char fname_format2[STRLEN]; char fname_dir[STRLEN]; char fname_base[STRLEN]; - char *c; MRI *mri = NULL; int im_init; int im_low, im_high; @@ -4948,15 +4943,15 @@ static MRI *genesisRead(const char *fname, int read_volume) } /* ----- split the file name into name and directory ----- */ - c = strrchr(fname, '/'); - if (c == NULL) { + const char *cc = strrchr(fname, '/'); + if (cc == NULL) { fname_dir[0] = '\0'; strcpy(fname_base, fname); } else { - strncpy(fname_dir, fname, (c - fname + 1)); - fname_dir[c - fname + 1] = '\0'; - strcpy(fname_base, c + 1); + strncpy(fname_dir, fname, (cc - fname + 1)); + fname_dir[cc - fname + 1] = '\0'; + strcpy(fname_base, cc + 1); } /* ----- derive the file name format (for sprintf) ----- */ @@ -4970,7 +4965,7 @@ static MRI *genesisRead(const char *fname, int read_volume) else if (strlen(fname_base) >= 3) /* avoid core dumps below... */ { twoformats = 1; - c = &fname_base[strlen(fname_base) - 3]; + char *c = &fname_base[strlen(fname_base) - 3]; if (strcmp(c, ".MR") == 0) { *c = '\0'; for (c--; isdigit(*c) && c >= fname_base; c--) @@ -5347,15 +5342,15 @@ static MRI *gelxRead(const char *fname, int read_volume) } /* ----- split the file name into name and directory ----- */ - c = strrchr(fname, '/'); - if (c == NULL) { + const char *cc = strrchr(fname, '/'); + if (cc == NULL) { fname_dir[0] = '\0'; strcpy(fname_base, fname); } else { - strncpy(fname_dir, fname, (c - fname + 1)); - fname_dir[c - fname + 1] = '\0'; - strcpy(fname_base, c + 1); + strncpy(fname_dir, fname, (cc - fname + 1)); + fname_dir[cc - fname + 1] = '\0'; + strcpy(fname_base, cc + 1); } ecount = scount = icount = 0; @@ -5579,7 +5574,7 @@ static MRI *gelxRead(const char *fname, int read_volume) ErrorReturn(NULL, (ERROR_BADFILE, "genesisRead(): error reading from file file %s", fname_use)); } #if (BYTE_ORDER == LITTLE_ENDIAN) - swab(mri->slices[i - im_low][y], mri->slices[i - im_low][y], 2 * mri->width); + swab(mri->slices[i - im_low][y], mri->slices[i - im_low][y], (size_t)(2 * mri->width)); #endif } @@ -6275,14 +6270,14 @@ static int analyzeWriteFrame(MRI *mri, const char *fname, int frame) MATRIX *T, *invT; char hdr_fname[STRLEN]; char mat_fname[STRLEN]; - char *c; + const char *c; FILE *fp; int error_value; int i, j, k; int bytes_per_voxel; short i1, i2, i3; int shortmax; - char *orientname[7] = {"transverse unflipped", + const char *orientname[7] = {"transverse unflipped", "coronal unflipped", "sagittal unflipped", "transverse flipped", @@ -6562,7 +6557,7 @@ static int analyzeWrite4D(MRI *mri, const char *fname) MATRIX *T, *invT; char hdr_fname[STRLEN]; char mat_fname[STRLEN]; - char *c; + const char *c; FILE *fp; int error_value; int i, j, k, frame; @@ -8339,15 +8334,15 @@ static MRI *ximgRead(const char *fname, int read_volume) } /* ----- split the file name into name and directory ----- */ - c = strrchr(fname, '/'); - if (c == NULL) { + const char *cc = strrchr(fname, '/'); + if (cc == NULL) { fname_dir[0] = '\0'; strcpy(fname_base, fname); } else { - strncpy(fname_dir, fname, (c - fname + 1)); - fname_dir[c - fname + 1] = '\0'; - strcpy(fname_base, c + 1); + strncpy(fname_dir, fname, (cc - fname + 1)); + fname_dir[cc - fname + 1] = '\0'; + strcpy(fname_base, cc + 1); } /* ----- derive the file name format (for sprintf) ----- */ @@ -8622,7 +8617,7 @@ static MRI *ximgRead(const char *fname, int read_volume) ErrorReturn(NULL, (ERROR_BADFILE, "genesisRead(): error reading from file file %s", fname_use)); } #if (BYTE_ORDER == LITTLE_ENDIAN) - swab(mri->slices[i - im_low][y], mri->slices[i - im_low][y], 2 * mri->width); + swab(mri->slices[i - im_low][y], mri->slices[i - im_low][y], (size_t)(2 * mri->width)); #endif } @@ -10063,6 +10058,198 @@ static int niiWrite(MRI *mri0, const char *fname) } /* end niiWrite() */ + +/*------------------------------------------------------------------ + mriNrrdRead + -----------------------------------------------------------------*/ +static MRI *mriNrrdRead(const char *fname, int read_volume) +{ + if (!nrrdSanity()) { + fprintf(stderr, "\n"); + fprintf(stderr, "!!! nrrd sanity check FAILED: fix and re-compile\n"); + char *err = biffGet(NRRD); + fprintf(stderr, "%s\n", err); + free(err); + return NULL; + } + + /* create a nrrd; at this point this is just an empty container */ + Nrrd *nin = nrrdNew(); + NrrdIoState *nio = nrrdIoStateNew(); + + /* read in the nrrd from file */ + if (nrrdLoad(nin, fname, nio)) { + char *err = biffGetDone(NRRD); + fprintf(stderr, "mriNrrdRead: trouble reading \"%s\":\n%s", fname, err); + free(err); + return NULL; + } + + // if it has more than 3 dimensions, then maybe its diffusion data + if (((nin->dim != 3) && (nin->dim != 4)) || (nin->spaceDim != 3)) { + /* say something about the array */ + printf("mriNrrdRead: \"%s\" is a %d-dimensional nrrd of type %d (%s)\n", + fname, + nin->dim, + nin->type, + airEnumStr(nrrdType, nin->type)); + printf("mriNrrdRead: the array contains %d elements, %d bytes in size\n", + (int)nrrdElementNumber(nin), + (int)nrrdElementSize(nin)); + if (nin->content) printf("mriNrrdRead: content: %s\n", nin->content); + + ErrorReturn(NULL, (ERROR_UNSUPPORTED, "Nrrd input of diffusion data not supported!")); + return NULL; + } + + /* print out the key/value pairs present */ + int kvn = nrrdKeyValueSize(nin); + if (kvn) { + int kvi; + for (kvi = 0; kvi < kvn; kvi++) { + char *val, *key; + nrrdKeyValueIndex(nin, &key, &val, kvi); + printf("mriNrrdRead: key:value %d = %s:%s\n", kvi, key, val); + free(key); + free(val); + key = val = NULL; + } + } + + // Get the component type. + int type = MRI_UCHAR; + switch (nin->type) { + case nrrdTypeChar: + case nrrdTypeUChar: + type = MRI_UCHAR; + break; + case nrrdTypeShort: + case nrrdTypeUShort: + type = MRI_SHORT; + break; + case nrrdTypeInt: + case nrrdTypeUInt: + type = MRI_INT; + break; + case nrrdTypeLLong: + case nrrdTypeULLong: + type = MRI_LONG; + break; + case nrrdTypeFloat: + type = MRI_FLOAT; + break; + default: + printf("mriNrrdRead: Unsupported type: %d (%s)\n", nin->type, airEnumStr(nrrdType, nin->type)); + return NULL; + } + + // alloc mri struct with the correct dimensions. + int width = nin->axis[0].size; + int height = nin->axis[1].size; + int depth = nin->axis[2].size; + int nframes = 1; // default nin->dim = 3 + if (nin->dim == 4) nframes = nin->axis[3].size; // multiple frames found + MRI *mri = MRIallocSequence(width, height, depth, type, nframes); + if (NULL == mri) { + printf("mriNrrdRead: Couldn't allocate MRI of size %d %d %d %d\n", width, height, depth, nframes); + return NULL; + } + + // Copy all the pixel data. + int x, y, z, f; + if (type == MRI_UCHAR) { + for (f = 0; f < nframes; f++) + for (z = 0; z < depth; z++) + for (y = 0; y < height; y++) + for (x = 0; x < width; x++) { + int index = x + (y * width) + (z * width * height) + (f * width * height * depth); + unsigned char *_uc = (unsigned char *)nin->data; + MRIseq_vox(mri, x, y, z, f) = (BUFTYPE)_uc[index]; + } + } + else if (type == MRI_SHORT) { + for (f = 0; f < nframes; f++) + for (z = 0; z < depth; z++) + for (y = 0; y < height; y++) + for (x = 0; x < width; x++) { + int index = x + (y * width) + (z * width * height) + (f * width * height * depth); + short *_s = (short *)nin->data; + MRISseq_vox(mri, x, y, z, f) = (short)_s[index]; + } + } + else if (type == MRI_INT) { + for (f = 0; f < nframes; f++) + for (z = 0; z < depth; z++) + for (y = 0; y < height; y++) + for (x = 0; x < width; x++) { + int index = x + (y * width) + (z * width * height) + (f * width * height * depth); + int *_i = (int *)nin->data; + MRIIseq_vox(mri, x, y, z, f) = (int)_i[index]; + } + } + else if (type == MRI_LONG) { + for (f = 0; f < nframes; f++) + for (z = 0; z < depth; z++) + for (y = 0; y < height; y++) + for (x = 0; x < width; x++) { + int index = x + (y * width) + (z * width * height) + (f * width * height * depth); + long *_l = (long *)nin->data; + MRILseq_vox(mri, x, y, z, f) = (long)_l[index]; + } + } + else if (type == MRI_FLOAT) { + for (f = 0; f < nframes; f++) + for (z = 0; z < depth; z++) + for (y = 0; y < height; y++) + for (x = 0; x < width; x++) { + int index = x + (y * width) + (z * width * height) + (f * width * height * depth); + float *_f = (float *)nin->data; + MRIFseq_vox(mri, x, y, z, f) = (float)_f[index]; + } + } + else { + printf("mriNrrdRead: Unsupported type=%d\n", type); + return NULL; + } + + // get and set the origin + mri->c_r = (float)nin->spaceOrigin[0]; + mri->c_a = (float)nin->spaceOrigin[1]; + mri->c_s = (float)nin->spaceOrigin[2]; + mri->ras_good_flag = 1; + + // get and set the spacing + mri->xsize = (float)nin->axis[0].spaceDirection[0]; + mri->ysize = (float)nin->axis[1].spaceDirection[1]; + mri->zsize = (float)nin->axis[2].spaceDirection[2]; + + // set orientation string + switch (nin->space) { + case nrrdSpaceRightAnteriorSuperior: { + MRIorientationStringToDircos(mri, "RAS"); + break; + } + case nrrdSpaceLeftAnteriorSuperior: { + MRIorientationStringToDircos(mri, "LAS"); + break; + } + case nrrdSpaceLeftPosteriorSuperior: { + MRIorientationStringToDircos(mri, "LPS"); + break; + } + } + + return mri; +} + +/*------------------------------------------------------------------ + mriNrrdWrite + -----------------------------------------------------------------*/ +static int mriNrrdWrite(MRI *mri, const char *fname) +{ + ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "mriNrrdWrite(): Nrrd output not supported!")); +} + /*------------------------------------------------------------------ itkMorphWrite() -----------------------------------------------------------------*/ @@ -10605,7 +10792,7 @@ MRI *MRIreadGeRoi(const char *fname, int n_slices) ErrorReturn(NULL, (ERROR_BADFILE, "MRIreadGeRoi(): error reading from file file %s", fname_use)); } #if (BYTE_ORDER == LITTLE_ENDIAN) - swab(mri->slices[i][y], mri->slices[i][y], 2 * mri->width); + swab(mri->slices[i][y], mri->slices[i][y], (size_t)(2 * mri->width)); #endif } @@ -11214,7 +11401,7 @@ static MRI *mghRead(const char *fname, int read_volume, int frame) float fval, xsize, ysize, zsize, x_r, x_a, x_s, y_r, y_a, y_s, z_r, z_a, z_s, c_r, c_a, c_s, xfov, yfov, zfov; short sval; // int tag_data_size; - char *ext; + const char *ext; int gzipped = 0; int nread; int tag; @@ -11559,7 +11746,7 @@ static int mghWrite(MRI *mri, const char *fname, int frame) float fval; short sval; int gzipped = 0; - char *ext; + const char *ext; if (frame >= 0) start_frame = end_frame = frame; @@ -11713,7 +11900,7 @@ static int mghWrite(MRI *mri, const char *fname, int frame) if (mri->pedir) znzTAGwrite(fp, TAG_PEDIR, mri->pedir, strlen(mri->pedir) + 1); else - znzTAGwrite(fp, TAG_PEDIR, "UNKNOWN", strlen("UNKNOWN")); + znzTAGwrite(fp, TAG_PEDIR, (void *)"UNKNOWN", strlen("UNKNOWN")); znzTAGwrite(fp, TAG_FIELDSTRENGTH, (void *)(&mri->FieldStrength), sizeof(mri->FieldStrength)); znzTAGwriteMRIframes(fp, mri); @@ -11745,7 +11932,7 @@ static int mghWrite(MRI *mri, const char *fname, int frame) */ MRI *MRIreorder4(MRI *mri, int order[4]) { - MRI *new; + MRI *result; int n, olddims[4], newdims[4]; int dold[4], dnew[4]; int c0, r0, s0, f0; @@ -11760,9 +11947,9 @@ MRI *MRIreorder4(MRI *mri, int order[4]) for (n = 0; n < 4; n++) newdims[n] = olddims[order[n] - 1]; // for(n=0; n<4; n++) // printf("%d %d %d %d\n",n,order[n],olddims[n],newdims[n]); - new = MRIallocSequence(newdims[0], newdims[1], newdims[2], mri->type, newdims[3]); - if (new == NULL) return (NULL); - MRIcopyHeader(mri, new); + result = MRIallocSequence(newdims[0], newdims[1], newdims[2], mri->type, newdims[3]); + if (result == NULL) return (NULL); + MRIcopyHeader(mri, result); for (c0 = 0; c0 < mri->width; c0++) { for (r0 = 0; r0 < mri->height; r0++) { @@ -11778,14 +11965,14 @@ MRI *MRIreorder4(MRI *mri, int order[4]) s1 = dnew[2]; f1 = dnew[3]; v = MRIgetVoxVal(mri, c0, r0, s0, f0); - MRIsetVoxVal(new, c1, r1, s1, f1, v); + MRIsetVoxVal(result, c1, r1, s1, f1, v); } } } exec_progress_callback(c0, mri->width, 0, 1); } - return (new); + return (result); } /*! diff --git a/utils/mriio_nrrd.c b/utils/mriio_nrrd.c deleted file mode 100644 index 451bc9c0799..00000000000 --- a/utils/mriio_nrrd.c +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @file mriio_nrrd.c - * @brief Provides Nrrd IO to Freesurfer - * - * Implements mriNrrdRead/Write using NrrdIO lib. - */ -/* - * Original Author: Nick Schmansky - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:46 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "NrrdIO/NrrdIO.h" -#include "error.h" -#include "mri.h" -#include "proto.h" -#include "utils.h" -extern MRI *mriNrrdReadDiffusion(char *fname, int read_volume); - -MRI *mriNrrdRead(char *fname, int read_volume) -{ - if (!nrrdSanity()) { - fprintf(stderr, "\n"); - fprintf(stderr, "!!! nrrd sanity check FAILED: fix and re-compile\n"); - char *err = biffGet(NRRD); - fprintf(stderr, "%s\n", err); - free(err); - return NULL; - } - - /* create a nrrd; at this point this is just an empty container */ - Nrrd *nin = nrrdNew(); - NrrdIoState *nio = nrrdIoStateNew(); - - /* read in the nrrd from file */ - if (nrrdLoad(nin, fname, nio)) { - char *err = biffGetDone(NRRD); - fprintf(stderr, "mriNrrdRead: trouble reading \"%s\":\n%s", fname, err); - free(err); - return NULL; - } - - /* if it has more than 3 dimensions, then maybe its diffusion data that - the ITK reader might understand (assuming we're building with ITK)*/ - if (((nin->dim != 3) && (nin->dim != 4)) || (nin->spaceDim != 3)) { - /* say something about the array */ - printf("mriNrrdRead: \"%s\" is a %d-dimensional nrrd of type %d (%s)\n", - fname, - nin->dim, - nin->type, - airEnumStr(nrrdType, nin->type)); - printf("mriNrrdRead: the array contains %d elements, %d bytes in size\n", - (int)nrrdElementNumber(nin), - (int)nrrdElementSize(nin)); - if (nin->content) printf("mriNrrdRead: content: %s\n", nin->content); - - return mriNrrdReadDiffusion(fname, read_volume); - } - - /* print out the key/value pairs present */ - int kvn = nrrdKeyValueSize(nin); - if (kvn) { - int kvi; - for (kvi = 0; kvi < kvn; kvi++) { - char *val, *key; - nrrdKeyValueIndex(nin, &key, &val, kvi); - printf("mriNrrdRead: key:value %d = %s:%s\n", kvi, key, val); - free(key); - free(val); - key = val = NULL; - } - } - - // Get the component type. - int type = MRI_UCHAR; - switch (nin->type) { - case nrrdTypeChar: - case nrrdTypeUChar: - type = MRI_UCHAR; - break; - case nrrdTypeShort: - case nrrdTypeUShort: - type = MRI_SHORT; - break; - case nrrdTypeInt: - case nrrdTypeUInt: - type = MRI_INT; - break; - case nrrdTypeLLong: - case nrrdTypeULLong: - type = MRI_LONG; - break; - case nrrdTypeFloat: - type = MRI_FLOAT; - break; - default: - printf("mriNrrdRead: Unsupported type: %d (%s)\n", nin->type, airEnumStr(nrrdType, nin->type)); - return NULL; - } - - // alloc mri struct with the correct dimensions. - int width = nin->axis[0].size; - int height = nin->axis[1].size; - int depth = nin->axis[2].size; - int nframes = 1; // default nin->dim = 3 - if (nin->dim == 4) nframes = nin->axis[3].size; // multiple frames found - MRI *mri = MRIallocSequence(width, height, depth, type, nframes); - if (NULL == mri) { - printf("mriNrrdRead: Couldn't allocate MRI of size %d %d %d %d\n", width, height, depth, nframes); - return NULL; - } - - // Copy all the pixel data. - int x, y, z, f; - if (type == MRI_UCHAR) { - for (f = 0; f < nframes; f++) - for (z = 0; z < depth; z++) - for (y = 0; y < height; y++) - for (x = 0; x < width; x++) { - int index = x + (y * width) + (z * width * height) + (f * width * height * depth); - unsigned char *_uc = (unsigned char *)nin->data; - MRIseq_vox(mri, x, y, z, f) = (BUFTYPE)_uc[index]; - } - } - else if (type == MRI_SHORT) { - for (f = 0; f < nframes; f++) - for (z = 0; z < depth; z++) - for (y = 0; y < height; y++) - for (x = 0; x < width; x++) { - int index = x + (y * width) + (z * width * height) + (f * width * height * depth); - short *_s = (short *)nin->data; - MRISseq_vox(mri, x, y, z, f) = (short)_s[index]; - } - } - else if (type == MRI_INT) { - for (f = 0; f < nframes; f++) - for (z = 0; z < depth; z++) - for (y = 0; y < height; y++) - for (x = 0; x < width; x++) { - int index = x + (y * width) + (z * width * height) + (f * width * height * depth); - int *_i = (int *)nin->data; - MRIIseq_vox(mri, x, y, z, f) = (int)_i[index]; - } - } - else if (type == MRI_LONG) { - for (f = 0; f < nframes; f++) - for (z = 0; z < depth; z++) - for (y = 0; y < height; y++) - for (x = 0; x < width; x++) { - int index = x + (y * width) + (z * width * height) + (f * width * height * depth); - long *_l = (long *)nin->data; - MRILseq_vox(mri, x, y, z, f) = (long)_l[index]; - } - } - else if (type == MRI_FLOAT) { - for (f = 0; f < nframes; f++) - for (z = 0; z < depth; z++) - for (y = 0; y < height; y++) - for (x = 0; x < width; x++) { - int index = x + (y * width) + (z * width * height) + (f * width * height * depth); - float *_f = (float *)nin->data; - MRIFseq_vox(mri, x, y, z, f) = (float)_f[index]; - } - } - else { - printf("mriNrrdRead: Unsupported type=%d\n", type); - return NULL; - } - - // get and set the origin - mri->c_r = (float)nin->spaceOrigin[0]; - mri->c_a = (float)nin->spaceOrigin[1]; - mri->c_s = (float)nin->spaceOrigin[2]; - mri->ras_good_flag = 1; - - // get and set the spacing - mri->xsize = (float)nin->axis[0].spaceDirection[0]; - mri->ysize = (float)nin->axis[1].spaceDirection[1]; - mri->zsize = (float)nin->axis[2].spaceDirection[2]; - - // set orientation string - switch (nin->space) { - case nrrdSpaceRightAnteriorSuperior: { - MRIorientationStringToDircos(mri, "RAS"); - break; - } - case nrrdSpaceLeftAnteriorSuperior: { - MRIorientationStringToDircos(mri, "LAS"); - break; - } - case nrrdSpaceLeftPosteriorSuperior: { - MRIorientationStringToDircos(mri, "LPS"); - break; - } - } - - return mri; -} - -int mriNrrdWrite(MRI *mri, char *fname) -{ - ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "mriNrrdWrite(): Nrrd output not supported!")); -} diff --git a/utils/mriio_nrrd_itk.cpp b/utils/mriio_nrrd_itk.cpp deleted file mode 100644 index 2a1fe7ec1af..00000000000 --- a/utils/mriio_nrrd_itk.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/** - * @file mriio_nrrd_itk.cpp - * @brief Provides Nrrd read support of diffusion data to Freesurfer - * - * Implements mriNrrdRead and mriNrrdWrite using ITK library. - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:46 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#ifndef HAVE_ITK_LIBS -// if Freesurfer is configured *without* ITK libs (that is, if --with-itk-dir -// wss not specified on the configure line), then include these stubs: -extern "C" { -#include "error.h" -#include "mri.h" -MRI *mriNrrdReadDiffusion(char *fname, int read_volume) -{ - ErrorReturn(NULL, (ERROR_UNSUPPORTED, "mriNrrdReadDiffusion(): Nrrd input of diffusion data not supported!")); - return NULL; -} -int mriNrrdWriteDiffusion(MRI *mri, char *fname) -{ - ErrorReturn(ERROR_UNSUPPORTED, - (ERROR_UNSUPPORTED, "mriNrrdWriteDiffusion(): Nrrd diffusion data output not supported!")); -} -} -#else // ITK libs available, so implement IO... - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -extern "C" { -#include "minc_volume_io.h" - -#include "analyze.h" -#include "chklc.h" -#include "diag.h" -#include "error.h" -#include "fio.h" -#include "machine.h" -#include "macros.h" -#include "matfile.h" -#include "math.h" -#include "matrix.h" -#include "mri.h" -#include "mri_identify.h" -#include "proto.h" -#include "region.h" -#include "signa.h" -#include "utils.h" -} - -#ifdef UCHAR -#undef UCHAR -#endif -#ifdef USHORT -#undef USHORT -#endif -#ifdef UINT -#undef UINT -#endif -#ifdef ULONG -#undef ULONG -#endif - -#if GCC_VERSION > 40408 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-local-typedefs" -#endif - -#define export // obsolete feature 'export template' used in these headers -#include "itkImage.h" -//#include "itkExceptionObject.h" -#include "itkDiffusionTensor3D.h" -#include "itkImageFileReader.h" -#include "itkImageFileWriter.h" -#include "itkMetaDataObject.h" -#include "itkNrrdImageIO.h" -#undef export - -using namespace std; - -extern "C" { -MRI *mriNrrdReadDiffusion(char *fname, int read_volume); -int mriNrrdWriteDiffusion(MRI *mri, char *fname); -} - -MRI *mriNrrdReadDiffusion(char *fname, int read_volume) -{ - typedef itk::DiffusionTensor3D< float > PixelType; - typedef itk::Image< PixelType, 3 > DiffusionImageType; - typedef itk::ImageFileReader< DiffusionImageType > ReaderType; - - MRI *mri = NULL; - int type = MRI_UCHAR; - - // Read the file. - ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(fname); - - itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New(); - // io->SetNrrdVectorType (nrrdKindList); - io->SetFileType(itk::ImageIOBase::ASCII); - - reader->SetImageIO(io); - reader->Update(); - - // Get the component type. - switch (io->GetComponentType()) { - case itk::ImageIOBase::UCHAR: - type = MRI_UCHAR; - break; - case itk::ImageIOBase::USHORT: - case itk::ImageIOBase::SHORT: - type = MRI_SHORT; - break; - case itk::ImageIOBase::ULONG: - case itk::ImageIOBase::LONG: - type = MRI_LONG; - break; - case itk::ImageIOBase::DOUBLE: - case itk::ImageIOBase::FLOAT: - type = MRI_FLOAT; - break; - default: - cerr << "Unsupported type: " << io->GetComponentTypeAsString(io->GetComponentType()) << endl; - return NULL; - } - - // Get a pointer to the image. - DiffusionImageType::Pointer image = reader->GetOutput(); - - // Get the bounds (the size of the largest possible region). - const DiffusionImageType::RegionType ®ion = image->GetLargestPossibleRegion(); - const DiffusionImageType::SizeType size = region.GetSize(); - cerr << "Size " << size[0] << " " << size[1] << " " << size[2] << endl; - - // Get the pixel type and the number of frames. - DiffusionImageType::PixelType value; - cerr << "Size of value " << value.Size() << endl; - - // Make a mri with the correct number of frames. - mri = MRIallocSequence(size[0], size[1], size[2], type, value.Size()); - if (NULL == mri) { - cerr << "mriNrrdReadDiffusion(): Couldn't allocate MRI of size " << size[0] << " " << size[1] << " " << size[2] - << endl; - return NULL; - } - - // Copy all the pixel data. - DiffusionImageType::IndexType index; - for (unsigned int z = 0; z < size[2]; z++) { - index[2] = z; - for (unsigned int y = 0; y < size[1]; y++) { - index[1] = y; - for (unsigned int x = 0; x < size[0]; x++) { - index[0] = x; - value = image->GetPixel(index); - switch (type) { - case MRI_UCHAR: - MRIseq_vox(mri, x, y, z, 0) = (BUFTYPE)value[0]; - MRIseq_vox(mri, x, y, z, 1) = (BUFTYPE)value[1]; - MRIseq_vox(mri, x, y, z, 2) = (BUFTYPE)value[2]; - break; - case MRI_INT: - MRIIseq_vox(mri, x, y, z, 0) = (int)value[0]; - MRIIseq_vox(mri, x, y, z, 1) = (int)value[1]; - MRIIseq_vox(mri, x, y, z, 2) = (int)value[2]; - break; - case MRI_LONG: - MRILseq_vox(mri, x, y, z, 0) = (long)value[0]; - MRILseq_vox(mri, x, y, z, 1) = (long)value[1]; - MRILseq_vox(mri, x, y, z, 2) = (long)value[2]; - break; - case MRI_FLOAT: - MRIFseq_vox(mri, x, y, z, 0) = value[0]; - MRIFseq_vox(mri, x, y, z, 1) = value[1]; - MRIFseq_vox(mri, x, y, z, 2) = value[2]; - break; - case MRI_SHORT: - MRISseq_vox(mri, x, y, z, 0) = (short)value[0]; - MRISseq_vox(mri, x, y, z, 1) = (short)value[1]; - MRISseq_vox(mri, x, y, z, 2) = (short)value[2]; - break; - default: - break; - } - } - } - } - - // Get and set the center. - const DiffusionImageType::PointType origin = image->GetOrigin(); - cerr << "Origin " << origin[0] << " " << origin[1] << " " << origin[2] << endl; - mri->c_r = origin[0]; - mri->c_a = origin[1]; - mri->c_s = origin[2]; - - // Get and set the spacing. - const DiffusionImageType::SpacingType spacing = image->GetSpacing(); - cerr << "Spacing " << spacing[0] << " " << spacing[1] << " " << spacing[2] << endl; - mri->xsize = spacing[0]; - mri->ysize = spacing[1]; - mri->zsize = spacing[2]; - - typedef itk::MetaDataDictionary DictionaryType; - typedef itk::MetaDataObject< string > DictionaryStringType; - - DictionaryType &headers = io->GetMetaDataDictionary(); - - DictionaryType::ConstIterator iHeader = headers.Begin(); - DictionaryType::ConstIterator end = headers.End(); - - while (iHeader != end) { - itk::MetaDataObjectBase::Pointer entry = iHeader->second; - - DictionaryStringType::Pointer value = dynamic_cast< DictionaryStringType * >(entry.GetPointer()); - - if (value) { - string sValue = value->GetMetaDataObjectValue(); - string sKey = iHeader->first; - cerr << "--- " << sKey << " = " << sValue << endl; - } - - ++iHeader; - } - - return mri; -} - -int mriNrrdWriteDiffusion(MRI *mri, char *fname) -{ - // just give an error until write function is complete and tested - ErrorReturn(ERROR_UNSUPPORTED, - (ERROR_UNSUPPORTED, - "mriNrrdWriteDiffusion(): " - "Nrrd diffusion data output not yet supported")); -} - -#endif // #ifndef HAVE_ITK_LIBS diff --git a/utils/mrimorph.c b/utils/mrimorph.cpp similarity index 99% rename from utils/mrimorph.c rename to utils/mrimorph.cpp index 5e205de6350..98d091b3663 100644 --- a/utils/mrimorph.c +++ b/utils/mrimorph.cpp @@ -101,7 +101,7 @@ static int m3dAlignPyramidLevel(MRI *mri_in, MRI *mri_ref, MRI *mri_ref_blur, MP static int mriOrthonormalizeTransform(MATRIX *m_L); static double mriIntensityRMS(MRI *mri_in, MRI *mri_ref, LTA *lta, double l_intensity, NECK_PARMS *np); static double mriIntensitySSE(MRI *mri_in, MRI *mri_ref, MATRIX *m_L); -static int mriWriteImageView(MRI *mri, char *base_name, int target_size, int view, int slice); +static int mriWriteImageView(MRI *mri, const char *base_name, int target_size, int view, int slice); static int writeSnapshot(MRI *mri, MORPH_PARMS *parms, int n); static int write3DSnapshot(MRI *mri_in, MRI *mri_ref, MORPH_PARMS *parms, MORPH_3D *m3d, int n); static double ltaGradientStep( @@ -4108,7 +4108,7 @@ static int write3DSnapshot(MRI *mri_in, MRI *mri_ref, MORPH_PARMS *parms, MORPH_ sprintf(fname, "in_%s", parms->base_name); MRIwriteImageViews(mri_in, fname, IMAGE_SIZE); #if 0 - sprintf(fname, "in_%s.mgh", parms->base_name) ; + sprintf(fname, "in_%s.mgh", parms->base_mriWriteImageViewname) ; fprintf(stdout, "writing volume to %s...\n", fname) ; MRIwrite(mri_in, fname) ; #endif @@ -4137,7 +4137,7 @@ static int write3DSnapshot(MRI *mri_in, MRI *mri_ref, MORPH_PARMS *parms, MORPH_ Description ------------------------------------------------------*/ -int MRIwriteImageViews(MRI *mri, char *base_name, int target_size) +int MRIwriteImageViews(MRI *mri, const char *base_name, int target_size) { int slice_direction = getSliceDirection(mri), x, y, z; @@ -4191,9 +4191,10 @@ int MRIwriteImageViews(MRI *mri, char *base_name, int target_size) Description ------------------------------------------------------*/ -static int mriWriteImageView(MRI *mri, char *base_name, int target_size, int view, int slice) +static int mriWriteImageView(MRI *mri, const char *base_name, int target_size, int view, int slice) { - char fname[STRLEN], *prefix; + char fname[STRLEN]; + const char *prefix; IMAGE *I; float scale; // int slice_direction ; @@ -4564,7 +4565,7 @@ MORPH_3D *MRI3DreadSmall(char *fname) if (!fp) ErrorReturn(NULL, (ERROR_NOFILE, "MRI3DreadSmall: could not open file %s", fname)); magic = freadInt(fp); - if (magic != M3D_MAGIC) { + if ((unsigned)magic != M3D_MAGIC) { fclose(fp); ErrorReturn(NULL, (ERROR_BADFILE, "file %s not an old 3d morph file.\nTry a new 3d morph read routine.\n", fname)); } @@ -6376,7 +6377,7 @@ static int m3dMorphSkull(MORPH_3D *m3d, MRI_SURFACE *mris_in_skull, MRI_SURFACE } } { - char *cp; + const char *cp; float sigma; cp = getenv("SIGMA"); if (!cp) cp = "1.0"; diff --git a/utils/mrinorm.c b/utils/mrinorm.cpp similarity index 96% rename from utils/mrinorm.c rename to utils/mrinorm.cpp index ad296416a7f..1241ba60980 100644 --- a/utils/mrinorm.c +++ b/utils/mrinorm.cpp @@ -40,7 +40,7 @@ #include "error.h" #include "filter.h" #include "macros.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mri.h" #include "mrinorm.h" #include "mrisegment.h" @@ -3416,7 +3416,7 @@ int MRI3dUseFileControlPoints(MRI *mri, const char *fname) } } if (ndel > 0 && cp != NULL) { - char *fname = "control.edited.dat"; + const char *fname = "control.edited.dat"; printf("FS_THRESH_CTRL detected in env - deleting %d control points\n", ndel); for (i = 0; i < count; i++) { if (deleted[i]) { diff --git a/utils/mripolv.c b/utils/mripolv.cpp similarity index 99% rename from utils/mripolv.c rename to utils/mripolv.cpp index 028ebf3e480..b8ac59cf4ab 100644 --- a/utils/mripolv.c +++ b/utils/mripolv.cpp @@ -37,7 +37,7 @@ #include "error.h" #include "filter.h" #include "macros.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mri.h" #include "mrimorph.h" #include "mrisegment.h" @@ -4158,7 +4158,7 @@ float MRIcpolvMedianAtVoxel(MRI *mri_src, int vertex, float x, float y, float z, } int MRIvertexToVector(int vertex, float *pdx, float *pdy, float *pdz) { - if ((vertex < 0) || (vertex >= sizeof(ic_x_vertices) / sizeof(ic_x_vertices[0]))) + if ((vertex < 0) || ((unsigned)vertex >= sizeof(ic_x_vertices) / sizeof(ic_x_vertices[0]))) ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "MRIvertexToVector(%d): index out of range", vertex)); *pdx = ic_x_vertices[vertex]; *pdy = ic_y_vertices[vertex]; diff --git a/utils/mriprob.c b/utils/mriprob.cpp similarity index 100% rename from utils/mriprob.c rename to utils/mriprob.cpp diff --git a/utils/mris_compVolFrac.c b/utils/mris_compVolFrac.cpp similarity index 100% rename from utils/mris_compVolFrac.c rename to utils/mris_compVolFrac.cpp diff --git a/utilscpp/mris_fastmarching.cpp b/utils/mris_fastmarching.cpp similarity index 71% rename from utilscpp/mris_fastmarching.cpp rename to utils/mris_fastmarching.cpp index 55d11d19dd5..dfc416d8949 100644 --- a/utilscpp/mris_fastmarching.cpp +++ b/utils/mris_fastmarching.cpp @@ -1,39 +1,3 @@ -/** - * @file mris_fastmarching.cpp - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -// -// mris_fastmarching.cpp -// -// original written by Florent Segonne (March, 2005) -// -// Warning: Do not edit the following four lines. CVS maintains them. -// Revision Author: $Author: nicks $ -// Revision Date : $Date: 2011/03/02 00:04:56 $ -// Revision : $Revision: 1.4 $ - #include "fastmarching.h" static MRI_REGION*mriFindLabel(MRI *mri,int label,int offset) { @@ -75,7 +39,7 @@ static MRI_REGION*mriFindLabel(MRI *mri,int label,int offset) { // the source mri mri_src is a float distance map with zero values inside. // the resolution is mri_src->xsize -extern "C" void MRISextractOutsideDistanceMap(MRIS *mris, MRI *mri_src, int label , int offset, float resolution, float max_distance) { +void MRISextractOutsideDistanceMap(MRIS *mris, MRI *mri_src, int label , int offset, float resolution, float max_distance) { MRI *mri_distance, *mri_fastmarching; /* resolution*/ diff --git a/utils/mrisbiorthogonalwavelets.c b/utils/mrisbiorthogonalwavelets.c deleted file mode 100644 index 992b2c4bb5d..00000000000 --- a/utils/mrisbiorthogonalwavelets.c +++ /dev/null @@ -1,659 +0,0 @@ -/** - * @file mrisbiorthogonalwavelets.c - * @brief Routines for biothogonal wavelets transformation. - * - * References: - * P. Schroder and W. Sweldens. Spherical wavelets: Texture processing. - * In Rendering Techniques '95. Springer Verlag, 1995. - * P. Schroder and W. Sweldens. Spherical wavelets: Efficiently representing - * functions on the sphere. Computer Graphics Proceedings (SIGGRAPH 95), - * pages 161-172, 1995. - */ -/* - * Original Author: Peng Yu - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:46 $ - * $Revision: 1.2 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include "cma.h" -#include "const.h" -#include "diag.h" -#include "error.h" -#include "icosahedron.h" -#include "macros.h" -#include "matrix.h" -#include "mri.h" -#include "mrinorm.h" -#include "mrisurf.h" -#include "proto.h" -#include "timer.h" -#include "version.h" - -MRI_SURFACE *wavelet_analysis_curv(MRI_SURFACE *mris_out, int order); -MRI_SURFACE *wavelet_analysis_vec(MRI_SURFACE *mris_out, int order); -MRI_SURFACE *wavelet_synthesis_curv(MRI_SURFACE *mris_out, int order); -MRI_SURFACE *wavelet_synthesis_vec(MRI_SURFACE *mris_out, int order); - -static void resetAllVertexNsize(MRIS* mris_high) { - int m; - for (m = 0; m < mris_high->nvertices; m++) { - cheapAssert(mris_high->vertices_topology[m].nsizeMax == 1); - cheapAssert(mris_high->vertices_topology[m].nsizeCur == 1); - } -} - -MRI_SURFACE *wavelet_analysis_curv(MRI_SURFACE *mris_out, int order) -{ - /* Initialize Ij,k*/ - int vno; - for (vno = 0; vno < mris_out->nvertices; vno++) { - VERTEX* vm_out = &mris_out->vertices[vno]; - vm_out->val = 1; - } - - /*Iteratively compute Ij,k*/ - int i; - for (i = order; i > 0; i--) { - MRIS* mris_high = ReadIcoByOrder(i, 100); // higher order surface - - int m; - resetAllVertexNsize(mris_high); - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - for (m = number; m < mris_high->nvertices; m++) { - - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.5 * vm_out->val; - } - int flag = 0, b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) - if (vmt_high->v[nnum] < number) // B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.125 * vm_out->val; - } - for (; nnum < vmt_high->v3num; nnum++) - if (vmt_high->v[nnum] < number) // C(j,m) - { - int k = vmt_high->v[nnum]; - int flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX* v = &mris_out->vertices[k]; - v->val -= 0.0625 * vm_out->val; - } - } - } - MRISfree(&mris_high); - } - - /*Analysis Stage I:*/ - for (i = order; i > 0; i--) { - MRIS* mris_high = ReadIcoByOrder(i, 100); // higher order surface - - int m; - resetAllVertexNsize(mris_high); - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - /* compute Yj,m for each m vertices */ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) // first order neighborhood - if (vmt_high->v[nnum] < number) // neighbor A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - vm_out->curv -= 0.5 * v->curv; - // if(m==67770) fprintf(stdout, "%f, %d, %f\n", v->curv, k, vm_out->curv); - } - int flag = 0, b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) // second order neighborhood - if (vmt_high->v[nnum] < number) // neighbor B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX* v = &mris_out->vertices[k]; - vm_out->curv -= 0.125 * v->curv; - // if(m==67770) fprintf(stdout, "%f, %d, %f\n", v->curv, k, vm_out->curv); - } - for (; nnum < vmt_high->v3num; nnum++) - if (vmt_high->v[nnum] < number) // neighbor C(j,m) - { - int k = vmt_high->v[nnum]; - int flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX* v = &mris_out->vertices[k]; - vm_out->curv += 0.0625 * v->curv; - // if(m==67770) fprintf(stdout, "%f, %d, %f\n", v->curv, k, vm_out->curv); - } - } - } - - /*Analysis Stage II: */ - /*Compute Lamda(j,k) using the Yita(j,m)*/ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - double s_jkm = vm_out->val / 2 / v->val; - // if(k==6642) fprintf(stdout, "%f, %f, %f, %f, %d\n", vm_out->val, v->val, s_jkm, vm_out->curv, m); - v->curv += s_jkm * vm_out->curv; - } - } - MRISfree(&mris_high); - } - return (mris_out); -} - -MRI_SURFACE *wavelet_analysis_vec(MRI_SURFACE *mris_out, int order) -{ - /* Initialize Ij,k*/ - int vno; - for (vno = 0; vno < mris_out->nvertices; vno++) { - VERTEX* vm_out = &mris_out->vertices[vno]; - vm_out->val = 1; - } - - /*Iteratively compute Ij,k*/ - int i; - for (i = order; i > 0; i--) { - MRIS* mris_high = ReadIcoByOrder(i, 100); // higher order surface - - int m; - for (m = 0; m < mris_high->nvertices; m++) cheapAssert(mris_high->vertices_topology[m].nsizeMax == 1); - - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.5 * vm_out->val; - } - - int flag = 0, b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) - if (vmt_high->v[nnum] < number) // B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.125 * vm_out->val; - } - - for (; nnum < vmt_high->v3num; nnum++) - if (vmt_high->v[nnum] < number) // C(j,m) - { - int k = vmt_high->v[nnum]; - int flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX* v = &mris_out->vertices[k]; - v->val -= 0.0625 * vm_out->val; - } - } - } - MRISfree(&mris_high); - } - - /*Analysis Stage I:*/ - for (i = order; i > 0; i--) { - MRIS* mris_high = ReadIcoByOrder(i, 100); // higher order surface - - int m; - resetAllVertexNsize(mris_high); - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - /* compute Yj,m for each m vertices */ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) // first order neighborhood - if (vmt_high->v[nnum] < number) // neighbor A(j,m) - { - int const k = vmt_high->v[nnum]; - VERTEX const * v = &mris_out->vertices[k]; - - MRISsetOriginalXYZ(mris_out, m, - vm_out->origx - 0.5 * v->origx, - vm_out->origy - 0.5 * v->origy, - vm_out->origz - 0.5 * v->origz); - } - - int flag = 0, b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) // second order neighborhood - if (vmt_high->v[nnum] < number) // neighbor B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX* v = &mris_out->vertices[k]; - MRISsetOriginalXYZ(mris_out, m, - vm_out->origx - 0.125 * v->origx, - vm_out->origy - 0.125 * v->origy, - vm_out->origz - 0.125 * v->origz); - } - - for (; nnum < vmt_high->v3num; nnum++) - if (vmt_high->v[nnum] < number) // neighbor C(j,m) - { - int k = vmt_high->v[nnum]; - int flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX* v = &mris_out->vertices[k]; - MRISsetOriginalXYZ(mris_out, m, - vm_out->origx + 0.0625 * v->origx, - vm_out->origy + 0.0625 * v->origy, - vm_out->origz + 0.0625 * v->origz); - } - } - } - - /*Analysis Stage II: */ - /*Compute Lamda(j,k) using the Yita(j,m)*/ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - double s_jkm = vm_out->val / 2 / v->val; - MRISsetOriginalXYZ(mris_out, k, - v->origx + s_jkm * vm_out->origx, - v->origy + s_jkm * vm_out->origy, - v->origz + s_jkm * vm_out->origz); - } - } - -#if 0 - - { //optional output - char fname[200]; - MRISfree(&mris_high); - mris_high = ReadIcoByOrder(i-1, 100); - for (m = 0; mnvertices; m++) - { - mris_high->vertices[m].x = mris_out->vertices[m].origx; - mris_high->vertices[m].y = mris_out->vertices[m].origy; - mris_high->vertices[m].z = mris_out->vertices[m].origz; - } - sprintf(fname,"/space/birn/42/users/pengyu/simulation/010223_61223/surf/lh.wavelet%d",i-1); - MRISwrite(mris_high, fname) ; - } -#endif - MRISfree(&mris_high); - } - return (mris_out); -} - -MRI_SURFACE *wavelet_synthesis_curv(MRI_SURFACE *mris_out, int order) -{ - - /*Initialize Ij,k*/ - int vno; - for (vno = 0; vno < mris_out->nvertices; vno++) { - VERTEX * vm_out = &mris_out->vertices[vno]; - vm_out->val = 1; - } - - /*Iteratively compute Ij,k*/ - int i; - for (i = order; i > 0; i--) { - MRIS * mris_high = ReadIcoByOrder(i, 100); // higher order surface - - int m; - resetAllVertexNsize(mris_high); - - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.5 * vm_out->val; - } - int flag = 0, b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) - if (vmt_high->v[nnum] < number) // B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.125 * vm_out->val; - } - for (; nnum < vmt_high->v3num; nnum++) - if (vmt_high->v[nnum] < number) // C(j,m) - { - int k = vmt_high->v[nnum]; - int flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX* v = &mris_out->vertices[k]; - v->val -= 0.0625 * vm_out->val; - } - } - } - MRISfree(&mris_high); - } - - for (i = 1; i <= order; i++) { - MRIS* mris_high = ReadIcoByOrder(i, 100); // higher order surface - int m; - resetAllVertexNsize(mris_high); - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - - /* Synthesis Stage I */ - /* Compute Lamda(j+1,k) using the Yita(j,m) */ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX* const vm_out = &mris_out ->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX * v = &mris_out->vertices[k]; - double s_jkm = vm_out->val / 2 / v->val; - v->curv -= s_jkm * vm_out->curv; - } - } - - /* compute Lamda(j+1,m) for each m vertices */ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX* const vm_out = &mris_out ->vertices [m]; - - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) // first order neighborhood - if (vmt_high->v[nnum] < number) // neighbor A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - vm_out->curv += 0.5 * v->curv; - } - - int flag = 0, b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) // second order neighborhood - if (vmt_high->v[nnum] < number) // neighbor B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX* v = &mris_out->vertices[k]; - vm_out->curv += 0.125 * v->curv; - } - - for (; nnum < vmt_high->v3num; nnum++) // third order neighborhood - if (vmt_high->v[nnum] < number) // neighbor C(j,m) - { - int k = vmt_high->v[nnum]; - flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX * v = &mris_out->vertices[k]; - vm_out->curv -= 0.0625 * v->curv; - } - } - } - MRISfree(&mris_high); - } - return (mris_out); -} - -MRI_SURFACE *wavelet_synthesis_vec(MRI_SURFACE *mris_out, int order) -{ - /*Initialize Ij,k*/ - int vno; - for (vno = 0; vno < mris_out->nvertices; vno++) { - VERTEX* vm_out = &mris_out->vertices[vno]; - vm_out->val = 1; - } - - /*Iteratively compute Ij,k*/ - int i; - for (i = order; i > 0; i--) { - MRIS * mris_high = ReadIcoByOrder(i, 100); // higher order surface - - int m; - resetAllVertexNsize(mris_high); - - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.5 * vm_out->val; - } - int flag = 0; - int b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) - if (vmt_high->v[nnum] < number) // B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX* v = &mris_out->vertices[k]; - v->val += 0.125 * vm_out->val; - } - for (; nnum < vmt_high->v3num; nnum++) - if (vmt_high->v[nnum] < number) // C(j,m) - { - int k = vmt_high->v[nnum]; - flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX* v = &mris_out->vertices[k]; - v->val -= 0.0625 * vm_out->val; - } - } - } - - MRISfree(&mris_high); - } - - for (i = 1; i <= order; i++) { - MRIS * mris_high = ReadIcoByOrder(i, 100); // higher order surface - - int m; - - resetAllVertexNsize(mris_high); - - MRISsetNeighborhoodSizeAndDist(mris_high, 3); - int const number = IcoNVtxsFromOrder(i - 1); // the start of m vertices - - /* Synthesis Stage I */ - /* Compute Lamda(j+1,k) using the Yita(j,m) */ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX const * const vm_out = &mris_out ->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) - if (vmt_high->v[nnum] < number) // A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX * const v = &mris_out->vertices[k]; - double s_jkm = vm_out->val / 2 / v->val; - MRISsetOriginalXYZ(mris_out, k, - v->origx - s_jkm * vm_out->origx, - v->origy - s_jkm * vm_out->origy, - v->origz - s_jkm * vm_out->origz); - } - } - - /* compute Lamda(j+1,m) for each m vertices */ - for (m = number; m < mris_high->nvertices; m++) { - VERTEX_TOPOLOGY const * const vmt_high = &mris_high->vertices_topology[m]; - VERTEX * const vm_out = &mris_out ->vertices [m]; - int nnum; - for (nnum = 0; nnum < vmt_high->vnum; nnum++) // first order neighborhood - if (vmt_high->v[nnum] < number) // neighbor A(j,m) - { - int k = vmt_high->v[nnum]; - VERTEX const * v = &mris_out->vertices[k]; - MRISsetOriginalXYZ(mris_out, m, - vm_out->origx + 0.5 * v->origx, - vm_out->origy + 0.5 * v->origy, - vm_out->origz + 0.5 * v->origz); - } - int flag = 0; - int b1 = 0, b2 = 0; - for (; nnum < vmt_high->v2num; nnum++) // second order neighborhood - if (vmt_high->v[nnum] < number) // neighbor B(j,m) - { - int k = vmt_high->v[nnum]; - if (flag == 0) - b1 = k; - else - b2 = k; - flag++; - VERTEX const * v = &mris_out->vertices[k]; - MRISsetOriginalXYZ(mris_out, m, - vm_out->origx + 0.125 * v->origx, - vm_out->origy + 0.125 * v->origy, - vm_out->origz + 0.125 * v->origz); - } - for (; nnum < vmt_high->v3num; nnum++) // third order neighborhood - if (vmt_high->v[nnum] < number) // neighbor C(j,m) - { - int k = vmt_high->v[nnum]; - flag = 0; // C has to be a second-order neighbor of B - int cno; - for (cno = mris_high->vertices_topology[b1].vnum; cno < mris_high->vertices_topology[b1].v2num; cno++) - if (mris_high->vertices_topology[b1].v[cno] == k) flag = 1; - for (cno = mris_high->vertices_topology[b2].vnum; cno < mris_high->vertices_topology[b2].v2num; cno++) - if (mris_high->vertices_topology[b2].v[cno] == k) flag = 1; - if (flag) { - VERTEX const * v = &mris_out->vertices[k]; - MRISsetOriginalXYZ(mris_out, m, - vm_out->origx - 0.0625 * v->origx, - vm_out->origy - 0.0625 * v->origy, - vm_out->origz - 0.0625 * v->origz); - } - } - } - MRISfree(&mris_high); - } - - return (mris_out); -} diff --git a/utils/mrisegment.c b/utils/mrisegment.cpp similarity index 100% rename from utils/mrisegment.c rename to utils/mrisegment.cpp diff --git a/utils/mriset.c b/utils/mriset.cpp similarity index 99% rename from utils/mriset.c rename to utils/mriset.cpp index ff44d68cc0f..d8dac912a44 100644 --- a/utils/mriset.c +++ b/utils/mriset.cpp @@ -42,7 +42,7 @@ double round(double x); #include "filter.h" #include "macros.h" #include "matrix.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mri.h" #include "mri2.h" #include "proto.h" @@ -3184,7 +3184,7 @@ int MRIlabeledVoxels(MRI *mri_src, int label) the values outside to be OutVal. template is a geometry template. */ -MRI *MRIsetBoundingBox(MRI *template, MRI_REGION *region, double InVal, double OutVal) +MRI *MRIsetBoundingBox(MRI *mri_template, MRI_REGION *region, double InVal, double OutVal) { MRI *mri; int x2, y2, z2; @@ -3194,19 +3194,19 @@ MRI *MRIsetBoundingBox(MRI *template, MRI_REGION *region, double InVal, double O if (region->y < 0) region->y = 0; if (region->z < 0) region->z = 0; - if (region->dx < 0) region->dx = template->width; - if (region->dy < 0) region->dy = template->height; - if (region->dz < 0) region->dz = template->depth; + if (region->dx < 0) region->dx = mri_template->width; + if (region->dy < 0) region->dy = mri_template->height; + if (region->dz < 0) region->dz = mri_template->depth; - if (region->x >= template->width) { + if (region->x >= mri_template->width) { printf("ERROR: MRIsegBoundingBox: region x >= width\n"); return (NULL); } - if (region->y >= template->height) { + if (region->y >= mri_template->height) { printf("ERROR: MRIsegBoundingBox: region y >= height\n"); return (NULL); } - if (region->z >= template->depth) { + if (region->z >= mri_template->depth) { printf("ERROR: MRIsegBoundingBox: region z >= depth\n"); return (NULL); } @@ -3214,20 +3214,20 @@ MRI *MRIsetBoundingBox(MRI *template, MRI_REGION *region, double InVal, double O y2 = region->y + region->dy; z2 = region->z + region->dz; - if (x2 >= template->width) { + if (x2 >= mri_template->width) { printf("ERROR: MRIsegBoundingBox: region x2 >= width\n"); return (NULL); } - if (y2 >= template->height) { + if (y2 >= mri_template->height) { printf("ERROR: MRIsegBoundingBox: region y2 >= height\n"); return (NULL); } - if (z2 >= template->depth) { + if (z2 >= mri_template->depth) { printf("ERROR: MRIsegBoundingBox: region z2 >= depth\n"); return (NULL); } - mri = MRIcloneBySpace(template, MRI_FLOAT, 1); + mri = MRIcloneBySpace(mri_template, MRI_FLOAT, 1); if (mri == NULL) return (NULL); for (c = 0; c < mri->width; c++) { diff --git a/utils/mrishash.c b/utils/mrishash.cpp similarity index 99% rename from utils/mrishash.c rename to utils/mrishash.cpp index c705fe20726..9230d027d1c 100644 --- a/utils/mrishash.c +++ b/utils/mrishash.cpp @@ -77,10 +77,6 @@ //================================================================== // Local structure types //================================================================== -#undef bool -#undef true -#undef false -typedef enum { false = 0, true = 1 } bool; typedef struct { @@ -1708,6 +1704,7 @@ int mhtfindClosestVertexGenericInBucket(MRIS_HASH_TABLE *mht, FindBucketsChecked_Count++; + MHB *bin; MHBT* bucket = MHTacqBucketAtVoxIx(mht, xv, yv, zv); if (!bucket) goto done; @@ -1716,7 +1713,7 @@ int mhtfindClosestVertexGenericInBucket(MRIS_HASH_TABLE *mht, //----------------------------------------- // Iterate through vertices in this bucket //----------------------------------------- - MHB *bin = bucket->bins; + bin = bucket->bins; for (vtxix = 0; vtxix < bucket->nused; vtxix++, bin++) { AVtxNum = bin->fno; @@ -1773,6 +1770,7 @@ int mhtfindClosestFaceCentroidGenericInBucket(MRIS_HASH_TABLE *mht, FindBucketsChecked_Count++; + MHB *bin; MHBT *bucket = MHTacqBucketAtVoxIx(mht, xv, yv, zv); if (!bucket) goto done; @@ -1781,7 +1779,7 @@ int mhtfindClosestFaceCentroidGenericInBucket(MRIS_HASH_TABLE *mht, //----------------------------------------- // Iterate through vertices in this bucket //----------------------------------------- - MHB *bin = bucket->bins; + bin = bucket->bins; int faceix; for (faceix = 0; faceix < bucket->nused; faceix++, bin++) { diff --git a/utils/mrisp.c b/utils/mrisp.cpp similarity index 99% rename from utils/mrisp.c rename to utils/mrisp.cpp index 5ab4bae9e73..ad734d4715f 100644 --- a/utils/mrisp.c +++ b/utils/mrisp.cpp @@ -2558,7 +2558,7 @@ MRI_SP *MRISPcombine(MRI_SP *mrisp, MRI_SP *mrisp_template, int fno) Description ------------------------------------------------------*/ -int MRISPwrite(MRI_SP *mrisp, char *fname) +int MRISPwrite(MRI_SP *mrisp, const char *fname) { char ext[STRLEN] ; diff --git a/utils/mrisurf.c b/utils/mrisurf.cpp similarity index 99% rename from utils/mrisurf.c rename to utils/mrisurf.cpp index 013ac357205..e06ef62bf42 100644 --- a/utils/mrisurf.c +++ b/utils/mrisurf.cpp @@ -125,7 +125,7 @@ static size_t showHashCalc; static bool vertix_n_hash_add(size_t vectorSize, MRIS_HASH* hashVector, MRIS const ** mrisPVector, FILE* showDiff, int vno) { - int i; + unsigned int i; #define SEP #define ELTP(TARGET, MBR) // don't hash pointers. Sometime may implement hashing their target #define ELTX(TYPE, MBR) // don't hash excluded elements @@ -213,7 +213,7 @@ static bool vertix_n_hash_add(size_t vectorSize, MRIS_HASH* hashVector, MRIS con static bool face_n_hash_add(size_t vectorSize, MRIS_HASH* hashVector, MRIS const ** mrisPVector, FILE* showDiff, int fno) { - int i; + unsigned int i; #define SEP #define ELTP(TARGET,NAME) // don't hash pointers #define ELTT(TYPE, MBR) \ @@ -278,7 +278,7 @@ static bool mris_n_hash_add(size_t vectorSize, MRIS_HASH* hashVector, MRIS const void mrisVertexHash(MRIS_HASH* hash, MRIS const * mris, int vno) { hash->hash = fnv_init(); - vertix_n_hash_add(1, hash, &mris, false, vno); + vertix_n_hash_add(1, hash, &mris, nullptr, vno); } void mris_hash_add(MRIS_HASH* hash, MRIS const * mris) diff --git a/utils/mrisurf_base.c b/utils/mrisurf_base.cpp similarity index 98% rename from utils/mrisurf_base.c rename to utils/mrisurf_base.cpp index 741f0d4793a..d8d91991ae7 100644 --- a/utils/mrisurf_base.c +++ b/utils/mrisurf_base.cpp @@ -100,7 +100,7 @@ int MRISsetInflatedFileName(char *inflated_name) mrisurf_surface_names[0] = inflated_name; sprintf(fname, "%s.H", inflated_name); - char * copy = calloc(strlen(fname) + 1, sizeof(char)); + char * copy = (char *)calloc(strlen(fname) + 1, sizeof(char)); strcpy(copy, fname); curvature_names[0] = copy; return (NO_ERROR); @@ -259,7 +259,7 @@ static void changeDistOrDistOrig(bool doOrig, MRIS *mris, int vno, int oldSize, mris->dist_alloced_flags |= flag; } - *(float**)pc = *p_storage; + *(float**)pc = (float *)*p_storage; *(int *)pcCap = neededCapacity; } @@ -276,7 +276,7 @@ float* mrisStealDistStore(MRIS* mris, int vno, int capacity) { VERTEX const * const v = &mris->vertices[vno]; float* p = NULL; - if (v->dist == NULL) { p = mris->dist_storage[vno]; mris->dist_storage[vno] = NULL; } + if (v->dist == NULL) { p = (float *)mris->dist_storage[vno]; mris->dist_storage[vno] = NULL; } return (float*)realloc(p, capacity*sizeof(float)); } @@ -298,7 +298,8 @@ void mrisSetDist(MRIS* mris, int vno, float* dist, int newCapacity) { float * * p = (float**)pc; if (mris->dist_storage[vno]) free(mris->dist_storage[vno]); // very frequently avoid the lock - *p = mris->dist_storage[vno] = dist; + mris->dist_storage[vno] = dist; + *p = dist; const int * pcCap = &v->dist_capacity; *(int*)pcCap = newCapacity; } @@ -422,7 +423,7 @@ void mrisDumpVertex(FILE* file, MRIS const * mris, int vno) { } -void mrisDumpFace(FILE* file, MRIS const * mris, int fno) { +void mrisDumpFace(MRIS const * mris, int fno, FILE* file) { FACE const * const f = &mris->faces[fno]; fprintf(file, "fno:%d ripflag:%d marked:%d\n", fno, f->ripflag, f->marked); @@ -440,7 +441,7 @@ void mrisDumpShape(FILE* file, MRIS const * mris) { int vno; for (vno = 0; vno < MIN(10,mris->nvertices); vno++) mrisDumpVertex(file, mris, vno); int fno; - for (fno = 0; fno < MIN(10,mris->nfaces); fno++) mrisDumpFace(file, mris, fno); + for (fno = 0; fno < MIN(10,mris->nfaces); fno++) mrisDumpFace(mris, fno, file); fprintf(file, "} // mrisDumpShape\n"); } @@ -803,8 +804,7 @@ int MRISsetCurvatureName(int nth, char const *name) int MRISprintCurvatureNames(FILE *fp) { - int k; - for (k = 0; k < sizeof(curvature_names) / sizeof(curvature_names[0]); k++) { + for (unsigned int k = 0; k < sizeof(curvature_names) / sizeof(curvature_names[0]); k++) { if (curvature_names[k]) printf("%d %s\n", k, curvature_names[k]); else if (mrisurf_surface_names[k]) @@ -1510,7 +1510,7 @@ void cprints(char *apch_left, char *apch_right) fflush(stderr); } -void cprintd(char *apch_left, int a_right) +void cprintd(const char *apch_left, int a_right) { // // PRECONDITIONS @@ -1609,7 +1609,7 @@ short VECTOR_elementIndex_find(VECTOR *apV, float af_searchTerm) } -short MRIS_vertexProgress_print(MRIS *apmris, int avertex, char *apch_message) +short MRIS_vertexProgress_print(MRIS *apmris, int avertex, const char *apch_message) { // // PRECONDITIONS diff --git a/utils/mrisurf_defect.c b/utils/mrisurf_defect.cpp similarity index 99% rename from utils/mrisurf_defect.c rename to utils/mrisurf_defect.cpp index b659cddd7ea..03a5031c83b 100644 --- a/utils/mrisurf_defect.c +++ b/utils/mrisurf_defect.cpp @@ -196,7 +196,7 @@ static void mrisFreeDefectVertexState(DEFECT_VERTEX_STATE *dvs) static DEFECT_VERTEX_STATE* mrisRecordVertexState(MRIS const * const mris, DEFECT * const defect, int * const vertex_trans) { - DEFECT_VERTEX_STATE* const dvs = calloc(1, sizeof(DVS)); + DEFECT_VERTEX_STATE* const dvs = (DVS *)calloc(1, sizeof(DVS)); if (!dvs) ErrorExit(ERROR_NOMEMORY, "mrisRecordVertexState: could not allocate dvs"); dvs->defect = defect; @@ -331,6 +331,7 @@ static void mrisRestoreOneVertexFaceState(MRI_SURFACE *mris, DEFECT_VERTEX_STATE static void mrisRestoreOneVertexState(MRI_SURFACE *mris, DEFECT_VERTEX_STATE *dvs, int const i) { VERTEX_STATE const * const vs = &dvs->vs[i]; + int vsize; int const vno = vs->vno; if (vno < 0) return; @@ -360,7 +361,7 @@ static void mrisRestoreOneVertexState(MRI_SURFACE *mris, DEFECT_VERTEX_STATE *dv MRIS_setNsizeCur(mris, vno, vs->nsizeCur); cheapAssert(vt->vtotal == vs->vtotal); - int const vsize = mrisVertexVSize(mris, vno); + vsize = mrisVertexVSize(mris, vno); if (vsize > 0) { // keep the zero-size ones for faster future realloc's, realloc the non-zero ones now @@ -2022,7 +2023,7 @@ static void cachedOrComputeVertexPseudoNormal( if (0) { cheapAssert(0 <= index); cheapAssert(index < PerThreadVertexPseudoNormalCacheSize); - cheapAssert(initedIndex < PerThreadVertexPseudoNormalCacheInitedSize); + cheapAssert((unsigned)initedIndex < PerThreadVertexPseudoNormalCacheInitedSize); } inited = p->inited[initedIndex] & initedMask; @@ -8405,7 +8406,7 @@ int topology_fixing_exit_after_diag = 0; MRI_SURFACE *MRIScorrectTopology( MRI_SURFACE *mris, MRI *mri, MRI *mri_wm, - int nsmooth, TOPOLOGY_PARMS *parms, char *defectbase) + int nsmooth, TOPOLOGY_PARMS *parms, const char *defectbase) { FACE_DEFECT_LIST *fdl; DEFECT_LIST *dl; @@ -15521,12 +15522,12 @@ mrisCheckDefectEdges(MRI_SURFACE *mris, DEFECT *defect, int vno, See if the edge e intersects any edges in the defect or it's border. ------------------------------------------------------*/ - static bool isHit(MRI_SURFACE * mris, int vno, DEFECT *defect, EDGE* e, int n, char* whyTracing) { + static bool isHit(MRI_SURFACE * mris, int vno, DEFECT *defect, EDGE* e, int n, const char* whyTracing) { bool result = false; if (vno == e->vno1 || vno == e->vno2 || vno < 0) { if (whyTracing) fprintf(stderr, "isHit false because shared vno when %s\n", whyTracing); - goto Done; + return false; } EDGE edge2; diff --git a/utils/mrisurf_deform.c b/utils/mrisurf_deform.cpp similarity index 99% rename from utils/mrisurf_deform.c rename to utils/mrisurf_deform.cpp index 5c5acd73987..b4a57006e3c 100644 --- a/utils/mrisurf_deform.c +++ b/utils/mrisurf_deform.cpp @@ -9495,9 +9495,10 @@ static float neg_area_ratios[] = { int mrisRemoveNegativeArea( MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int base_averages, float min_area_pct, int max_passes) { - int total_steps, done, steps, n_averages, old_averages, npasses, niter; + unsigned int npasses; + int total_steps, done, steps, n_averages, old_averages, niter; float pct_neg, ratio; - char *snum, *sdenom; + const char *snum, *sdenom; float l_area, l_parea, l_corr, l_spring, l_dist, l_nlarea, *pnum, *pdenom, cmod; double tol; @@ -12622,8 +12623,7 @@ int MRISrigidBodyAlignGlobal( float const max_radians = RADIANS(max_degrees); printf("Starting MRISrigidBodyAlignGlobal()\n"); - struct timeb mytimer; - TimerStart(&mytimer); + Timer mytimer; int const old_norm = parms->abs_norm; parms->abs_norm = 1; @@ -12661,8 +12661,7 @@ int MRISrigidBodyAlignGlobal( if (use_new) { printf("Starting new MRISrigidBodyAlignGlobal_findMinSSE()\n"); - struct timeb new_timer; - TimerStart(&new_timer); + Timer new_timer; // This does not modify either mris or params until after the old code has executed // @@ -12679,7 +12678,7 @@ int MRISrigidBodyAlignGlobal( parms->start_t += 1.0f; parms->t += 1.0f; - int msec = TimerStop(&new_timer); + int msec = new_timer.milliseconds(); printf(" new MRISrigidBodyAlignGlobal_findMinSSE" " min @ (%2.2f, %2.2f, %2.2f) sse = %2.1f, elapsed since starting=%6.4f min\n", (float)DEGREES(new_mina), (float)DEGREES(new_minb), (float)DEGREES(new_ming), new_sse, @@ -12690,8 +12689,7 @@ int MRISrigidBodyAlignGlobal( if (use_old) { printf("Starting old MRISrigidBodyAlignGlobal_findMinSSE()\n"); - struct timeb old_timer; - TimerStart(&old_timer); + Timer old_timer; // Note: // This used to do a series of smaller and smaller rotations to mris_sphere, rotating the sphere to the minimum each time. @@ -12782,7 +12780,7 @@ int MRISrigidBodyAlignGlobal( } } // alpha - int msec = TimerStop(&old_timer); + int msec = old_timer.milliseconds(); printf(" min @ (%2.2f, %2.2f, %2.2f) sse = %2.1f, elapsed since starting=%6.4f min\n", (float)DEGREES(mina), (float)DEGREES(minb), (float)DEGREES(ming), (float)(min_sse + ext_sse), @@ -12811,7 +12809,7 @@ int MRISrigidBodyAlignGlobal( old_mina = center_a; old_minb = center_b, old_ming = center_g, old_sse = center_sse; - int msec = TimerStop(&old_timer); + int msec = old_timer.milliseconds(); printf(" old MRISrigidBodyAlignGlobal_findMinSSE" " min @ (%2.2f, %2.2f, %2.2f) sse = %2.1f, elapsed since starting=%6.4f min\n", (float)DEGREES(old_mina), (float)DEGREES(old_minb), (float)DEGREES(old_ming), old_sse, @@ -12849,7 +12847,7 @@ int MRISrigidBodyAlignGlobal( mris->status = old_status; parms->abs_norm = old_norm; - int msec = TimerStop(&mytimer); + int msec = mytimer.milliseconds(); printf("MRISrigidBodyAlignGlobal() done %6.2f min\n", msec / (1000 * 60.0)); return (NO_ERROR); diff --git a/utils/mrisurf_integrate.c b/utils/mrisurf_integrate.cpp similarity index 99% rename from utils/mrisurf_integrate.c rename to utils/mrisurf_integrate.cpp index 6b05d6f80c6..772b526b255 100644 --- a/utils/mrisurf_integrate.c +++ b/utils/mrisurf_integrate.cpp @@ -235,7 +235,7 @@ int mrisLogIntegrationParms(FILE *fp, MRI_SURFACE *mris, INTEGRATION_PARMS *parm static int mrisIntegrationEpoch(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int base_averages) { int total_steps, done, steps, n_averages, old_averages; - char *snum, *sdenom; + const char *snum, *sdenom; float ratio, *pdenom, *pnum; if (!FZERO(parms->l_corr)) { @@ -764,7 +764,6 @@ int MRISregister(MRI_SURFACE *mris, MRI_SP *mrisp; char fname[STRLEN], base_name[STRLEN], path[STRLEN]; double base_dt; - struct timeb start; int first = 1; INTEGRATION_PARMS saved_parms; @@ -781,7 +780,7 @@ int MRISregister(MRI_SURFACE *mris, if (IS_QUADRANGULAR(mris)) { MRISremoveTriangleLinks(mris); } - TimerStart(&start); + Timer start; FileNamePath(mris->fname, path); sprintf(base_name, "%s/%s.%s", path, mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh", parms->base_name); @@ -1149,7 +1148,7 @@ int MRISregister(MRI_SURFACE *mris, MRISPfree(&parms->mrisp) ; MRISPfree(&parms->mrisp_template) ; #endif - msec = TimerStop(&start); + msec = start.milliseconds(); if (Gdiag & DIAG_SHOW) fprintf(stdout, "registration took %2.2f hours\n", (float)msec / (1000.0f * 60.0f * 60.0f)); if (Gdiag & DIAG_WRITE) { fprintf(parms->fp, "registration took %2.2f hours\n", (float)msec / (1000.0f * 60.0f * 60.0f)); @@ -1179,7 +1178,6 @@ int MRISvectorRegister(MRI_SURFACE *mris, VERTEX *v; char fname[STRLEN], base_name[STRLEN], path[STRLEN]; double base_dt; - struct timeb start; static int first = 1; int n, fno, ncorrs; int *frames, nframes, nf, *indices; @@ -1189,7 +1187,7 @@ int MRISvectorRegister(MRI_SURFACE *mris, if (IS_QUADRANGULAR(mris)) { MRISremoveTriangleLinks(mris); } - TimerStart(&start); + Timer start; MRISsaveVertexPositions(mris, ORIGINAL_VERTICES); FileNamePath(mris->fname, path); sprintf(base_name, "%s/%s.%s", path, mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh", parms->base_name); @@ -1245,7 +1243,7 @@ int MRISvectorRegister(MRI_SURFACE *mris, /* allocate the VALS_VP structure */ for (n = 0; n < mris->nvertices; n++) { v = &mris->vertices[n]; - vp = calloc(1, sizeof(VALS_VP)); + vp = (VALS_VP *)calloc(1, sizeof(VALS_VP)); vp->nvals = ncorrs; vp->orig_vals = (float *)calloc(ncorrs, sizeof(float)); /* before blurring */ vp->vals = (float *)malloc(ncorrs * sizeof(float)); /* values used by @@ -1543,7 +1541,7 @@ int MRISvectorRegister(MRI_SURFACE *mris, free(frames); free(indices); - msec = TimerStop(&start); + msec = start.milliseconds(); if (Gdiag & DIAG_SHOW) fprintf(stdout, "registration took %2.2f hours\n", (float)msec / (1000.0f * 60.0f * 60.0f)); if (Gdiag & DIAG_WRITE) fprintf(parms->fp, "registration took %2.2f hours\n", (float)msec / (1000.0f * 60.0f * 60.0f)); @@ -2155,7 +2153,6 @@ MRI_SURFACE *MRISunfold(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int max_pas { int base_averages, i, nbrs[MAX_NBHD_SIZE], niter, passno, msec, use_nl_area; double starting_sse, ending_sse, l_area, pct_error; - struct timeb start; printf("MRISunfold() max_passes = %d -------\n", max_passes); mrisLogIntegrationParms(stdout, mris, parms); @@ -2166,7 +2163,7 @@ MRI_SURFACE *MRISunfold(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int max_pas if (IS_QUADRANGULAR(mris)) { MRISremoveTriangleLinks(mris); } - TimerStart(&start); + Timer start; starting_sse = ending_sse = 0.0f; /* compiler warning */ memset(nbrs, 0, MAX_NBHD_SIZE * sizeof(nbrs[0])); #if 0 @@ -2323,7 +2320,7 @@ MRI_SURFACE *MRISunfold(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int max_pas parms->tol = tol; } - for (i = 0; i < NCOEFS; i++) { + for (i = 0; (unsigned)i < NCOEFS; i++) { if (mris->status == MRIS_SPHERE && i == NCOEFS - 1) { continue; } @@ -2436,7 +2433,7 @@ MRI_SURFACE *MRISunfold(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int max_pas pct_error = MRISpercentDistanceError(mris); fprintf(stdout, "final distance error %%%2.2f\n", (float)pct_error); mrisProjectSurface(mris); - msec = TimerStop(&start); + msec = start.milliseconds(); if (Gdiag & DIAG_SHOW) { mrisLogStatus(mris, parms, stderr, 0, -1); fprintf(stdout, "optimization complete.\n"); @@ -2465,11 +2462,10 @@ MRI_SURFACE *MRISquickSphere(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int ma { int niter, passno, msec, nbrs[MAX_NBHD_SIZE], i, use_dists, base_averages; double pct_error, orig_k, last_sse, sse, pct_change; - struct timeb start; orig_k = NEG_AREA_K; - TimerStart(&start); + Timer start; if (IS_QUADRANGULAR(mris)) { MRISremoveTriangleLinks(mris); @@ -2569,7 +2565,7 @@ MRI_SURFACE *MRISquickSphere(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int ma pct_error = MRISpercentDistanceError(mris); fprintf(stdout, "final distance error %%%2.2f\n", (float)pct_error); mrisProjectSurface(mris); - msec = TimerStop(&start); + msec = start.milliseconds(); if (Gdiag & DIAG_SHOW) { mrisLogStatus(mris, parms, stderr, 0, -1); fprintf(stdout, "optimization complete.\n"); diff --git a/utils/mrisurf_io.c b/utils/mrisurf_io.cpp similarity index 99% rename from utils/mrisurf_io.c rename to utils/mrisurf_io.cpp index 71060f00168..c3eb5829f41 100644 --- a/utils/mrisurf_io.c +++ b/utils/mrisurf_io.cpp @@ -76,7 +76,8 @@ int MRISreadTriangleProperties(MRI_SURFACE *mris, const char *mris_fname) float f; FILE *fp; - char fname[STRLEN], fpref[STRLEN], hemi[20], *cp; + char fname[STRLEN], fpref[STRLEN], hemi[20]; + const char *cp; if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) { fprintf(stdout, "reading triangle files..."); @@ -203,7 +204,8 @@ int MRISwriteTriangleProperties(MRI_SURFACE *mris, const char *mris_fname) int fno, ano, vno; FACE *face; FILE *fp; - char fname[STRLEN], fpref[STRLEN], hemi[20], *cp; + char fname[STRLEN], fpref[STRLEN], hemi[20]; + const char *cp; MRIScomputeTriangleProperties(mris); @@ -285,7 +287,9 @@ int MRISwriteCurvature(MRI_SURFACE *mris, const char *sname) { int k, mritype; float curv; - char fname[STRLEN], *cp, path[STRLEN], name[STRLEN], *hemi; + char fname[STRLEN], path[STRLEN], name[STRLEN]; + const char *hemi; + const char *cp; FILE *fp; switch (mris->hemisphere) { @@ -396,7 +400,8 @@ int MRISwriteDists(MRI_SURFACE *mris, const char *sname) { int k, i; float dist; - char fname[STRLEN], *cp, path[STRLEN]; + char fname[STRLEN], path[STRLEN]; + const char *cp; FILE *fp; cp = strchr(sname, '/'); @@ -1408,7 +1413,8 @@ int MRISreadAnnotation(MRI_SURFACE *mris, const char *sname) { int vno, need_hemi; int return_code; - char *cp, fname[STRLEN], path[STRLEN], fname_no_path[STRLEN]; + char fname[STRLEN], path[STRLEN], fname_no_path[STRLEN]; + const char *cp; int *array; #if 0 int numannothist; @@ -2224,7 +2230,8 @@ int mrisWriteSnapshots(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int t) ------------------------------------------------------*/ int mrisWriteSnapshot(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int t) { - char fname[STRLEN], path[STRLEN], base_name[STRLEN], *cp, *hemi; + char fname[STRLEN], path[STRLEN], base_name[STRLEN], *cp; + const char *hemi; switch (mris->hemisphere) { case LEFT_HEMISPHERE: @@ -4139,7 +4146,7 @@ static MRIS* MRISreadOverAlloc_new(const char *fname, double nVFMultiplier) case TAG_CMDLINE: if (mris->ncmds > MAX_CMDS) ErrorExit(ERROR_NOMEMORY, "mghRead(%s): too many commands (%d) in file", fname, mris->ncmds); - mris->cmdlines[mris->ncmds] = calloc(len + 1, sizeof(char)); + mris->cmdlines[mris->ncmds] = (char *)calloc(len + 1, sizeof(char)); fread(mris->cmdlines[mris->ncmds], sizeof(char), len, fp); mris->cmdlines[mris->ncmds][len] = 0; mris->ncmds++; @@ -4553,7 +4560,7 @@ static MRIS* MRISreadOverAlloc_old(const char *fname, double nVFMultiplier) case TAG_CMDLINE: if (mris->ncmds > MAX_CMDS) ErrorExit(ERROR_NOMEMORY, "mghRead(%s): too many commands (%d) in file", fname, mris->ncmds); - mris->cmdlines[mris->ncmds] = calloc(len + 1, sizeof(char)); + mris->cmdlines[mris->ncmds] = (char *)calloc(len + 1, sizeof(char)); fread(mris->cmdlines[mris->ncmds], sizeof(char), len, fp); mris->cmdlines[mris->ncmds][len] = 0; mris->ncmds++; @@ -5362,7 +5369,8 @@ int MRISreadCurvatureFile(MRI_SURFACE *mris, const char *sname) int k, i, vnum, fnum; float curv = 0, curvmin, curvmax; FILE *fp; - char *cp, path[STRLEN], fname[STRLEN], type; + const char *cp; + char path[STRLEN], fname[STRLEN], type; int mritype, frame, nv, c, r, s, vno; MRI *TempMRI; @@ -5525,7 +5533,8 @@ int MRISreadCurvatureFile(MRI_SURFACE *mris, const char *sname) ------------------------------------------------------*/ float *MRISreadCurvatureVector(MRI_SURFACE *mris, const char *sname) { - char *cp, path[STRLEN], fname[STRLEN]; + const char *cp; + char path[STRLEN], fname[STRLEN]; float *cvec = NULL; int return_code = ERROR_NONE; @@ -5616,7 +5625,8 @@ int MRISreadFloatFile(MRI_SURFACE *mris, const char *sname) int k, vnum, fnum; float f; FILE *fp; - char *cp, path[STRLEN], fname[STRLEN]; + const char *cp; + char path[STRLEN], fname[STRLEN]; cp = strchr(sname, '/'); if (!cp) /* no path - use same one as mris was read from */ @@ -5826,7 +5836,7 @@ int MRISwriteTriangularSurface(MRI_SURFACE *mris, const char *fname) if (!user) { user = "UNKNOWN"; } - time_str = current_date_time(); + time_str = currentDateTime().c_str(); if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf(stdout, "writing surface file %s, created by %s on %s.\n", fname, user, time_str); fp = fopen(fname, "w"); @@ -6092,7 +6102,7 @@ static MRI_SURFACE *mrisReadTriangleFile(const char *fname, double nVFMultiplier case TAG_CMDLINE: if (mris->ncmds > MAX_CMDS) ErrorExit(ERROR_NOMEMORY, "MRISread(%s): too many commands (%d) in file", fname, mris->ncmds); - mris->cmdlines[mris->ncmds] = calloc(len + 1, sizeof(char)); + mris->cmdlines[mris->ncmds] = (char *)calloc(len + 1, sizeof(char)); if (mris->cmdlines[mris->ncmds] == NULL) ErrorExit(ERROR_NOMEMORY, "MRISread(%s): could not allocate %d byte cmdline", fname, len); mris->cmdlines[mris->ncmds][len] = 0; @@ -6121,7 +6131,8 @@ static MRI_SURFACE *mrisReadTriangleFile(const char *fname, double nVFMultiplier ------------------------------------------------------*/ int MRISbuildFileName(MRI_SURFACE *mris, const char *sname, char *fname) { - char path[STRLEN], *slash, *dot; + char path[STRLEN]; + const char *slash, *dot; slash = strchr(sname, '/'); if (!slash) /* no path - use same one as mris was read from */ @@ -6233,7 +6244,8 @@ int MRISreadNewCurvatureFile(MRI_SURFACE *mris, const char *sname) int k, vnum, fnum, vals_per_vertex; float curv, curvmin, curvmax; FILE *fp; - char *cp, path[STRLEN], fname[STRLEN]; + const char *cp; + char path[STRLEN], fname[STRLEN]; cp = strchr(sname, '/'); if (!cp) /* no path - use same one as mris was read from */ @@ -6306,7 +6318,8 @@ int MRISreadNewCurvatureFile(MRI_SURFACE *mris, const char *sname) } float *MRISreadNewCurvatureVector(MRI_SURFACE *mris, const char *sname) { - char *cp, path[STRLEN], fname[STRLEN]; + const char *cp; + char path[STRLEN], fname[STRLEN]; float *cvec = NULL; int return_code = ERROR_NONE; diff --git a/utils/mrisurf_metricProperties.c b/utils/mrisurf_metricProperties.cpp similarity index 99% rename from utils/mrisurf_metricProperties.c rename to utils/mrisurf_metricProperties.cpp index a3dcb1107d0..a826f9a6856 100644 --- a/utils/mrisurf_metricProperties.c +++ b/utils/mrisurf_metricProperties.cpp @@ -1802,18 +1802,17 @@ int MRIScomputeMetricProperties(MRIS *mris) if (count_MRIScomputeMetricProperties_calls == debug_count) { fprintf(stdout, "b %s:%d needed with debug_count:%d\n", __FILE__, __LINE__, count_MRIScomputeMetricProperties_calls); } - + bool const useOldBehaviour = !!getenv("FREESURFER_OLD_MRIScomputeMetricProperties"); bool const useNewBehaviour = !!getenv("FREESURFER_NEW_MRIScomputeMetricProperties") || !useOldBehaviour; - MRIS_MP mp; + MRIS_MP mp = MRIS_MP(); MRISMP_ctr(&mp); if (useNewBehaviour) { MRISfreeDistsButNotOrig(mris); // So they can be stolen to avoid unnecessary mallocs and frees - - MRISMP_load(mris, &mp); // Copy the input data before MRIScomputeMetricPropertiesWkr changes it - MRISMP_computeMetricProperties(&mp); // It should not matter the order these are done in + MRISMP_load(mris, &mp); // Copy the input data before MRIScomputeMetricPropertiesWkr changes it + MRISMP_computeMetricProperties(&mp); // It should not matter the order these are done in } if (useOldBehaviour) { @@ -3412,7 +3411,7 @@ float FACES_commonEdgeLength_find(MRIS *apmris, FACE *apFACE_I, FACE *apFACE_J) // static int calls = 0; - char *pch_function = "FACES_commonEdgeLength_find"; + const char *pch_function = "FACES_commonEdgeLength_find"; VERTEX *pVERTEX_O = NULL; // Common vertex O VERTEX *pVERTEX_I = NULL; // Common vertex I static VECTOR *pVECTOR_O = NULL; // Common vertex O cart. coords @@ -5823,7 +5822,7 @@ short FACES_Hcurvature_determineSign(MRIS *apmris, // static int calls = 0; - char *pch_function = "FACES_Hcurvature_determineSign"; + const char *pch_function = "FACES_Hcurvature_determineSign"; int ret = 0; int vertexO = -1; int vertexI = -1; @@ -5916,7 +5915,7 @@ int VERTEX_faceAngles_determine(MRIS *apmris, int avertex, VECTOR *apv_angle) // o Initial design and coding. // - char *pch_function = "VERTEX_faceAngles_determine"; + const char *pch_function = "VERTEX_faceAngles_determine"; int nfaces = -1; float f_angle = 0.; float f_lenApexNormal = 0.; @@ -6006,7 +6005,7 @@ float FACES_angleNormal_find(MRIS *apmris, int apFACE_I_fno, int apFACE_J_fno) float f_acosArg = 0.; // Dot product arguments float f_dot = 0.; // Dot product short sign = 1; // Angle "sign" - char *pch_function = "FACES_angleNormal_find"; + const char *pch_function = "FACES_angleNormal_find"; DebugEnterFunction(("%s", pch_function)); if (!calls) { @@ -6060,7 +6059,7 @@ int VERTEX_faceMinMaxAngles_determine( // o Initial design and coding. // - char *pch_function = "VERTEX_faceMinMaxAngles_determine"; + const char *pch_function = "VERTEX_faceMinMaxAngles_determine"; int face = 0; // Face index counte int nfaces = 0; // Number of faces at float f_faceAngle = 0.; // Actual face angle @@ -6153,7 +6152,7 @@ short MRIS_discreteKH_compute(MRIS *apmris) // computed. // - char *pch_function = "MRIS_discreteKH_compute"; + const char *pch_function = "MRIS_discreteKH_compute"; VECTOR *pv_geometricOrder = NULL; // Geometrically ordered faces int vertex = 0; // Vertex index number @@ -6261,7 +6260,7 @@ short MRIS_discretek1k2_compute(MRIS *apmris, short ab_signedPrinciples) // f_abs(..) size. // - char *pch_function = "MRIS_discretek1k2_compute"; + const char *pch_function = "MRIS_discretek1k2_compute"; VERTEX *pVERTEX = NULL; float f_k1 = 0.; float f_k2 = 0.; @@ -9915,7 +9914,7 @@ int MRISaverageGradients(MRIS *mris, int num_avgs) float sigma; VERTEX *v; MRI_SP *mrisp, *mrisp_blur; - char *UFSS; + const char *UFSS; // Must explicity "setenv USE_FAST_SURF_SMOOTHER 0" to turn off fast UFSS = getenv("USE_FAST_SURF_SMOOTHER"); @@ -10151,7 +10150,7 @@ int MRISaverageGradients(MRIS *mris, int num_avgs) // Do all the iterations for (i = 0 ; i < num_avgs ; i++) { - int chunksIndex; + unsigned int chunksIndex; ROMP_PF_begin #ifdef HAVE_OPENMP #pragma omp parallel for if_ROMP(assume_reproducible) @@ -10467,7 +10466,7 @@ int MRISaverageGradientsFastCheck(int num_avgs) char tmpstr[2000], *UFSS; MRIS *mrisA, *mrisB; int k, msec, nerrs; - struct timeb mytimer; + Timer mytimer; float e; // Make sure to turn off override (restored later) @@ -10502,15 +10501,15 @@ int MRISaverageGradientsFastCheck(int num_avgs) mrisB->vertices[100].ripflag = 1; printf("Running Original Version\n"); - TimerStart(&mytimer); + mytimer.reset(); MRISaverageGradients(mrisA, num_avgs); - msec = TimerStop(&mytimer); + msec = mytimer.milliseconds(); printf("Original %6.2f min\n", msec / (1000 * 60.0)); printf("Running Fast Version\n"); - TimerStart(&mytimer); + mytimer.reset(); MRISaverageGradientsFast(mrisB, num_avgs); - msec = TimerStop(&mytimer); + msec = mytimer.milliseconds(); printf("Fast %6.2f min\n", msec / (1000 * 60.0)); printf("Checking for differences\n"); @@ -13280,7 +13279,7 @@ MRI *MRISsmoothKernel(MRIS *surf, MRI *src, MRI *mask, MRI *mrikern, MATRIX *glo double *kern; int n, nhops; SURFHOPLIST **shl; - struct timeb mytimer; + Timer mytimer; int msecTime; if (mrikern && globkern) { @@ -13321,7 +13320,7 @@ MRI *MRISsmoothKernel(MRIS *surf, MRI *src, MRI *mask, MRI *mrikern, MATRIX *glo crslut = MRIScrsLUT(surf, src); if (*pshl == NULL) { - TimerStart(&mytimer); + mytimer.reset(); printf("Allocating shl %d\n", surf->nvertices); shl = (SURFHOPLIST **)calloc(sizeof(SURFHOPLIST *), surf->nvertices); ROMP_PF_begin @@ -13339,14 +13338,14 @@ MRI *MRISsmoothKernel(MRIS *surf, MRI *src, MRI *mask, MRI *mrikern, MATRIX *glo ROMP_PF_end *pshl = shl; - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); printf("Done allocating shl %d, %g sec\n", surf->nvertices, msecTime / 1000.0); } else shl = *pshl; printf("Starting loop over %d vertices\n", surf->nvertices); - TimerStart(&mytimer); + mytimer.reset(); ROMP_PF_begin #ifdef _OPENMP #pragma omp parallel for if_ROMP(experimental) @@ -13412,7 +13411,7 @@ MRI *MRISsmoothKernel(MRIS *surf, MRI *src, MRI *mask, MRI *mrikern, MATRIX *glo ROMP_PF_end printf("\n"); - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); printf("Finished loop over %d vertices, %d hops, t=%g sec\n", surf->nvertices, nhops, msecTime / 1000.0); printf("vtxval %g\n", MRIFseq_vox(out, 1031, 0, 0, 0)); diff --git a/utils/mrisurf_mri.c b/utils/mrisurf_mri.cpp similarity index 99% rename from utils/mrisurf_mri.c rename to utils/mrisurf_mri.cpp index c3248b93b45..7bb215136c4 100644 --- a/utils/mrisurf_mri.c +++ b/utils/mrisurf_mri.cpp @@ -64,7 +64,6 @@ int MRISpositionSurfaces(MRI_SURFACE *mris, MRI **mri_flash, int nvolumes, INTEG double pial_sse, sse, wm_sse, delta_t = 0.0, dt, l_intensity, base_dt, last_sse, rms, mle_sse, last_mle_sse, pct_sse_decrease, l_repulse, l_surf_repulse, last_wm_sse, last_pial_sse; MHT *mht = NULL; - struct timeb then; int msec; MRI *mri_brain = mri_flash[0]; @@ -72,7 +71,7 @@ int MRISpositionSurfaces(MRI_SURFACE *mris, MRI **mri_flash, int nvolumes, INTEG if (IS_QUADRANGULAR(mris)) { MRISremoveTriangleLinks(mris); } - TimerStart(&then); + Timer then; parms->mri_smooth = parms->mri_brain = mri_brain; niterations = parms->niterations; write_iterations = parms->write_iterations; @@ -380,7 +379,7 @@ int MRISpositionSurfaces(MRI_SURFACE *mris, MRI **mri_flash, int nvolumes, INTEG parms->start_t = n; parms->dt = base_dt; if (Gdiag & DIAG_SHOW) { - msec = TimerStop(&then); + msec = then.milliseconds(); fprintf(stdout, "positioning took %2.1f minutes\n", (float)msec / (60 * 1000.0f)); } if (Gdiag & DIAG_WRITE) { @@ -400,7 +399,6 @@ int MRISpositionSurface(MRI_SURFACE *mris, MRI *mri_brain, MRI *mri_smooth, INTE int avgs, niterations, n, write_iterations, nreductions = 0, done; double sse, delta_t = 0.0, rms, dt, l_intensity, base_dt, last_sse, last_rms, max_mm; MHT *mht = NULL, *mht_v_orig = NULL, *mht_v_current = NULL, *mht_f_current = NULL, *mht_pial = NULL; - struct timeb then; int msec; printf("Entering MRISpositionSurface()\n"); @@ -421,7 +419,7 @@ int MRISpositionSurface(MRI_SURFACE *mris, MRI *mri_brain, MRI *mri_smooth, INTE if (IS_QUADRANGULAR(mris)) { MRISremoveTriangleLinks(mris); } - TimerStart(&then); + Timer then; parms->mri_brain = mri_brain; parms->mri_smooth = mri_smooth; niterations = parms->niterations; @@ -769,7 +767,7 @@ int MRISpositionSurface(MRI_SURFACE *mris, MRI *mri_brain, MRI *mri_smooth, INTE parms->start_t = n; parms->dt = base_dt; if (Gdiag & DIAG_SHOW) { - msec = TimerStop(&then); + msec = then.milliseconds(); fprintf(stdout, "positioning took %2.1f minutes\n", (float)msec / (60 * 1000.0f)); } if (Gdiag & DIAG_WRITE) { @@ -800,7 +798,6 @@ int MRISpositionSurface_mef( int avgs, niterations, n, write_iterations, nreductions = 0, done; double delta_t = 0.0, rms, dt, l_intensity, base_dt, last_rms, max_mm, sse, last_sse, delta_rms; MHT *mht = NULL, *mht_v_orig = NULL, *mht_v_current = NULL, *mht_f_current = NULL; - struct timeb then; int msec; max_mm = MIN(MAX_ASYNCH_MM, MIN(mri_30->xsize, MIN(mri_30->ysize, mri_30->zsize)) / 2); @@ -814,7 +811,7 @@ int MRISpositionSurface_mef( if (IS_QUADRANGULAR(mris)) { MRISremoveTriangleLinks(mris); } - TimerStart(&then); + Timer then; // the following are used in mrisComputeIntensityError() and computeSSE() parms->mri_brain = NULL; // mri_30 ; parms->mri_smooth = NULL; // mri_5 ; @@ -976,7 +973,7 @@ int MRISpositionSurface_mef( parms->start_t = n; parms->dt = base_dt; if (Gdiag & DIAG_SHOW) { - msec = TimerStop(&then); + msec = then.milliseconds(); fprintf(stdout, "positioning took %2.1f minutes\n", (float)msec / (60 * 1000.0f)); } if (Gdiag & DIAG_WRITE) { @@ -4718,7 +4715,7 @@ MRI *MRISloadSurfVals(const char *srcvalfile, imag_val, curv, curvbak, fsmask, nc. Others can be easily added. If there is an error, a 1 is returned; otherwise 0. -----------------------------------------------------------------*/ -int MRIScopyMRI(MRIS *Surf, MRI *Src, int Frame, char *Field) +int MRIScopyMRI(MRIS *Surf, MRI *Src, int Frame, const char *Field) { int vtx, useval = 0, usecurv = 0, nvox, c, r, s; float val; @@ -4892,7 +4889,7 @@ int MRIScopyMRI(MRIS *Surf, MRI *Src, int Frame, char *Field) type will be MRI_FLOAT. A pointer to mri is returned. If an error occurs, NULL is returned. -----------------------------------------------------------------*/ -MRI *MRIcopyMRIS(MRI *mri, MRIS *surf, int Frame, char *Field) +MRI *MRIcopyMRIS(MRI *mri, MRIS *surf, int Frame, const char *Field) { int vtx, useval = 0, usecurv = 0, nvox, c, r, s; float val; @@ -5074,9 +5071,8 @@ MRI *MRISsmoothMRI(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *BinMask, MRI *Ta int nnbrs_actual; float val, m; MRI *SrcTmp; - struct timeb mytimer; int msecTime; - char *UFSS; + const char *UFSS; // Must explicity "setenv USE_FAST_SURF_SMOOTHER 0" to turn off fast UFSS = getenv("USE_FAST_SURF_SMOOTHER"); @@ -5121,11 +5117,11 @@ MRI *MRISsmoothMRI(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *BinMask, MRI *Ta } /*------------------------------------------------------------*/ - TimerStart(&mytimer); + Timer mytimer; SrcTmp = MRIcopy(Src, NULL); for (nthstep = 0; nthstep < nSmoothSteps; nthstep++) { if (Gdiag_no > 1) { - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); printf("Step = %d, tsec = %g\n", nthstep, msecTime / 1000.0); fflush(stdout); } @@ -5172,7 +5168,7 @@ MRI *MRISsmoothMRI(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *BinMask, MRI *Ta MRIcopy(Targ, SrcTmp); } /* end loop over smooth step */ - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); if (Gdiag_no > 0) { printf("Smoothing done, nsteps = %d, tsec = %g\n", nthstep, msecTime / 1000.0); } @@ -5200,7 +5196,6 @@ MRI *MRISsmoothMRIFast(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MRI { int nnbrs, nthstep, frame, vno, nthnbr, num, nvox, nbrvno, reshape; MRI *SrcTmp, *mritmp, *IncMaskTmp = NULL; - struct timeb mytimer; int msecTime; int *nNbrs, *nNbrs0, *rip, *rip0, nNbrsMax; float **pF, **pF0, *tF, *tF0, sumF; @@ -5257,7 +5252,7 @@ MRI *MRISsmoothMRIFast(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MRI rip0 = rip; nNbrs0 = nNbrs; - TimerStart(&mytimer); + Timer mytimer; // Loop through frames for (frame = 0; frame < Src->nframes; frame++) { @@ -5335,7 +5330,7 @@ MRI *MRISsmoothMRIFast(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MRI else Targ = MRIcopy(SrcTmp, Targ); - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); if (Gdiag_no > 0) { printf("MRISsmoothFast() nsteps = %d, tsec = %g\n", nSmoothSteps, msecTime / 1000.0); fflush(stdout); @@ -5362,7 +5357,6 @@ MRI *MRISsmoothMRIFastD(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MR { int nnbrs, nthstep, frame, vno, nthnbr, num, nvox, nbrvno, c, r, s; MRI *IncMaskTmp = NULL; - struct timeb mytimer; int msecTime; int *nNbrs, *nNbrs0, *rip, *rip0, nNbrsMax; double **pF, **pF0, *tF, *tF0, sumF; @@ -5418,7 +5412,7 @@ MRI *MRISsmoothMRIFastD(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MR nNbrs0 = nNbrs; pD0 = pD; - TimerStart(&mytimer); + Timer mytimer; // Loop through frames for (frame = 0; frame < Src->nframes; frame++) { @@ -5489,7 +5483,7 @@ MRI *MRISsmoothMRIFastD(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MR } /* end loop over frame */ - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); if (Gdiag_no > 0) { printf("MRISsmoothFastD() nsteps = %d, tsec = %g\n", nSmoothSteps, msecTime / 1000.0); fflush(stdout); @@ -5514,7 +5508,6 @@ MRI *MRISsmoothMRIFastD(MRIS *Surf, MRI *Src, int nSmoothSteps, MRI *IncMask, MR int MRISsmoothMRIFastFrame(MRIS *Surf, MRI *Src, int frame, int nSmoothSteps, MRI *IncMask) { int nnbrs, nthstep, vno, nthnbr, num, nvox, nbrvno; - struct timeb mytimer; int msecTime; float sumF; VERTEX *v, *vn; @@ -5563,7 +5556,7 @@ int MRISsmoothMRIFastFrame(MRIS *Surf, MRI *Src, int frame, int nSmoothSteps, MR exit(1); } - TimerStart(&mytimer); + Timer mytimer; // Set up pointers for this call pF = pF0; @@ -5627,7 +5620,7 @@ int MRISsmoothMRIFastFrame(MRIS *Surf, MRI *Src, int frame, int nSmoothSteps, MR } } - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); if (Gdiag_no > 0) { printf("MRISsmoothFast2() nsteps = %d, tsec = %g\n", nSmoothSteps, msecTime / 1000.0); fflush(stdout); diff --git a/utils/mrisurf_obsolete.c b/utils/mrisurf_obsolete.cpp similarity index 99% rename from utils/mrisurf_obsolete.c rename to utils/mrisurf_obsolete.cpp index aeb3d9073f8..c0f2ddd34c8 100644 --- a/utils/mrisurf_obsolete.c +++ b/utils/mrisurf_obsolete.cpp @@ -3372,7 +3372,7 @@ MRISunfoldOnSphere(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int max_passes) } /* first time through only - use big ratio to remove folds */ - TimerStart(&start) ; + start.reset() ; for (i = 0 ; i < NSCOEFS ; i++) { if (mris->nsize < parms->nbhd_size) /* resample distances on surface */ @@ -3420,7 +3420,7 @@ MRISunfoldOnSphere(MRI_SURFACE *mris, INTEGRATION_PARMS *parms, int max_passes) (starting_sse-ending_sse)/starting_sse) ; #endif } - msec = TimerStop(&start) ; + msec = start.milliseconds() ; if (Gdiag & DIAG_SHOW) { fprintf(stdout, diff --git a/utils/mrisurf_timeStep.c b/utils/mrisurf_timeStep.cpp similarity index 99% rename from utils/mrisurf_timeStep.c rename to utils/mrisurf_timeStep.cpp index 09bbf8db19c..99d70341027 100644 --- a/utils/mrisurf_timeStep.c +++ b/utils/mrisurf_timeStep.cpp @@ -57,13 +57,13 @@ static int MRISAsynchronousTimeStep_optionalDxDyDzUpdate_svi( float x, float y, float z) { const size_t numSubvolsPerEdge = MRISAsynchronousTimeStep_optionalDxDyDzUpdate_numSubvolsPerEdge; - int const svxLo = MIN(numSubvolsPerEdge-1,(int)((x - ctx->xSubvolVerge - ctx->xLo)/ctx->xSubvolLen)); - int const svyLo = MIN(numSubvolsPerEdge-1,(int)((y - ctx->ySubvolVerge - ctx->yLo)/ctx->ySubvolLen)); - int const svzLo = MIN(numSubvolsPerEdge-1,(int)((z - ctx->zSubvolVerge - ctx->zLo)/ctx->zSubvolLen)); + int const svxLo = MIN((int)numSubvolsPerEdge-1,(int)((x - ctx->xSubvolVerge - ctx->xLo)/ctx->xSubvolLen)); + int const svyLo = MIN((int)numSubvolsPerEdge-1,(int)((y - ctx->ySubvolVerge - ctx->yLo)/ctx->ySubvolLen)); + int const svzLo = MIN((int)numSubvolsPerEdge-1,(int)((z - ctx->zSubvolVerge - ctx->zLo)/ctx->zSubvolLen)); - int const svxHi = MIN(numSubvolsPerEdge-1,(int)((x + ctx->xSubvolVerge - ctx->xLo)/ctx->xSubvolLen)); - int const svyHi = MIN(numSubvolsPerEdge-1,(int)((y + ctx->ySubvolVerge - ctx->yLo)/ctx->ySubvolLen)); - int const svzHi = MIN(numSubvolsPerEdge-1,(int)((z + ctx->zSubvolVerge - ctx->zLo)/ctx->zSubvolLen)); + int const svxHi = MIN((int)numSubvolsPerEdge-1,(int)((x + ctx->xSubvolVerge - ctx->xLo)/ctx->xSubvolLen)); + int const svyHi = MIN((int)numSubvolsPerEdge-1,(int)((y + ctx->ySubvolVerge - ctx->yLo)/ctx->ySubvolLen)); + int const svzHi = MIN((int)numSubvolsPerEdge-1,(int)((z + ctx->zSubvolVerge - ctx->zLo)/ctx->zSubvolLen)); if (svxLo != svxHi || svyLo != svyHi || svzLo != svzHi) return MRISAsynchronousTimeStep_optionalDxDyDzUpdate_numSubvolsPerThread - 1; // the svi for any items not deep inside a subvolume @@ -716,16 +716,14 @@ static void mrisAsynchronousTimeStep_optionalDxDyDzUpdate( // BEVIN mris_make_su // so sort each subvols list... // { int * temp = (int*)malloc(sizeof(int)*mris->nvertices); - - int svi; - for (svi = 0; svi < numSubvolsPerThread; svi++) { + + for (unsigned int svi = 0; svi < numSubvolsPerThread; svi++) { // build the list in the temp // int tempSize = 0; - - int tid; - for (tid = 0; tid < numThreads; tid++) { + + for (unsigned int tid = 0; tid < numThreads; tid++) { SubvolInfo* subvol = subvols + tid*numSubvolsPerThread + svi; int vno = subvol->firstVnoPlus1 - 1; while (vno >= 0) { @@ -2055,7 +2053,7 @@ int MRISexpandSurface(MRI_SURFACE *mris, float distance, INTEGRATION_PARMS *parm int vno, n, niter, avgs, nrounds, surf_no, orig_start_t = parms->start_t; VERTEX *v; double dist, dx = 0., dy = 0., dz = 0.0, dtotal, *pial_x, *pial_y, *pial_z, l_spring_orig; - char fname[STRLEN], *hemi, *cp; + char fname[STRLEN], *cp; INTEGRATION_PARMS thick_parms; MRI_SURFACE *mris_ico; MHT *mht = NULL; @@ -2074,7 +2072,7 @@ int MRISexpandSurface(MRI_SURFACE *mris, float distance, INTEGRATION_PARMS *parm pial_y = (double *)calloc(mris->nvertices, sizeof(double)); pial_z = (double *)calloc(mris->nvertices, sizeof(double)); - hemi = mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh"; + const char *hemi = mris->hemisphere == LEFT_HEMISPHERE ? "lh" : "rh"; if (pial_x == NULL || pial_y == NULL || pial_z == NULL) { ErrorExit(ERROR_NOMEMORY, "MRISexpandSurface: could not allocaet %d element vertex array", mris->nvertices); diff --git a/utils/mrisurf_topology.c b/utils/mrisurf_topology.cpp similarity index 99% rename from utils/mrisurf_topology.c rename to utils/mrisurf_topology.cpp index 0b8fba213de..37066bc3df4 100644 --- a/utils/mrisurf_topology.c +++ b/utils/mrisurf_topology.cpp @@ -224,8 +224,7 @@ void MRIScheckIsPolyhedron(MRIS *mris, const char* file, int line) { } else { Edges const * const edgesForVno2 = &edges[vno2]; int count = 0; - int i; - for (i = 0; i < edgesForVno2->hiVnosCount; i++) { + for (unsigned int i = 0; i < edgesForVno2->hiVnosCount; i++) { if (hiVnos[edgesForVno2->hiVnosBegin + i] == vno) count++; } cheapAssert(count == 1); // each should be entered exactly once @@ -260,8 +259,7 @@ void MRIScheckIsPolyhedron(MRIS *mris, const char* file, int line) { int vno2 = face->v[n2]; if (vno1 > vno2) { vno1 = vno2; vno2 = face->v[n1]; } else cheapAssert(vno1 != vno2); Edges const * const edgesForVno = &edges[vno1]; - int i; - for (i = 0; i < edgesForVno->hiVnosCount; i++) { + for (unsigned int i = 0; i < edgesForVno->hiVnosCount; i++) { if (hiVnos [edgesForVno->hiVnosBegin + i] != vno2) continue; // found the entry for an edge if (!badCount) { @@ -283,9 +281,8 @@ void MRIScheckIsPolyhedron(MRIS *mris, const char* file, int line) { cheapAssert(!reportsNot1); if (badCount) break; - - int edgeNo; - for (edgeNo = 0; edgeNo < hiVnosSize; edgeNo++) { + + for (unsigned int edgeNo = 0; edgeNo < hiVnosSize; edgeNo++) { int count = nFacesPerEdge[edgeNo]; if (count == 2) continue; if (count < 2 && tearsOk) continue; @@ -918,14 +915,13 @@ void MRIS_VertexNeighbourInfo_check( MRIS_VertexNeighbourInfo* rhs) { cheapAssert(lhs->hops == rhs->hops); - - int i; - for (i = 0; i <= lhs->hops; i++) + + for (unsigned int i = 0; i <= lhs->hops; i++) cheapAssert(lhs->vnum[i] == rhs->vnum[i]); // Even test the algorithms put them in the same order! // - for (i = 0; i < lhs->vnum[lhs->hops]; i++) + for (int i = 0; i < lhs->vnum[lhs->hops]; i++) cheapAssert(lhs->v[i] == rhs->v[i]); } @@ -946,8 +942,7 @@ void MRIS_VertexNeighbourInfo_load_from_VERTEX (MRIS_VertexNeighbourInfo* info, void MRIS_VertexNeighbourInfo_load_from_vlist (MRIS_VertexNeighbourInfo* info, MRIS* mris, int vno, size_t listSize, int* vlist, int* hops) { info->vnum[0] = 1; - int i; - for (i = 0; i < listSize; i++) { + for (unsigned int i = 0; i < listSize; i++) { info->v[i] = vlist[i]; info->hops = hops[i]; cheapAssert(info->hops >= 0); @@ -1059,7 +1054,8 @@ void MRIS_check_vertexNeighbours(MRIS* mris) { } if (!doTesting) return; - MRIS_VertexNeighbourInfo info0,info1; + MRIS_VertexNeighbourInfo info0 = MRIS_VertexNeighbourInfo(); + MRIS_VertexNeighbourInfo info1 = MRIS_VertexNeighbourInfo(); int vlist[MAX_NEIGHBORS], hops[MAX_NEIGHBORS]; int vno; @@ -1109,7 +1105,7 @@ static int MRISfindNeighborsAtVertex_new(MRIS *mris, int vno, int nlinks, size_t static Temp tempForEachThread[_MAX_FS_THREADS]; Temp* const temp = &tempForEachThread[omp_get_thread_num()]; - if (temp->capacity < mris->nvertices) { + if (temp->capacity < (unsigned)mris->nvertices) { temp->capacity = mris->nvertices; temp->status = (unsigned char*)realloc(temp->status, temp->capacity*sizeof(unsigned char)); bzero(temp->status, temp->capacity*sizeof(unsigned char)); @@ -1141,7 +1137,7 @@ static int MRISfindNeighborsAtVertex_new(MRIS *mris, int vno, int nlinks, size_t // Add the known rings // - int neighborCount = 0; + unsigned int neighborCount = 0; cheapAssert(vt->nsizeMax > 0); @@ -1258,8 +1254,7 @@ static int MRISfindNeighborsAtVertex_new(MRIS *mris, int vno, int nlinks, size_t // Clear the temp for reuse later // temp->status[vno] = Status_notInSet; - int i; - for (i = 0; i < neighborCount; i++) { + for (unsigned int i = 0; i < neighborCount; i++) { temp->status[vlist[i]] = Status_notInSet; } @@ -1922,7 +1917,7 @@ short VERTICES_commonInFaces_find(FACE *apFACE_I, FACE *apFACE_J, VECTOR *apv_ve int i = 0; int j = 0; int k = 0; - char *pch_function = "VERTICES_commonInFaces_find"; + const char *pch_function = "VERTICES_commonInFaces_find"; short b_hit = 0; float f_val = -1.; @@ -3054,7 +3049,7 @@ static short FACES_aroundVertex_reorder(MRIS *apmris, int avertex, VECTOR *pv_ge // o The number of connected faces is returned in the function name, or // 0 is there is some error. - char *pch_function = "FACES_aroundVertex_reorder"; + const char *pch_function = "FACES_aroundVertex_reorder"; int nfaces = 0; int *pFaceIndex = NULL; int packedCount = 1; diff --git a/utils/mrisurf_vals.c b/utils/mrisurf_vals.cpp similarity index 100% rename from utils/mrisurf_vals.c rename to utils/mrisurf_vals.cpp diff --git a/utils/mrisutils.c b/utils/mrisutils.cpp similarity index 99% rename from utils/mrisutils.c rename to utils/mrisutils.cpp index ce5edbdd503..c5b5f079b72 100644 --- a/utils/mrisutils.c +++ b/utils/mrisutils.cpp @@ -812,10 +812,10 @@ MRIS *MRISmatchSurfaceToLabel( double tol; MHT *mht = NULL; int avgs = AVERAGES_NBR; - struct timeb then; + Timer then; int msec; - TimerStart(&then); + then.reset(); if (integration_parms == NULL) { parms = (INTEGRATION_PARMS *)calloc(1, sizeof(INTEGRATION_PARMS)); @@ -958,7 +958,7 @@ MRIS *MRISmatchSurfaceToLabel( last_rms); } - msec = TimerStop(&then); + msec = then.milliseconds(); if (1) // Gdiag & DIAG_SHOW) fprintf(stdout, "positioning took %2.2f minutes\n", (float)msec / (60 * 1000.0f)); @@ -2104,14 +2104,15 @@ MRI *MRIScomputeFlattenedVolume(MRI_SURFACE *mris, */ MRI_SP *MRISmakeTemplate(int nsubjects, char **subjlist, int nhemis, char **hemilist, char *surfregname) { - static char *surface_names[] = {"inflated", "smoothwm", "smoothwm"}; - static char *curvature_names[] = {"inflated.H", "sulc", NULL}; + static const char *surface_names[] = {"inflated", "smoothwm", "smoothwm"}; + static const char *curvature_names[] = {"inflated.H", "sulc", NULL}; char tmpstr[2000]; int images_per_surface = 3; int nsurfaces = sizeof(curvature_names) / sizeof(curvature_names[0]); int nparam_images = images_per_surface * nsurfaces; float scale = 1; - char *annot_name = "aparc", *SUBJECTS_DIR, *hemi, *subject; + const char *annot_name = "aparc"; + char *SUBJECTS_DIR, *hemi, *subject; INTEGRATION_PARMS parms; int which_norm = NORM_MEAN; int navgs = 0, nthhemi, sno, nthsubject; @@ -2839,7 +2840,7 @@ int L2Sinit(LABEL2SURF *l2s) alloc the surfaces. subject can be null (this info is just passed to the labels). */ -LABEL2SURF *L2Salloc(int nsurfs, char *subject) +LABEL2SURF *L2Salloc(int nsurfs, const char *subject) { int n; LABEL2SURF *l2s; @@ -2953,7 +2954,7 @@ int L2SimportLabel(LABEL2SURF *l2s, LABEL *label, int surfno) because surf vg not set. Returns 0 if all tests passed or 1 if any test failed. */ -int L2Stest(char *subject) +int L2Stest(const char *subject) { char *SUBJECTS_DIR, tmpstr[2000]; SUBJECTS_DIR = getenv("SUBJECTS_DIR"); diff --git a/utils/mrivoxel.c b/utils/mrivoxel.cpp similarity index 99% rename from utils/mrivoxel.c rename to utils/mrivoxel.cpp index 7bcd2530979..3915eb35882 100644 --- a/utils/mrivoxel.c +++ b/utils/mrivoxel.cpp @@ -34,7 +34,7 @@ #include "diag.h" #include "error.h" #include "macros.h" -#include "minc_volume_io.h" +#include "minc.h" #include "mri.h" #include "proto.h" diff --git a/utils/numerics.cpp b/utils/numerics.cpp index 50da8901c78..5874e294403 100644 --- a/utils/numerics.cpp +++ b/utils/numerics.cpp @@ -53,12 +53,10 @@ #include "fs_vnl/fs_lbfgs.h" #include "fs_vnl/fs_powell.h" -extern "C" { #include "cephes.h" #include "diag.h" #include "error.h" #include "numerics.h" -} // used for calculating the incomplete beta function static double d_huge(); @@ -464,7 +462,7 @@ static double beta(double x, double y) * @param x Argument of the function. Normally, 0.0 <= x <= 1.0. * @return Value of the function. */ -extern "C" float OpenBetaIncomplete(float a, float b, float x) +float OpenBetaIncomplete(float a, float b, float x) { double cx; int i; @@ -716,7 +714,7 @@ double normal_01_cdf(double x) * GAMMA_INC is returned as 0. * @return The value of the function. */ -extern "C" float OpenGammaIncomplete(float p, float x) +float OpenGammaIncomplete(float p, float x) { double a; double arg; @@ -850,7 +848,7 @@ extern "C" float OpenGammaIncomplete(float p, float x) return value; } -extern "C" int OpenDFPMin(float p[], +int OpenDFPMin(float p[], int n, float iTolerance, int *oIterations, @@ -934,7 +932,7 @@ extern "C" int OpenDFPMin(float p[], /** * Provides the eigen values and vectors for symmetric matrices. */ -extern "C" int OpenEigenSystem(float *iaData, int icData, float *oEigenValues, float *oEigenVectors) +int OpenEigenSystem(float *iaData, int icData, float *oEigenValues, float *oEigenVectors) { vnl_matrix< float > vnlMatrix(iaData, icData, icData); @@ -952,7 +950,7 @@ extern "C" int OpenEigenSystem(float *iaData, int icData, float *oEigenValues, f /** * Provides the eigen values and vectors for symmetric matrices. */ -extern "C" int OpenNonSymmetricEigenSystem(float *iaData, int icData, float *oEigenValues, float *oEigenVectors) +int OpenNonSymmetricEigenSystem(float *iaData, int icData, float *oEigenValues, float *oEigenVectors) { // convert the data into a double double data[icData * icData]; @@ -984,7 +982,7 @@ extern "C" int OpenNonSymmetricEigenSystem(float *iaData, int icData, float *oEi return NO_ERROR; } -extern "C" void OpenPowell(float iaParams[], +void OpenPowell(float iaParams[], float **ioInitialDirection, int icParams, float iTolerance, @@ -1041,7 +1039,7 @@ extern "C" void OpenPowell(float iaParams[], It would be better to have more options on this function. Note: each "iteration" is a loop thru a 1D min for each parameter. ------------------------------------------------------------------------*/ -extern "C" int OpenPowell2(float iaParams[], +int OpenPowell2(float iaParams[], float **ioInitialDirection, int icParams, float iTolerance, @@ -1095,7 +1093,7 @@ extern "C" int OpenPowell2(float iaParams[], return (0); } -extern "C" int OpenLUMatrixInverse(MATRIX *iMatrix, MATRIX *oInverse) +int OpenLUMatrixInverse(MATRIX *iMatrix, MATRIX *oInverse) { // NO_ERROR from error.h int errorCode = NO_ERROR; @@ -1157,7 +1155,7 @@ extern "C" int OpenLUMatrixInverse(MATRIX *iMatrix, MATRIX *oInverse) * @param iMatrix * @return Returns 0 if the matrix is non-square. */ -extern "C" float OpenMatrixDeterminant(MATRIX *iMatrix) +float OpenMatrixDeterminant(MATRIX *iMatrix) { float determinant = 0.0; @@ -1184,7 +1182,7 @@ extern "C" float OpenMatrixDeterminant(MATRIX *iMatrix) * @param oW Ouput diagonal vector. * @param oV Ouput V matrix. */ -extern "C" int OpenSvdcmp(MATRIX *ioA, VECTOR *oW, MATRIX *oV) +int OpenSvdcmp(MATRIX *ioA, VECTOR *oW, MATRIX *oV) { int errorCode = NO_ERROR; @@ -1215,7 +1213,7 @@ extern "C" int OpenSvdcmp(MATRIX *ioA, VECTOR *oW, MATRIX *oV) * different seed. The behaviour of this function is meant to mimic that of * the ran1 algorithm in numerical recipes. */ -extern "C" float OpenRan1(long *iSeed) +float OpenRan1(long *iSeed) { #ifdef HAVE_OPENMP @@ -1246,7 +1244,7 @@ extern "C" float OpenRan1(long *iSeed) * @param iYStartDerivative The derivative at the beginning of the function. * @param iYEndDerivative The derivative at the last point of the function. */ -extern "C" void OpenSpline( +void OpenSpline( float iaX[], float iaY[], int icXY, float iYStartDerivative, float iYEndDerivative, float oaYSecondDerivatives[]) { float *secondDerivatives = SplineCubicSet( @@ -1264,7 +1262,7 @@ extern "C" void OpenSpline( * interpolated as the closest edge point, rather than the usual extrapolated * point. */ -extern "C" void OpenSplint( +void OpenSplint( float iaX[], float iaY[], float iaYSecondDerivatives[], int icYSecondDerivatives, float iX, float *oY) { float firstDerivative = 0.0; @@ -1644,7 +1642,7 @@ float *d3_np_fs(int n, float a[], float b[]) #define NR_END 1 #define FREE_ARG char * -extern "C" float *vector(long nl, long nh) +float *vector(long nl, long nh) /* allocate a float vector with subscript range v[nl..nh] */ { float *v; @@ -1654,7 +1652,7 @@ extern "C" float *vector(long nl, long nh) return v - nl + NR_END; } -extern "C" float **matrix(long nrl, long nrh, long ncl, long nch) +float **matrix(long nrl, long nrh, long ncl, long nch) /* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */ { long i, nrow = nrh - nrl + 1, ncol = nch - ncl + 1; @@ -1678,7 +1676,7 @@ extern "C" float **matrix(long nrl, long nrh, long ncl, long nch) return m; } -extern "C" void free_vector(float *v, long nl, long nh) +void free_vector(float *v, long nl, long nh) /* free a float vector allocated with vector() */ { free((FREE_ARG)(v + nl - NR_END)); } void free_matrix(float **m, long nrl, long nrh, long ncl, long nch) @@ -1792,7 +1790,7 @@ vnl_matrix_fixed< double, 4, 4 > MatrixSqrt(const vnl_matrix_fixed< double, 4, 4 return msqrt; } -extern "C" MATRIX *MatrixSqrt(MATRIX *m, MATRIX *sqrtm) +MATRIX *MatrixSqrt(MATRIX *m, MATRIX *sqrtm) { int i, j; vnl_matrix_fixed< double, 4, 4 > vnl_m; @@ -1828,9 +1826,6 @@ extern "C" MATRIX *MatrixSqrt(MATRIX *m, MATRIX *sqrtm) */ //##################### FUNC PROTOS ###################################### -#ifdef __cplusplus -extern "C" { -#endif static const unsigned long int SC_MASK_LO = 0x00ffffffUL; /*2^24 - 1 */ static const unsigned long int SC_MASK_HI = ~0x00ffffffUL; @@ -1846,10 +1841,6 @@ double sc_gamma_large(const sc_rng *r, const double a); double sc_gamma_int(const sc_rng *r, const unsigned int a); double sc_ugauss(const sc_rng *r); -#ifdef __cplusplus -} -#endif - //##################### FUNCTIONS ####################################### //########### VNL ################################################### @@ -1862,7 +1853,7 @@ double sc_ugauss(const sc_rng *r); Returns 0 on success and nonzero otherwise (eg, when U is non-positive def). */ -extern "C" int sc_linalg_cholesky_decomp(MATRIX *U) +int sc_linalg_cholesky_decomp(MATRIX *U) { int i, j, err; @@ -1894,7 +1885,7 @@ static void sc_err_msg(const char *msg) //########################## RNG ############################### -extern "C" unsigned long int sc_inc_status(sc_status_t *status) +unsigned long int sc_inc_status(sc_status_t *status) { int i, j; long int step; @@ -1931,7 +1922,7 @@ extern "C" unsigned long int sc_inc_status(sc_status_t *status) return (step); } -extern "C" unsigned long int sc_rng_get(const sc_rng *r) +unsigned long int sc_rng_get(const sc_rng *r) { sc_status_t *status; int i, skip; @@ -1950,7 +1941,7 @@ extern "C" unsigned long int sc_rng_get(const sc_rng *r) return (ret); } -extern "C" void sc_rng_set(sc_rng *r, unsigned long int seed_in) +void sc_rng_set(sc_rng *r, unsigned long int seed_in) { int const_lux; sc_status_t *status; @@ -1992,7 +1983,7 @@ extern "C" void sc_rng_set(sc_rng *r, unsigned long int seed_in) return; } -extern "C" sc_rng *sc_rng_alloc(const sc_rng_type *T) +sc_rng *sc_rng_alloc(const sc_rng_type *T) { sc_rng *r; @@ -2009,7 +2000,7 @@ extern "C" sc_rng *sc_rng_alloc(const sc_rng_type *T) return (r); } -extern "C" void sc_rng_free(sc_rng *r) +void sc_rng_free(sc_rng *r) { if (r->status != NULL) free(r->status); @@ -2018,7 +2009,7 @@ extern "C" void sc_rng_free(sc_rng *r) return; } -extern "C" double sc_uni(const sc_rng *r) +double sc_uni(const sc_rng *r) { double u; @@ -2027,7 +2018,7 @@ extern "C" double sc_uni(const sc_rng *r) return (u); } -extern "C" double sc_uni_pos(const sc_rng *r) +double sc_uni_pos(const sc_rng *r) { double x; do { @@ -2039,7 +2030,7 @@ extern "C" double sc_uni_pos(const sc_rng *r) //##################### RAN ### -extern "C" double sc_ran_flat(const sc_rng *r, const double a, const double b) +double sc_ran_flat(const sc_rng *r, const double a, const double b) { double u, ret; @@ -2048,7 +2039,7 @@ extern "C" double sc_ran_flat(const sc_rng *r, const double a, const double b) return (ret); } -extern "C" double sc_ran_gaussian(const sc_rng *r, const double sigma) +double sc_ran_gaussian(const sc_rng *r, const double sigma) { double x, y, r2, ret; @@ -2062,7 +2053,7 @@ extern "C" double sc_ran_gaussian(const sc_rng *r, const double sigma) return (ret); } -extern "C" double sc_ugauss(const sc_rng *r) +double sc_ugauss(const sc_rng *r) { double ret; @@ -2071,7 +2062,7 @@ extern "C" double sc_ugauss(const sc_rng *r) return (ret); } -extern "C" double sc_gamma_int(const sc_rng *r, const unsigned int a) +double sc_gamma_int(const sc_rng *r, const unsigned int a) { unsigned int i; double prod, ret; @@ -2090,7 +2081,7 @@ extern "C" double sc_gamma_int(const sc_rng *r, const unsigned int a) } } -extern "C" double sc_gamma_large(const sc_rng *r, const double a) +double sc_gamma_large(const sc_rng *r, const double a) { double sqa, y, v, ret; @@ -2106,7 +2097,7 @@ extern "C" double sc_gamma_large(const sc_rng *r, const double a) return (ret); } -extern "C" double sc_gamma_frac(const sc_rng *r, const double a) +double sc_gamma_frac(const sc_rng *r, const double a) { double p, q, u, v, ret; p = M_E / (a + M_E); @@ -2127,7 +2118,7 @@ extern "C" double sc_gamma_frac(const sc_rng *r, const double a) return (ret); } -extern "C" double sc_ran_gamma(const sc_rng *r, const double a, const double b) +double sc_ran_gamma(const sc_rng *r, const double a, const double b) { unsigned int na; double ret; @@ -2147,7 +2138,7 @@ extern "C" double sc_ran_gamma(const sc_rng *r, const double a, const double b) } } -extern "C" double sc_ran_fdist(const sc_rng *r, const double nu1, const double nu2) +double sc_ran_fdist(const sc_rng *r, const double nu1, const double nu2) { double Y1, Y2, ret; @@ -2158,7 +2149,7 @@ extern "C" double sc_ran_fdist(const sc_rng *r, const double nu1, const double n return (ret); } -extern "C" double sc_ran_chisq(const sc_rng *r, const double nu) +double sc_ran_chisq(const sc_rng *r, const double nu) { double ret; @@ -2166,7 +2157,7 @@ extern "C" double sc_ran_chisq(const sc_rng *r, const double nu) return (ret); } -extern "C" double sc_ran_tdist(const sc_rng *r, const double nu) +double sc_ran_tdist(const sc_rng *r, const double nu) { double Y1, Y2, Z, ret; @@ -2188,7 +2179,7 @@ extern "C" double sc_ran_tdist(const sc_rng *r, const double nu) } } -extern "C" double sc_ran_exponential(const sc_rng *r, const double mu) +double sc_ran_exponential(const sc_rng *r, const double mu) { double u, ret; @@ -2198,7 +2189,7 @@ extern "C" double sc_ran_exponential(const sc_rng *r, const double mu) return (ret); } -extern "C" double sc_ran_binomial_pdf(unsigned int k, double p, unsigned int n) +double sc_ran_binomial_pdf(unsigned int k, double p, unsigned int n) { double ret; @@ -2214,7 +2205,7 @@ extern "C" double sc_ran_binomial_pdf(unsigned int k, double p, unsigned int n) //##################### CDF ### -extern "C" double sc_cdf_flat_Q(double x, double a, double b) +double sc_cdf_flat_Q(double x, double a, double b) { double ret = 0.0; @@ -2225,7 +2216,7 @@ extern "C" double sc_cdf_flat_Q(double x, double a, double b) return (1.0 - ret); } -extern "C" double sc_cdf_flat_Qinv(double Q, double a, double b) +double sc_cdf_flat_Qinv(double Q, double a, double b) { double ret = 0.0; @@ -2238,7 +2229,7 @@ extern "C" double sc_cdf_flat_Qinv(double Q, double a, double b) return (ret); } -extern "C" double sc_cdf_fdist_Q(double x, double nu1, double nu2) +double sc_cdf_fdist_Q(double x, double nu1, double nu2) { double ret = 0.0; @@ -2247,7 +2238,7 @@ extern "C" double sc_cdf_fdist_Q(double x, double nu1, double nu2) return (ret); } -extern "C" double sc_cdf_fdist_Qinv(double Q, double nu1, double nu2) +double sc_cdf_fdist_Qinv(double Q, double nu1, double nu2) { double ret = 0.0; @@ -2256,7 +2247,7 @@ extern "C" double sc_cdf_fdist_Qinv(double Q, double nu1, double nu2) return (ret); } -extern "C" double sc_cdf_tdist_Q(double x, double nu) +double sc_cdf_tdist_Q(double x, double nu) { double ret = 0.0; @@ -2265,7 +2256,7 @@ extern "C" double sc_cdf_tdist_Q(double x, double nu) return (ret); } -extern "C" double sc_cdf_tdist_Qinv(double Q, double nu) +double sc_cdf_tdist_Qinv(double Q, double nu) { double ret = 0.0; @@ -2274,7 +2265,7 @@ extern "C" double sc_cdf_tdist_Qinv(double Q, double nu) return (ret); } -extern "C" double sc_cdf_gaussian_Q(double x, double nu) +double sc_cdf_gaussian_Q(double x, double nu) { double ret = 0.0; @@ -2288,7 +2279,7 @@ extern "C" double sc_cdf_gaussian_Q(double x, double nu) return (ret); } -extern "C" double sc_cdf_gaussian_Qinv(double Q, double nu) +double sc_cdf_gaussian_Qinv(double Q, double nu) { double ret = 0.0; @@ -2302,7 +2293,7 @@ extern "C" double sc_cdf_gaussian_Qinv(double Q, double nu) return (ret); } -extern "C" double sc_cdf_chisq_Q(double x, double nu) +double sc_cdf_chisq_Q(double x, double nu) { double ret = 0.0; @@ -2311,7 +2302,7 @@ extern "C" double sc_cdf_chisq_Q(double x, double nu) return (ret); } -extern "C" double sc_cdf_chisq_Qinv(double Q, double nu) +double sc_cdf_chisq_Qinv(double Q, double nu) { double ret = 0.0; diff --git a/utils/offset.c b/utils/offset.cpp similarity index 99% rename from utils/offset.c rename to utils/offset.cpp index 0b5e09c272b..008d0e0a8a8 100644 --- a/utils/offset.c +++ b/utils/offset.cpp @@ -37,7 +37,6 @@ /*----------------------------------------------------- INCLUDE FILES -------------------------------------------------------*/ -#include #include #include #include @@ -73,18 +72,18 @@ IMAGE *ImageCalculateOffset(IMAGE *Ix, IMAGE *Iy, int wsize, IMAGE *Ioffset) { static IMAGE *Iorient = NULL, *Idir = NULL; - struct timeb then; + Timer then; int msec; - if (Gdiag & DIAG_TIMER) TimerStart(&then); + if (Gdiag & DIAG_TIMER) then.reset(); Iorient = ImageOffsetOrientation(Ix, Iy, wsize, Iorient); if ((Gdiag & DIAG_WRITE) && (Gdiag & DIAG_VERBOSE)) ImageWrite(Iorient, "orient.hipl"); if (Gdiag & DIAG_TIMER) { - msec = TimerStop(&then); + msec = then.milliseconds(); fprintf(stderr, "orientation took %2.3f sec\n", (float)msec / 1000.0f); - TimerStart(&then); + then.reset(); } Idir = ImageOffsetDirection(Ix, Iy, wsize, Iorient, Idir); @@ -92,7 +91,7 @@ IMAGE *ImageCalculateOffset(IMAGE *Ix, IMAGE *Iy, int wsize, IMAGE *Ioffset) if ((Gdiag & DIAG_WRITE) && (Gdiag & DIAG_VERBOSE)) ImageWrite(Idir, "dir.hipl"); if (Gdiag & DIAG_TIMER) { - msec = TimerStop(&then); + msec = then.milliseconds(); fprintf(stderr, "direction took %2.3f sec\n", (float)msec / 1000.0f); } diff --git a/utils/path.c b/utils/path.cpp similarity index 99% rename from utils/path.c rename to utils/path.cpp index 71079bc1000..ff21e6bef1a 100644 --- a/utils/path.c +++ b/utils/path.cpp @@ -23,7 +23,6 @@ * */ -#define _GNU_SOURCE #include #include #include diff --git a/utils/pdf.c b/utils/pdf.cpp similarity index 100% rename from utils/pdf.c rename to utils/pdf.cpp diff --git a/utils/pgmstubs.c b/utils/pgmstubs.cpp similarity index 100% rename from utils/pgmstubs.c rename to utils/pgmstubs.cpp diff --git a/utilscpp/pointset.cpp b/utils/pointset.cpp similarity index 91% rename from utilscpp/pointset.cpp rename to utils/pointset.cpp index 92ca4aa9de2..18c47bef0f1 100644 --- a/utilscpp/pointset.cpp +++ b/utils/pointset.cpp @@ -1,11 +1,11 @@ #include -#include "pointset.hpp" +#include "pointset.h" /// Writes pointset to a JSON file -/// todo\ support the .dat output format as well and -/// use json.hpp instead of hard-coding this stuff +/// TODO: support the .dat output format as well and +/// use json.h instead of hard-coding this stuff bool PointSet::save(std::string filename) { diff --git a/utils/prime.c b/utils/prime.cpp similarity index 100% rename from utils/prime.c rename to utils/prime.cpp diff --git a/utils/queue.c b/utils/queue.c deleted file mode 100644 index 7cb5c5d29cb..00000000000 --- a/utils/queue.c +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @file queue.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:54 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/* - @(#)queue.c 1.3 - 3/15/94 -*/ -/*------------------------------------------------------------------------ - File Name: queue.c - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: - -------------------------------------------------------------------------*/ -/*------------------------------------------------------------------------ - HEADERS -------------------------------------------------------------------------*/ - -#include -#include - -#include "queue.h" -#include "thread.h" - -/*------------------------------------------------------------------------ - CONSTANTS -------------------------------------------------------------------------*/ - -/*------------------------------------------------------------------------ - STATIC DATA -------------------------------------------------------------------------*/ - -/*------------------------------------------------------------------------ - STATIC PROTOTYPES -------------------------------------------------------------------------*/ - -/*------------------------------------------------------------------------ - FUNCTIONS -------------------------------------------------------------------------*/ -/*------------------------------------------------------------------------ - Parameters: - - Description: - - Return Values: - nothing. -------------------------------------------------------------------------*/ -QUEUE *Qalloc(int max_elts) -{ - QUEUE *q; - // int i = max_elts; - - q = (QUEUE *)calloc(1, sizeof(QUEUE)); - - // i = max_elts + 1; - return (q); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - - Return Values: - nothing. -------------------------------------------------------------------------*/ -void Qfree(QUEUE *q) -{ - QELT *qelt; - - for (qelt = Qget(q, 0); qelt; qelt = Qget(q, 0)) free(qelt); - - free(q); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - - Return Values: - nothing. -------------------------------------------------------------------------*/ -int Qput(QUEUE *q, void *data) -{ - QELT *qelt; - - qelt = (QELT *)calloc(1, sizeof(QELT)); - if (!qelt) return (-1); - - qelt->data = data; - - if (!q->head) /* empty list */ - { - q->head = q->tail = qelt; - qelt->next = qelt->prev = NULL; /* just to be explicit */ - } - else /* link in at end of list */ - { - qelt->next = NULL; - qelt->prev = q->tail; - q->tail->next = qelt; - q->tail = qelt; - } - - q->nelts++; - return (0); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - - Return Values: - nothing. -------------------------------------------------------------------------*/ -void *Qget(QUEUE *q, int mode) -{ - QELT *qelt; - void *data; - - if (!q->head) { - if (mode == Q_DONT_WAIT) - return (NULL); - else - ThreadSuspend(TID_SELF, 0); - - if (!q->head) /* somebody woke me up and nothing was there */ - return (NULL); - } - - qelt = q->head; - q->head = qelt->next; - if (!q->head) - q->tail = NULL; /* empty list */ - else - q->head->prev = NULL; /* head of list now */ - - q->nelts--; - data = qelt->data; - free(qelt); - - return (data); -} diff --git a/utils/randomfields.c b/utils/randomfields.cpp similarity index 100% rename from utils/randomfields.c rename to utils/randomfields.cpp diff --git a/utils/rbf.c b/utils/rbf.cpp similarity index 95% rename from utils/rbf.c rename to utils/rbf.cpp index 8e8d033692b..499a4c18ad6 100644 --- a/utils/rbf.c +++ b/utils/rbf.cpp @@ -124,7 +124,7 @@ static int rbfAllocateTrainingParameters(RBF *rbf); Description allocate and initialize an rbf classifier. ------------------------------------------------------*/ -RBF *RBFinit(int ninputs, int noutputs, int max_clusters[], char *names[]) +RBF *RBFinit(int ninputs, int noutputs, int max_clusters[], const char *names[]) { RBF *rbf; int i; @@ -197,7 +197,7 @@ int RBFtrain(RBF *rbf, void *parm, float momentum) { - int i, class, c, cno; + int i, classnum, c, cno; CLUSTERING_PARM cp; CLUSTER_SET *cs; @@ -234,8 +234,8 @@ int RBFtrain(RBF *rbf, } /* fill in cluster pointers in rbf struct for convenience sake */ - for (cno = class = 0; class < rbf->noutputs; class ++) { - cs = rbf->cs[class]; + for (cno = classnum = 0; classnum < rbf->noutputs; classnum ++) { + cs = rbf->cs[classnum]; if (cs) for (c = 0; c < cs->nclusters; c++, cno++) rbf->clusters[cno] = cs->clusters + c; } @@ -499,7 +499,7 @@ static int rbfShowClusterCenters(RBF *rbf, FILE *fp) for (i = 0; i < rbf->noutputs; i++) { cs = rbf->cs[i]; if (!cs) continue; - fprintf(fp, "class %s:\n", rbf->class_names[i]); + fprintf(fp, "classnum %s:\n", rbf->class_names[i]); for (c = 0; c < cs->nclusters; c++) { cluster = cs->clusters + c; fprintf(fp, "cluster %d has %d observations. Center:", c, cluster->nsamples); @@ -559,13 +559,13 @@ static float rbfGaussian(MATRIX *m_sigma_inverse, VECTOR *v_means, VECTOR *v_obs inverse covariance matrix m_sigma_inverse given the input v_obs. ------------------------------------------------------*/ -float RBFcomputeErrors(RBF *rbf, int class, VECTOR *v_error) +float RBFcomputeErrors(RBF *rbf, int classnum, VECTOR *v_error) { int i; float target, error, total_error; for (total_error = 0.0f, i = 1; i <= rbf->noutputs; i++) { - if (class == (i - 1)) + if (classnum == (i - 1)) target = 1.0f; else target = 0.0f; @@ -617,7 +617,7 @@ static int rbfAdjustOutputWeights(RBF *rbf, VECTOR *v_error) Description Print the RBF activations to a file for debugging. ------------------------------------------------------*/ -int RBFprintActivations(RBF *rbf, VECTOR *v_obs, VECTOR *v_error, int class, FILE *fp) +int RBFprintActivations(RBF *rbf, VECTOR *v_obs, VECTOR *v_error, int classnum, FILE *fp) { int i; @@ -630,8 +630,8 @@ int RBFprintActivations(RBF *rbf, VECTOR *v_obs, VECTOR *v_error, int class, FIL fprintf(fp, "%+2.2f ", RVECTOR_ELT(rbf->v_outputs, i)); if (v_error) fprintf(fp, "(%+2.2f) ", VECTOR_ELT(v_error, i)); } - if (class >= 0) - fprintf(fp, " : %d \n", class); + if (classnum >= 0) + fprintf(fp, " : %d \n", classnum); else fprintf(fp, "\n"); return (NO_ERROR); @@ -800,21 +800,21 @@ static int rbfComputeOutputs(RBF *rbf) ------------------------------------------------------*/ int RBFclassify(RBF *rbf, VECTOR *v_obs) { - int class, c; + int classnum, c; float max_val, val; rbfComputeHiddenActivations(rbf, v_obs); rbfComputeOutputs(rbf); max_val = RVECTOR_ELT(rbf->v_outputs, 1); - class = 0; + classnum = 0; for (c = 2; c <= rbf->noutputs; c++) { val = RVECTOR_ELT(rbf->v_outputs, c); if (val > max_val) { max_val = val; - class = c - 1; + classnum = c - 1; } } - return (class); + return (classnum); } /*----------------------------------------------------- Parameters: @@ -837,7 +837,7 @@ static float rbfTrain(RBF *rbf, int which) { VECTOR *v_obs, *v_error; - int obs_no, class, epoch = 0, nsmall = 0, nnegative = 0, nobs, positive = 0; + int obs_no, classnum, epoch = 0, nsmall = 0, nnegative = 0, nobs, positive = 0; float error, sse = 0.0f, delta_sse, rms, old_sse; RBF *rbf_save = NULL; @@ -862,7 +862,7 @@ static float rbfTrain(RBF *rbf, #else obs_no = nobs; #endif - if ((*get_observation_func)(v_obs, obs_no, parm, 0, &class) != NO_ERROR) + if ((*get_observation_func)(v_obs, obs_no, parm, 0, &classnum) != NO_ERROR) ErrorExit(ERROR_BADPARM, "rbfTrain: observation function failed to" " obtain training sample # %d", @@ -881,7 +881,7 @@ static float rbfTrain(RBF *rbf, rbfNormalizeObservation(rbf, v_obs, v_obs); rbfComputeHiddenActivations(rbf, v_obs); rbfComputeOutputs(rbf); - error = RBFcomputeErrors(rbf, class, v_error); + error = RBFcomputeErrors(rbf, classnum, v_error); sse += error; if (which & TRAIN_CENTERS) rbfAdjustHiddenCenters(rbf, v_error); #if 1 @@ -999,13 +999,13 @@ int RBFexamineTrainingSet(RBF *rbf, int (*get_observation_func)(VECTOR *v_obs, int no, void *parm, int same_class, int *pclass), void *parm) { - int obs_no = 0, class, row, c, i; + int obs_no = 0, classnum, row, c, i; VECTOR *v_obs; float *means, *stds, v, mean; v_obs = VectorAlloc(rbf->ninputs, MATRIX_REAL); - if ((*get_observation_func)(v_obs, obs_no++, parm, 0, &class) != NO_ERROR) + if ((*get_observation_func)(v_obs, obs_no++, parm, 0, &classnum) != NO_ERROR) ErrorExit(ERROR_BADPARM, "rbfExamineTrainingSet: no samples in set"); /* not really a good idea to be messing with the CS internal parameters, @@ -1025,7 +1025,7 @@ int RBFexamineTrainingSet(RBF *rbf, stds[row - 1] = v * v; } - while ((*get_observation_func)(v_obs, obs_no++, parm, 0, &class) == NO_ERROR) { + while ((*get_observation_func)(v_obs, obs_no++, parm, 0, &classnum) == NO_ERROR) { for (i = 0; i < rbf->ninputs; i++) { v = VECTOR_ELT(v_obs, i + 1); if (v > rbf->max_inputs[i]) rbf->max_inputs[i] = v; @@ -1070,17 +1070,17 @@ RBF *RBFcopyWeights(RBF *rbf_src, RBF *rbf_dst) int i; if (!rbf_dst) { - int max_clusters[MAX_OUTPUTS], cno, class, c; + int max_clusters[MAX_OUTPUTS], cno, classnum, c; CLUSTER_SET *cs_src, *cs_dst; for (i = 0; i < rbf_src->noutputs; i++) max_clusters[i] = rbf_src->cs[i] ? rbf_src->cs[i]->max_clusters : 0; - rbf_dst = RBFinit(rbf_src->ninputs, rbf_src->noutputs, max_clusters, rbf_src->class_names); + rbf_dst = RBFinit(rbf_src->ninputs, rbf_src->noutputs, max_clusters, const_cast(rbf_src->class_names)); /* fill in cluster pointers in rbf struct for convenience sake */ - for (cno = class = 0; class < rbf_src->noutputs; class ++) { - cs_src = rbf_src->cs[class]; - cs_dst = rbf_dst->cs[class]; + for (cno = classnum = 0; classnum < rbf_src->noutputs; classnum ++) { + cs_src = rbf_src->cs[classnum]; + cs_dst = rbf_dst->cs[classnum]; if (cs_src) for (c = 0; c < cs_src->nclusters; c++, cno++) rbf_dst->clusters[cno] = cs_dst->clusters + c; } @@ -1128,12 +1128,12 @@ static float rbfComputeCurrentError( float error, sse, obs_no; // float rms; VECTOR *v_obs, *v_error; - int class; + int classnum; v_obs = VectorAlloc(rbf->ninputs, MATRIX_REAL); v_error = VectorAlloc(rbf->noutputs, MATRIX_REAL); for (sse = 0.0f, obs_no = 0; obs_no < rbf->nobs; obs_no++) { - if ((*get_observation_func)(v_obs, obs_no, parm, 0, &class) != NO_ERROR) + if ((*get_observation_func)(v_obs, obs_no, parm, 0, &classnum) != NO_ERROR) ErrorExit(ERROR_BADPARM, "rbfTrain: observation function failed to" " obtain training sample # %d", @@ -1141,7 +1141,7 @@ static float rbfComputeCurrentError( rbfNormalizeObservation(rbf, v_obs, v_obs); rbfComputeHiddenActivations(rbf, v_obs); rbfComputeOutputs(rbf); - error = RBFcomputeErrors(rbf, class, v_error); + error = RBFcomputeErrors(rbf, classnum, v_error); sse += error; } // rms = sqrt(sse / (float)rbf->nobs); @@ -1170,7 +1170,7 @@ static int rbfCalculateOutputWeights( RBF *rbf, int (*get_observation_func)(VECTOR *v_obs, int no, void *parm, int same_class, int *pclass), void *parm) { VECTOR *v_obs, *v_hidden; - int class, obs_no, i, k; + int classnum, obs_no, i, k; MATRIX *m_Gt_G, *m_Gt_G_inv, *m_Gt_D; v_obs = VectorAlloc(rbf->ninputs, MATRIX_REAL); @@ -1182,7 +1182,7 @@ static int rbfCalculateOutputWeights( /* go through the training set again to calculate (Gt G) and Gt D where D is the vector of desired values */ for (obs_no = 0; obs_no < rbf->nobs; obs_no++) { - if ((*get_observation_func)(v_obs, obs_no, parm, 0, &class) != NO_ERROR) + if ((*get_observation_func)(v_obs, obs_no, parm, 0, &classnum) != NO_ERROR) ErrorExit(ERROR_BADPARM, "rbfCalculateOutputWeights: observation " " function failed to obtain training sample # %d", @@ -1192,7 +1192,7 @@ static int rbfCalculateOutputWeights( for (i = 1; i <= rbf->nhidden + 1; i++) { /* only contributs to this class (all other outputs are 0) */ - m_Gt_D->rptr[i][class + 1] += RVECTOR_ELT(v_hidden, i); + m_Gt_D->rptr[i][classnum + 1] += RVECTOR_ELT(v_hidden, i); for (k = 1; k <= rbf->nhidden + 1; k++) m_Gt_G->rptr[i][k] += RVECTOR_ELT(v_hidden, i) * RVECTOR_ELT(v_hidden, k); } } @@ -1296,7 +1296,7 @@ int RBFwriteInto(RBF *rbf, FILE *fp) int i; fprintf(fp, "%d %d %d\n", rbf->noutputs, rbf->ninputs, rbf->nhidden); - fprintf(fp, "\n# class names and max # of clusters\n"); + fprintf(fp, "\n# classnum names and max # of clusters\n"); for (i = 0; i < rbf->noutputs; i++) fprintf(fp, "%d %s\n", rbf->cs[i] ? rbf->cs[i]->max_clusters : 0, rbf->class_names[i]); @@ -1318,8 +1318,9 @@ int RBFwriteInto(RBF *rbf, FILE *fp) ------------------------------------------------------*/ RBF *RBFreadFrom(FILE *fp) { - int i, c, cno, class, noutputs, ninputs, nhidden, max_clusters[MAX_OUTPUTS]; - char *names[MAX_OUTPUTS], *cp, line[100]; + int i, c, cno, classnum, noutputs, ninputs, nhidden, max_clusters[MAX_OUTPUTS]; + char *cp, line[100]; + char *names[MAX_OUTPUTS]; RBF *rbf; if (fscanf(fp, "%d %d %d\n", &noutputs, &ninputs, &nhidden) != 3) @@ -1333,7 +1334,7 @@ RBF *RBFreadFrom(FILE *fp) names[i] = (char *)calloc(strlen(cp) + 1, sizeof(char)); strcpy(names[i], cp); } - rbf = RBFinit(ninputs, noutputs, max_clusters, names); + rbf = RBFinit(ninputs, noutputs, max_clusters, const_cast(names)); for (i = 0; i < noutputs; i++) free(names[i]); MatrixAsciiReadFrom(fp, rbf->m_wij); @@ -1343,9 +1344,9 @@ RBF *RBFreadFrom(FILE *fp) } /* fill in cluster pointers in rbf struct for convenience sake */ - for (cno = class = 0; class < rbf->noutputs; class ++) { - if (rbf->cs[class]) - for (c = 0; c < rbf->cs[class]->nclusters; c++, cno++) rbf->clusters[cno] = rbf->cs[class]->clusters + c; + for (cno = classnum = 0; classnum < rbf->noutputs; classnum ++) { + if (rbf->cs[classnum]) + for (c = 0; c < rbf->cs[classnum]->nclusters; c++, cno++) rbf->clusters[cno] = rbf->cs[classnum]->clusters + c; } return (rbf); @@ -1353,7 +1354,7 @@ RBF *RBFreadFrom(FILE *fp) #if 0 int -RBFbuildScatterPlot(RBF *rbf, int class, MATRIX *m_scatter, +RBFbuildScatterPlot(RBF *rbf, int classnum, MATRIX *m_scatter, char *training_file_name) { static int first = 0 ; @@ -1397,7 +1398,7 @@ RBFbuildScatterPlot(RBF *rbf, int class, MATRIX *m_scatter, stds = rbf->cs[0]->stds ; /* now fill in scatter plot */ - while (mricGetClassifierInput(v_obs, obs_no++, &parms,1,&class) == NO_ERROR) + while (mricGetClassifierInput(v_obs, obs_no++, &parms,1,&classnum) == NO_ERROR) { for (i = 0 ; i < rbf->ninputs ; i++) { diff --git a/utils/rbm.c b/utils/rbm.cpp similarity index 100% rename from utils/rbm.c rename to utils/rbm.cpp diff --git a/utils/realm.c b/utils/realm.cpp similarity index 99% rename from utils/realm.c rename to utils/realm.cpp index 6652f04eb05..985909306b0 100644 --- a/utils/realm.c +++ b/utils/realm.cpp @@ -716,12 +716,14 @@ static int chooseChild( return c; } -typedef enum Widen_Mask { - Widen_xLo = 1, Widen_xHi = 2, - Widen_yLo = 4, Widen_yHi = 8, - Widen_zLo = 16, Widen_zHi = 32 } Widen_Mask; +#define Widen_xLo 1 +#define Widen_xHi 2 +#define Widen_yLo 4 +#define Widen_yHi 8 +#define Widen_zLo 16 +#define Widen_zHi 32 -static void widenSubtree_wkr(RealmTreeNode* n, float xLo, float xHi, float yLo, float yHi, float zLo, float zHi, Widen_Mask widen_Mask) { +static void widenSubtree_wkr(RealmTreeNode* n, float xLo, float xHi, float yLo, float yHi, float zLo, float zHi, unsigned widen_Mask) { if (!n || (widen_Mask == 0)) return; // if (widen_Mask & Widen_xLo) n->xLo = xLo; if (widen_Mask & Widen_xHi) n->xHi = xHi; @@ -731,7 +733,7 @@ static void widenSubtree_wkr(RealmTreeNode* n, float xLo, float xHi, float yLo, if (n->vnos) return; // leaf nodes // there are eight children - // zyx + // zyx // 0 000 // 1 001 // 2 010 @@ -742,19 +744,19 @@ static void widenSubtree_wkr(RealmTreeNode* n, float xLo, float xHi, float yLo, // 7 111 // each should only have some of its bounds widened // - widenSubtree_wkr(n->childIfPresent[0], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yHi | Widen_zHi)); - widenSubtree_wkr(n->childIfPresent[1], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yHi | Widen_zHi)); - widenSubtree_wkr(n->childIfPresent[2], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yLo | Widen_zHi)); - widenSubtree_wkr(n->childIfPresent[3], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yLo | Widen_zHi)); - widenSubtree_wkr(n->childIfPresent[4], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yHi | Widen_zLo)); - widenSubtree_wkr(n->childIfPresent[5], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yHi | Widen_zLo)); - widenSubtree_wkr(n->childIfPresent[6], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yLo | Widen_zLo)); - widenSubtree_wkr(n->childIfPresent[7], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yLo | Widen_zLo)); + widenSubtree_wkr(n->childIfPresent[0], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yHi | Widen_zHi)); + widenSubtree_wkr(n->childIfPresent[1], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yHi | Widen_zHi)); + widenSubtree_wkr(n->childIfPresent[2], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yLo | Widen_zHi)); + widenSubtree_wkr(n->childIfPresent[3], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yLo | Widen_zHi)); + widenSubtree_wkr(n->childIfPresent[4], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yHi | Widen_zLo)); + widenSubtree_wkr(n->childIfPresent[5], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yHi | Widen_zLo)); + widenSubtree_wkr(n->childIfPresent[6], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xHi | Widen_yLo | Widen_zLo)); + widenSubtree_wkr(n->childIfPresent[7], xLo, xHi, yLo, yHi, zLo, zHi, widen_Mask & ~(Widen_xLo | Widen_yLo | Widen_zLo)); } static void widenSubtree(RealmTree* realmTree, float xLo, float xHi, float yLo, float yHi, float zLo, float zHi) { RealmTreeNode* n = &realmTree->root; - Widen_Mask widen_Mask = 0; + unsigned widen_Mask = 0; if (xLo < n->xLo) widen_Mask |= Widen_xLo; if (xHi > n->xHi) widen_Mask |= Widen_xHi; if (yLo < n->yLo) widen_Mask |= Widen_yLo; @@ -1441,7 +1443,7 @@ static void moveToNext(RealmIterator* realmIterator, Realm* realm) { #endif unsigned long c = i & leafIndexMask; c++; - if (c < n->vnosSize) { + if (c < (unsigned)n->vnosSize) { realmIterator->i++; return; } @@ -1717,9 +1719,9 @@ static void growCapacity(int* p_capacity, int minCapacity) { static void growInts(int** p_old, int old_capacity, int new_capacity) { int* old = *p_old; - int* new = (int*)realloc(old, new_capacity*sizeof(int)); - bzero(&new[old_capacity], (new_capacity - old_capacity)*sizeof(int)); - *p_old = new; + int* curr = (int*)realloc(old, new_capacity*sizeof(int)); + bzero(&curr[old_capacity], (new_capacity - old_capacity)*sizeof(int)); + *p_old = curr; } static void growCapacityAndInts(int** p_old, int* p_capacity, int minCapacity) { diff --git a/utils/rec.c b/utils/rec.c deleted file mode 100644 index 1e1db4d3695..00000000000 --- a/utils/rec.c +++ /dev/null @@ -1,192 +0,0 @@ -/** - * @file rec.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.9 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include - -#include "error.h" -#include "matrix.h" -#include "rec.h" - -REC *RecRead(char *fname, int iop_neeg, int iop_nmeg) -{ - int i, j, tnchan; - float f; - FILE *fp; - REC *rec; - - printf("read_rec(%s)\n", fname); - - fp = fopen(fname, "r"); - if (fp == NULL) ErrorReturn(NULL, (ERROR_BADFILE, "RecRead: could not open file %s", fname)); - - rec = (REC *)calloc(1, sizeof(REC)); - if (rec == NULL) ErrorExit(ERROR_NOMEMORY, "RecRead: couldn't allocate rec struct"); - - fscanf(fp, "%*s"); - fscanf(fp, "%d %d %d", &rec->ntimepts, &rec->nmeg_channels, &rec->neeg_channels); - tnchan = rec->nmeg_channels + rec->neeg_channels; - rec->ptime = (int)(2 * pow(2.0, ceil(log((float)rec->ntimepts) / log(2.0)))); - printf("ntimepts=%d, ptime=%d\n", rec->ntimepts, rec->ptime); -#if 0 - if (sol_ntime>0 && sol_ntime!=rec->ntimepts) - { - printf("ntime does not match rec->ntimepts (%d != %d)\n",sol_ntime,rec->ntimepts); - exit(0); - } - - sol_ntime = rec->ntimepts; - sol_ptime = tptime; - - if (rec->nmeg_channels>0 && rec->nmeg_channels!=tnmeg) - { - printf("nmeg does not match tnmeg (%d != %d)\n",rec->nmeg_channels,tnmeg); - exit(0); - } - if (sol_neeg>0 && sol_neeg!=tneeg) - { - printf("neeg does not match tnmeg (%d != %d)\n",sol_neeg,tneeg); - exit(0); - } -#endif - - rec->latencies = (float *)calloc(rec->ptime, sizeof(float)); - if (!rec->latencies) ErrorExit(ERROR_NOMEMORY, "RecRead(%s): could not allocate latency vector", fname); - rec->m_data = MatrixAlloc(tnchan, rec->ptime, MATRIX_REAL); - for (j = 0; j < rec->ntimepts; j++) { - fscanf(fp, "%f", &f); - rec->latencies[j] = f; - for (i = 0; i < rec->neeg_channels; i++) { - fscanf(fp, "%f", &f); - if (iop_neeg > 0) *MATRIX_RELT(rec->m_data, i + 1, j + 1) = f; - } - for (i = 0; i < rec->nmeg_channels; i++) { - fscanf(fp, "%f", &f); - if (iop_nmeg > 0) *MATRIX_RELT(rec->m_data, i + iop_neeg + 1, j + 1) = f; - } - } - fclose(fp); - printf("rec file read, sample period %2.4f, starting latency %2.4f\n", - rec->latencies[1] - rec->latencies[0], - rec->latencies[0]); - -#if 0 - sol_dipcmp_val[sol_nrec] = matrix(sol_nnz*sol_nperdip,sol_ntime); -#endif - return (rec); -} - -/* flag = 0 everything as usual - flag = 1 load only EEG channels - flag = 2 load only MEG channels - flag = 4 don't pad with ramp -*/ -REC *RecReadPartially(char *fname, int iop_neeg, int iop_nmeg, int flag) -{ - int i, j, tnchan; - float f; - FILE *fp; - REC *rec; - - printf("read_rec(%s)\n", fname); - - fp = fopen(fname, "r"); - if (fp == NULL) ErrorReturn(NULL, (ERROR_BADFILE, "RecRead: could not open file %s", fname)); - - rec = (REC *)calloc(1, sizeof(REC)); - if (rec == NULL) ErrorExit(ERROR_NOMEMORY, "RecRead: couldn't allocate rec struct"); - - fscanf(fp, "%*s"); - fscanf(fp, "%d %d %d", &rec->ntimepts, &rec->nmeg_channels, &rec->neeg_channels); - tnchan = rec->nmeg_channels + rec->neeg_channels; - rec->ptime = rec->ntimepts; - if (!(flag & 4)) { - rec->ptime = (int)(2 * pow(2.0, ceil(log((float)rec->ntimepts) / log(2.0)))); - } - printf("ntimepts=%d, ptime=%d\n", rec->ntimepts, rec->ptime); -#if 0 - if (sol_ntime>0 && sol_ntime!=rec->ntimepts) - { - printf("ntime does not match rec->ntimepts (%d != %d)\n",sol_ntime,rec->ntimepts); - exit(0); - } - - sol_ntime = rec->ntimepts; - sol_ptime = tptime; - - if (rec->nmeg_channels>0 && rec->nmeg_channels!=tnmeg) - { - printf("nmeg does not match tnmeg (%d != %d)\n",rec->nmeg_channels,tnmeg); - exit(0); - } - if (sol_neeg>0 && sol_neeg!=tneeg) - { - printf("neeg does not match tnmeg (%d != %d)\n",sol_neeg,tneeg); - exit(0); - } -#endif - - rec->latencies = (float *)calloc(rec->ptime, sizeof(float)); - if (!rec->latencies) ErrorExit(ERROR_NOMEMORY, "RecRead(%s): could not allocate latency vector", fname); - - /* added by twitzel */ - if (flag & 1) { - tnchan = rec->neeg_channels; - } - if (flag & 2) { - tnchan = rec->nmeg_channels; - } - - rec->m_data = MatrixAlloc(tnchan, rec->ptime, MATRIX_REAL); - for (j = 0; j < rec->ntimepts; j++) { - fscanf(fp, "%f", &f); - rec->latencies[j] = f; - - for (i = 0; i < rec->neeg_channels; i++) { - fscanf(fp, "%f", &f); - if (iop_neeg > 0) *MATRIX_RELT(rec->m_data, i + 1, j + 1) = f; - } - - for (i = 0; i < rec->nmeg_channels; i++) { - fscanf(fp, "%f", &f); - if (iop_nmeg > 0) *MATRIX_RELT(rec->m_data, i + iop_neeg + 1, j + 1) = f; - } - } - fclose(fp); - printf("rec file read, sample period %2.4f, starting latency %2.4f\n", - rec->latencies[1] - rec->latencies[0], - rec->latencies[0]); - if (flag & 1) { - rec->nmeg_channels = 0; - } - if (flag & 2) { - rec->neeg_channels = 0; - } -#if 0 - sol_dipcmp_val[sol_nrec] = matrix(sol_nnz*sol_nperdip,sol_ntime); -#endif - return (rec); -} diff --git a/utils/region.c b/utils/region.cpp similarity index 100% rename from utils/region.c rename to utils/region.cpp diff --git a/utils/registerio.c b/utils/registerio.cpp similarity index 99% rename from utils/registerio.c rename to utils/registerio.cpp index e1b3c0cb5f9..5149592f259 100644 --- a/utils/registerio.c +++ b/utils/registerio.cpp @@ -173,7 +173,7 @@ int regio_print_register( FILE *fp, const char *subject, float inplaneres, float betplaneres, float intensity, const MATRIX *R, int float2int) { int r, c; - char *f2imethod; + const char *f2imethod; if (subject == NULL) fprintf(fp, "subject-unknown\n"); @@ -344,7 +344,7 @@ int regio_write_mincxfm(const char *xfmfile, const MATRIX *R, const char *filein fprintf(fp, "MNI Transform File\n"); if (fileinfo) fprintf(fp, "%% %s\n", fileinfo); fprintf(fp, "%% This file was created by %s\n", Progname); - fprintf(fp, "%% %s\n", current_date_time()); + fprintf(fp, "%% %s\n", currentDateTime().c_str()); fprintf(fp, "\n"); fprintf(fp, "Transform_Type = Linear;\n"); fprintf(fp, "Linear_Transform =\n"); diff --git a/utils/resample.c b/utils/resample.cpp similarity index 99% rename from utils/resample.c rename to utils/resample.cpp index 31af4512879..d55d204a4da 100644 --- a/utils/resample.c +++ b/utils/resample.cpp @@ -1912,7 +1912,6 @@ MRI *MRIseg2SegPVF( float **nperfth, npervox; // need float for nperf for consistency int nhits, segidmax, nthvox, ndc, ndr, nds, nthreads; int c, r, s, f, nframesout = 0, outtype = 0, DoSeg; - struct timeb timer; static int InitNeeded = 1, nvox = 0, *clist = NULL, *rlist = NULL, *slist = NULL, *seg2frame, nthcall = 0; if (ReInit < 0) { @@ -1926,7 +1925,7 @@ MRI *MRIseg2SegPVF( return (NULL); } - TimerStart(&timer); + Timer timer; if (ct) DoSeg = 1; @@ -2097,7 +2096,7 @@ MRI *MRIseg2SegPVF( dsstart, ds); printf("delta %g %g %g, npervox = %g\n", vg->xsize / ndc, vg->ysize / ndr, vg->zsize / nds, npervox); - printf("MRIseg2SegPVF(): starting fill t = %g, nvox=%d\n", TimerStop(&timer) / 1000.0, nvox); + printf("MRIseg2SegPVF(): starting fill t = %g, nvox=%d\n", timer.seconds(), nvox); fflush(stdout); } @@ -2190,7 +2189,7 @@ MRI *MRIseg2SegPVF( free(nperfth); if (nthcall < 4 || Gdiag_no > 0) { - printf("MRIseg2SegPVF(): done t = %g, nhits=%d, nthreads=%d\n", TimerStop(&timer) / 1000.0, nhits, nthreads); + printf("MRIseg2SegPVF(): done t = %g, nhits=%d, nthreads=%d\n", timer.seconds(), nhits, nthreads); fflush(stdout); } nthcall++; diff --git a/utils/rescale.c b/utils/rescale.c deleted file mode 100644 index 7628af2649c..00000000000 --- a/utils/rescale.c +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @file rescale.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/******************************************************************* - * Name: rescale.c - * Author: Douglas N. Greve, 5/14/96 - * Purpose: rescales the pixels of an image to within the given - * maximum and minimum. As a bonus, it also returns - * the row and column of the min and max. - * - * Input Formats: float - * Output Formats: byte - * - * Notes: 1. The input and output do not have to be of the same - * format. - * 2. MinPoint[0] = row ... - * 3. This is different than h_linscale() in two ways: - * a. The desired output range is specified instead - * of the scale and offset. - * b. The output image does not have to be float - * (as in linscale). - ******************************************************************/ - -#include - -#include "macros.h" -#include "minmaxrc.h" - -#include "rescale.h" - -/* y = Offset + Slope * x, y=New, x=Old ***/ -static int h_GetScaleParams(float OldMin, float OldMax, float NewMin, float NewMax, float *Offset, float *Slope) -{ - float Del; - int Warning = 1; - - Del = OldMax - OldMin; - if (Del < .00000001F) { - *Offset = 0.0F; - *Slope = 1.0F; - Warning = 1; - } - else { - *Slope = (NewMax - NewMin) / Del; - *Offset = (NewMin - *Slope * OldMin); - Warning = 0; - } - - return (Warning); -} -/*************************************************************/ -int h_rescale( - struct header *phdSrc, float NewMin, float NewMax, int MinPoint[2], int MaxPoint[2], struct header *phdDst) -{ - Pixelval Min, Max; - float Offset, Slope; - int err; - - /** find the present min and max and where they are **/ - err = h_minmaxrc(phdSrc, &Min, MinPoint, &Max, MaxPoint); - if (err) return (err); - - /****** switch over the input format *************/ - switch (phdSrc->pixel_format) { - case PFFLOAT: - /* for float input, switch over the output format */ - switch (phdDst->pixel_format) { - case PFBYTE: - h_GetScaleParams(Min.v_float, Max.v_float, NewMin, NewMax, &Offset, &Slope); - return (h_rescale_fb(phdSrc, Slope, Offset, phdDst)); - break; - - case PFFLOAT: - h_GetScaleParams(Min.v_float, Max.v_float, NewMin, NewMax, &Offset, &Slope); - return (h_rescale_ff(phdSrc, Slope, Offset, phdDst)); - break; - - default: - return (perr(HE_FMTSUBR, "h_rescale: Destination", hformatname(phdDst->pixel_format))); - } /* end switch over destination pixel format for float input*/ - break; - - default: - return (perr(HE_FMTSUBR, "h_rescale: Source", hformatname(phdSrc->pixel_format))); - } /********** end switch over source pixel format *************/ - return (HIPS_OK); -} - -/********************************************************/ -int h_rescale_fb(struct header *phdSrc, float Slope, float Offset, struct header *phdDst) -{ - register INT32B n; - register float *pSrc; - register byte *pDst; - - pSrc = (float *)phdSrc->image; - pDst = (byte *)phdDst->image; - - for (n = 0; n < phdSrc->numpix; n++) *pDst++ = (byte)(*pSrc++ * Slope + Offset); - - return (HIPS_OK); -} - -/********************************************************/ -int h_rescale_ff(struct header *phdSrc, float Slope, float Offset, struct header *phdDst) -{ - register INT32B n; - register float *pSrc; - register float *pDst; - - pSrc = (float *)phdSrc->image; - pDst = (float *)phdDst->image; - - for (n = 0; n < phdSrc->numpix; n++) *pDst++ = (float)(*pSrc++ * Slope + Offset); - - return (HIPS_OK); -} diff --git a/utils/retinotopy.c b/utils/retinotopy.cpp similarity index 100% rename from utils/retinotopy.c rename to utils/retinotopy.cpp diff --git a/utils/rfa.c b/utils/rfa.cpp similarity index 99% rename from utils/rfa.c rename to utils/rfa.cpp index 78a8d64895f..6ded387cdbd 100644 --- a/utils/rfa.c +++ b/utils/rfa.cpp @@ -694,7 +694,7 @@ static int csf_labels[] = {CSF, int MRIcountCSFInNbhd(MRI *mri_seg, int wsize, int x, int y, int z) { - int total, n; + unsigned int total, n; for (n = total = 0; n < NCSF_LABELS; n++) total += MRIcountValInNbhd(mri_seg, wsize, x, y, z, csf_labels[n]); diff --git a/utils/rforest.c b/utils/rforest.cpp similarity index 99% rename from utils/rforest.c rename to utils/rforest.cpp index aa30a28f8da..4850e935003 100644 --- a/utils/rforest.c +++ b/utils/rforest.cpp @@ -49,7 +49,7 @@ RANDOM_FOREST *RFalloc(int ntrees, int nfeatures, int nclasses, int max_depth, c TREE *tree; int n, c = 0; - rf = calloc(1, sizeof(RANDOM_FOREST)); + rf = (RANDOM_FOREST *)calloc(1, sizeof(RANDOM_FOREST)); if (rf == NULL) ErrorExit(ERROR_NOMEMORY, "RFalloc(%d, %d, %d, %d): could not allocate RF", ntrees, nfeatures, nclasses, max_depth); @@ -102,7 +102,7 @@ RANDOM_FOREST *RFalloc(int ntrees, int nfeatures, int nclasses, int max_depth, c ERROR_NOMEMORY, "RFalloc(%d, %d, %d, %d): could not allocate fmax", ntrees, nfeatures, nclasses, max_depth); for (n = 0; n < rf->ntrees; n++) { tree = &rf->trees[n]; - tree->root.class_counts = calloc(rf->nclasses, sizeof(tree->root.class_counts[0])); + tree->root.class_counts = (int *)calloc(rf->nclasses, sizeof(tree->root.class_counts[0])); if (tree->root.class_counts == NULL) ErrorExit(ERROR_NOMEMORY, "RFalloc(%d, %d, %d, %d): could not allocate root %d", @@ -1079,7 +1079,7 @@ int RFsetNumberOfClasses(RANDOM_FOREST *rf, int nclasses) for (n = 0; n < rf->ntrees; n++) { tree = &rf->trees[n]; old_class_counts = tree->root.class_counts; - tree->root.class_counts = calloc(nclasses, sizeof(tree->root.class_counts[0])); + tree->root.class_counts = (int *)calloc(nclasses, sizeof(tree->root.class_counts[0])); if (tree->root.class_counts == NULL) ErrorExit(ERROR_NOMEMORY, "RFsetNumberOfClasses(%d): could not allocate class names", nclasses); memmove(tree->root.class_counts, old_class_counts, rf->nclasses * sizeof(tree->root.class_counts[0])); diff --git a/utils/rfutils.c b/utils/rfutils.cpp similarity index 100% rename from utils/rfutils.c rename to utils/rfutils.cpp diff --git a/utils/rgb.cpp b/utils/rgb.cpp new file mode 100644 index 00000000000..c072fa06910 --- /dev/null +++ b/utils/rgb.cpp @@ -0,0 +1,926 @@ +#include +#include +#include +#include +#include + +#include "rgb.h" + +#define OPEN_GL_CODE 1 + +void isetname(RGB_IMAGE *image, const char *name) { + strncpy(image->name,name,80); +} + +void isetcolormap(RGB_IMAGE *image, int colormap) { + image->colormap = colormap; +} + +int iclose(RGB_IMAGE *image) { + long tablesize, ret; + + iflush(image); + img_optseek(image, 0); + if (image->flags&_IOWRT) { + if (image->dorev) + cvtimage((long *)image); + swapImage(image) ; + if (img_write(image,(char *)image,sizeof(RGB_IMAGE)) != sizeof(RGB_IMAGE)) { + i_errhdlr("iclose: error on write of image header\n",0,0,0,0); + return EOF; + } + swapImage(image) ; + if (image->dorev) + cvtimage((long *)image); + if (ISRLE(image->type)) { + img_optseek(image, 512L); + tablesize = image->ysize*image->zsize*sizeof(long); + if (image->dorev) + cvtlongs((long *)image->rowstart,(long)tablesize); + if (img_write(image,(char *)(image->rowstart),tablesize) != tablesize) { + i_errhdlr("iclose: error on write of rowstart\n",0,0,0,0); + return EOF; + } + if (image->dorev) + cvtlongs((long *)image->rowsize,tablesize); + if (img_write(image,(char *)(image->rowsize),tablesize) != tablesize) { + i_errhdlr("iclose: error on write of rowsize\n",0,0,0,0); + return EOF; + } + } + } + if (image->base) { + free(image->base); + image->base = 0; + } + if (image->tmpbuf) { + free(image->tmpbuf); + image->tmpbuf = 0; + } + if (ISRLE(image->type)) { + free(image->rowstart); + image->rowstart = 0; + free(image->rowsize); + image->rowsize = 0; + } + ret = close(image->file); + if (ret != 0) + i_errhdlr("iclose: error on close of file\n",0,0,0,0); + free(image); + return ret; +} + +int iflush(RGB_IMAGE *image) { + unsigned short *base; + + if ( (image->flags&_IOWRT) + && (base=image->base)!=NULL && (image->ptr-base)>0) { + if (putrow(image, base, image->y,image->z)!=image->xsize) { + image->flags |= _IOERR; + return(EOF); + } + } + return(0); +} + +int ifilbuf(RGB_IMAGE *image) { + int size; + + if ((image->flags&_IOREAD) == 0) + return(EOF); + if (image->base==NULL) { + size = IBUFSIZE(image->xsize); + if ((image->base = ibufalloc(image)) == NULL) { + i_errhdlr("can't alloc image buffer\n",0,0,0,0); + return EOF; + } + } + image->cnt = getrow(image,image->base,image->y,image->z); + image->ptr = image->base; + if (--image->cnt < 0) { + if (image->cnt == -1) { + image->flags |= _IOEOF; + if (image->flags & _IORW) + image->flags &= ~_IOREAD; + } else + image->flags |= _IOERR; + image->cnt = 0; + return -1; + } + if (++image->y >= image->ysize) { + image->y = 0; + if (++image->z >= image->zsize) { + image->z = image->zsize-1; + image->flags |= _IOEOF; + return -1; + } + } + return *image->ptr++ & 0xffff; +} + +unsigned int iflsbuf(RGB_IMAGE *image, unsigned int c) { + register unsigned short *base; + register int n, rn; + int size; + + if ((image->flags&_IOWRT)==0) + return(EOF); + if ((base=image->base)==NULL) { + size = IBUFSIZE(image->xsize); + if ((image->base=base=ibufalloc(image)) == NULL) { + i_errhdlr("flsbuf: error on buf alloc\n",0,0,0,0); + return EOF; + } + rn = n = 0; + } else if ((rn = n = image->ptr - base) > 0) { + n = putrow(image,base,image->y,image->z); + if (++image->y >= image->ysize) { + image->y = 0; + if (++image->z >= image->zsize) { + image->z = image->zsize-1; + image->flags |= _IOEOF; + return -1; + } + } + } + image->cnt = image->xsize-1; + *base++ = c; + image->ptr = base; + if (rn != n) { + image->flags |= _IOERR; + return(EOF); + } + return(c); +} + +int getpix(RGB_IMAGE *image) { + if (--(image)->cnt>=0) + return (int)(*(image)->ptr++); + else + return ifilbuf(image); +} + +unsigned int putpix(RGB_IMAGE *image, unsigned int pix) { + if (--(image)->cnt>=0) + return (unsigned int)(*(image)->ptr++ = pix); + else + return iflsbuf(image,pix); +} + +unsigned long img_seek(RGB_IMAGE *image, unsigned int y, unsigned int z) { + if (img_badrow(image,y,z)) { + i_errhdlr("img_seek: row number out of range\n", 0,0,0,0); + return EOF; + } + image->x = 0; + image->y = y; + image->z = z; + if (ISVERBATIM(image->type)) { + switch (image->dim) { + case 1: + return img_optseek(image, 512L); + case 2: + return img_optseek(image,512L+(y*image->xsize)*BPP(image->type)); + case 3: + return img_optseek(image, + 512L+(y*image->xsize+z*image->xsize*image->ysize)* + BPP(image->type)); + default: + i_errhdlr("img_seek: weird dim\n",0,0,0,0); + break; + } + } else if (ISRLE(image->type)) { + switch (image->dim) { + case 1: + return img_optseek(image, image->rowstart[0]); + case 2: + return img_optseek(image, image->rowstart[y]); + case 3: + return img_optseek(image, image->rowstart[y+z*image->ysize]); + default: + i_errhdlr("img_seek: weird dim\n",0,0,0,0); + break; + } + } else + i_errhdlr("img_seek: weird image type\n",0,0,0,0); + return((unsigned long)-1); +} + +int img_badrow(RGB_IMAGE *image, unsigned int y, unsigned int z) { + if (y>=image->ysize || z>=image->zsize) + return 1; + else + return 0; +} + +int img_write(RGB_IMAGE *image, char *buffer,int count) { + int retval; + + retval = write(image->file,buffer,count); + if (retval == count) + image->offset += count; + else + image->offset = -1; + return retval; +} + +int img_read(RGB_IMAGE *image, char *buffer, int count) { + int retval; + + retval = read(image->file,buffer,count); + if (retval == count) + image->offset += count; + else + image->offset = -1; + return retval; +} + +unsigned long img_optseek(RGB_IMAGE *image, unsigned long offset) { + if (image->offset != offset) { + image->offset = offset; + return ((unsigned long) lseek(image->file,offset,0)); + } + return offset; +} + +long img_getrowsize(RGB_IMAGE *image) { + switch (image->dim) { + case 1: + return image->rowsize[0]; + case 2: + return image->rowsize[image->y]; + case 3: + return image->rowsize[image->y+image->z*image->ysize]; + } + return(0L) ; +} + +void img_setrowsize(RGB_IMAGE *image, long cnt, long y, long z) { + int *sizeptr; + + if (img_badrow(image,y,z)) + return; + switch (image->dim) { + default: + case 1: + sizeptr = &image->rowsize[0]; + image->rowstart[0] = image->rleend; + break; + case 2: + sizeptr = &image->rowsize[y]; + image->rowstart[y] = image->rleend; + break; + case 3: + sizeptr = &image->rowsize[y+z*image->ysize]; + image->rowstart[y+z*image->ysize] = image->rleend; + } + if (*sizeptr != -1) + image->wastebytes += *sizeptr; + *sizeptr = cnt; + image->rleend += cnt; +} + +#define docompact \ + while(iptr126 ? 126:count; \ + count -= todo; \ + *optr++ = 0x80|todo; \ + while(todo--) \ + *optr++ = *sptr++; \ + } \ + sptr = iptr; \ + cc = *iptr++; \ + while( (iptr126 ? 126:count; \ + count -= todo; \ + *optr++ = todo; \ + *optr++ = cc; \ + } \ + } \ + *optr++ = 0; + +int img_rle_compact(unsigned short *expbuf, int ibpp, + unsigned short *rlebuf, int obpp, int cnt) { + if (ibpp == 1 && obpp == 1) { + register unsigned char *iptr = (unsigned char *)expbuf; + register unsigned char *ibufend = iptr+cnt; + register unsigned char *sptr; + register unsigned char *optr = (unsigned char *)rlebuf; + register short todo, cc; + register long count; + + docompact; + return optr - (unsigned char *)rlebuf; + } else if (ibpp == 1 && obpp == 2) { + register unsigned char *iptr = (unsigned char *)expbuf; + register unsigned char *ibufend = iptr+cnt; + register unsigned char *sptr; + register unsigned short *optr = rlebuf; + register short todo, cc; + register long count; + + docompact; + return optr - rlebuf; + } else if (ibpp == 2 && obpp == 1) { + register unsigned short *iptr = expbuf; + register unsigned short *ibufend = iptr+cnt; + register unsigned short *sptr; + register unsigned char *optr = (unsigned char *)rlebuf; + register short todo, cc; + register long count; + + docompact; + return optr - (unsigned char *)rlebuf; + } else if (ibpp == 2 && obpp == 2) { + register unsigned short *iptr = expbuf; + register unsigned short *ibufend = iptr+cnt; + register unsigned short *sptr; + register unsigned short *optr = rlebuf; + register short todo, cc; + register long count; + + docompact; + return optr - rlebuf; + } else { + i_errhdlr("rle_compact: bad bpp: %d %d\n",ibpp,obpp,0,0); + return 0; + } +} + +#define doexpand \ + while(1) { \ + pixel = *iptr++; \ + if ( !(count = (pixel & 0x7f)) ) \ + return; \ + if(pixel & 0x80) { \ + while(count--) \ + *optr++ = *iptr++; \ + } else { \ + pixel = *iptr++; \ + while(count--) \ + *optr++ = pixel; \ + } \ + } + +void img_rle_expand(unsigned short *rlebuf, int ibpp, + unsigned short *expbuf, int obpp) { + if (ibpp == 1 && obpp == 1) { + register unsigned char *iptr = (unsigned char *)rlebuf; + register unsigned char *optr = (unsigned char *)expbuf; + register unsigned short pixel,count; + + doexpand; + } else if (ibpp == 1 && obpp == 2) { + register unsigned char *iptr = (unsigned char *)rlebuf; + register unsigned short *optr = expbuf; + register unsigned short pixel,count; + + doexpand; + } else if (ibpp == 2 && obpp == 1) { + register unsigned short *iptr = rlebuf; + register unsigned char *optr = (unsigned char *)expbuf; + register unsigned short pixel,count; + + doexpand; + } else if (ibpp == 2 && obpp == 2) { + register unsigned short *iptr = rlebuf; + register unsigned short *optr = expbuf; + register unsigned short pixel,count; + + doexpand; + } else + i_errhdlr("rle_expand: bad bpp: %d %d\n",ibpp,obpp,0,0); +} + +int putrow_uc(RGB_IMAGE *image, unsigned char *buffer, unsigned int y, unsigned int z) { + register unsigned char *sptr; + register unsigned char *cptr; + register unsigned int x; + register unsigned long min, max; + register long cnt; + + if ( !(image->flags & (_IORW|_IOWRT)) ) + return -1; + if (image->dim<3) + z = 0; + if (image->dim<2) + y = 0; + if (ISVERBATIM(image->type)) { + switch (BPP(image->type)) { + case 1: + min = image->min; + max = image->max; + cptr = (unsigned char *)image->tmpbuf; + sptr = buffer; + /* this might be uneccessary for this uc function */ + for (x=image->xsize; x--;) { + *cptr = *sptr++; + if (*cptr > max) max = *cptr; + if (*cptr < min) min = *cptr; + cptr++; + } + image->min = min; + image->max = max; + img_seek(image,y,z); + cnt = image->xsize; + if (img_write(image,(char *)(image->tmpbuf),cnt) != cnt) { + i_errhdlr("putrow: error on write of row\n",0,0,0,0); + return -1; + } else + return cnt; + case 2: + printf("ERROR: this rgb save function BPP=2 is not implemented\n"); + default: + i_errhdlr("putrow: weird bpp\n",0,0,0,0); + } + } else if (ISRLE(image->type)) { + printf("ERROR: compressed RGB is not implemented !\n"); + } else + i_errhdlr("putrow: weird image type\n",0,0,0,0); + return(-1); +} + +int putrow(RGB_IMAGE *image, unsigned short *buffer, unsigned int y, unsigned int z) { + register unsigned short *sptr; + register unsigned char *cptr; + register unsigned int x; + register unsigned long min, max; + register long cnt; + + if ( !(image->flags & (_IORW|_IOWRT)) ) + return -1; + if (image->dim<3) + z = 0; + if (image->dim<2) + y = 0; + if (ISVERBATIM(image->type)) { + switch (BPP(image->type)) { + case 1: + min = image->min; + max = image->max; + cptr = (unsigned char *)image->tmpbuf; + sptr = buffer; + for (x=image->xsize; x--;) { + *cptr = *sptr++; + if (*cptr > max) max = *cptr; + if (*cptr < min) min = *cptr; + cptr++; + } + image->min = min; + image->max = max; + img_seek(image,y,z); + cnt = image->xsize; + if (img_write(image,(char *)(image->tmpbuf),cnt) != cnt) { + i_errhdlr("putrow: error on write of row\n",0,0,0,0); + return -1; + } else + return cnt; + /* NOTREACHED */ + + case 2: + min = image->min; + max = image->max; + sptr = buffer; + for (x=image->xsize; x--;) { + if (*sptr > max) max = *sptr; + if (*sptr < min) min = *sptr; + sptr++; + } + image->min = min; + image->max = max; + img_seek(image,y,z); + cnt = image->xsize<<1; + if (image->dorev) + cvtshorts(buffer,cnt); + if (img_write(image,(char *)(buffer),cnt) != cnt) { + if (image->dorev) + cvtshorts(buffer,cnt); + i_errhdlr("putrow: error on write of row\n",0,0,0,0); + return -1; + } else { + if (image->dorev) + cvtshorts(buffer,cnt); + return image->xsize; + } + /* NOTREACHED */ + + default: + i_errhdlr("putrow: weird bpp\n",0,0,0,0); + } + } else if (ISRLE(image->type)) { + switch (BPP(image->type)) { + case 1: + min = image->min; + max = image->max; + sptr = buffer; + for (x=image->xsize; x--;) { + if (*sptr > max) max = *sptr; + if (*sptr < min) min = *sptr; + sptr++; + } + image->min = min; + image->max = max; + cnt = img_rle_compact(buffer,2,image->tmpbuf,1,image->xsize); + img_setrowsize(image,cnt,y,z); + img_seek(image,y,z); + if (img_write(image,(char *)(image->tmpbuf),cnt) != cnt) { + i_errhdlr("putrow: error on write of row\n",0,0,0,0); + return -1; + } else + return image->xsize; + /* NOTREACHED */ + + case 2: + min = image->min; + max = image->max; + sptr = buffer; + for (x=image->xsize; x--;) { + if (*sptr > max) max = *sptr; + if (*sptr < min) min = *sptr; + sptr++; + } + image->min = min; + image->max = max; + cnt = img_rle_compact(buffer,2,image->tmpbuf,2,image->xsize); + cnt <<= 1; + img_setrowsize(image,cnt,y,z); + img_seek(image,y,z); + if (image->dorev) + cvtshorts(image->tmpbuf,cnt); + if (img_write(image,(char *)(image->tmpbuf),cnt) != cnt) { + if (image->dorev) + cvtshorts(image->tmpbuf,cnt); + i_errhdlr("putrow: error on write of row\n",0,0,0,0); + return -1; + } else { + if (image->dorev) + cvtshorts(image->tmpbuf,cnt); + return image->xsize; + } + /* NOTREACHED */ + + default: + i_errhdlr("putrow: weird bpp\n",0,0,0,0); + } + } else + i_errhdlr("putrow: weird image type\n",0,0,0,0); + return(-1); +} + +int getrow(RGB_IMAGE *image, unsigned short *buffer, + unsigned int y, unsigned int z) { + register short i; + register unsigned char *cptr; + register unsigned short *sptr; + register short cnt; + + if ( !(image->flags & (_IORW|_IOREAD)) ) + return -1; + if (image->dim<3) + z = 0; + if (image->dim<2) + y = 0; + img_seek(image, y, z); + if (ISVERBATIM(image->type)) { + switch (BPP(image->type)) { + case 1: + if (img_read(image,(char *)image->tmpbuf,image->xsize) + != image->xsize) { + i_errhdlr("getrow: error on read of row\n",0,0,0,0); + return -1; + } else { + cptr = (unsigned char *)image->tmpbuf; + sptr = buffer; + for (i=image->xsize; i--;) + *sptr++ = *cptr++; + } + return image->xsize; + /* NOTREACHED */ + + case 2: + cnt = image->xsize<<1; + if (img_read(image,(char *)(buffer),cnt) != cnt) { + i_errhdlr("getrow: error on read of row\n",0,0,0,0); + return -1; + } else { + if (image->dorev) + cvtshorts(buffer,cnt); + return image->xsize; + } + /* NOTREACHED */ + + default: + i_errhdlr("getrow: weird bpp\n",0,0,0,0); + break; + } + } else if (ISRLE(image->type)) { + switch (BPP(image->type)) { + case 1: + if ( (cnt = img_getrowsize(image)) == -1 ) + return -1; + if ( img_read(image,(char *)(image->tmpbuf),cnt) != cnt ) { + i_errhdlr("getrow: error on read of row\n",0,0,0,0); + return -1; + } else { + img_rle_expand(image->tmpbuf,1,buffer,2); + return image->xsize; + } + /* NOTREACHED */ + + case 2: + if ( (cnt = img_getrowsize(image)) == -1 ) + return -1; + if ( cnt != img_read(image,(char *)(image->tmpbuf),cnt) ) { + i_errhdlr("getrow: error on read of row\n",0,0,0,0); + return -1; + } else { + if (image->dorev) + cvtshorts(image->tmpbuf,cnt); + img_rle_expand(image->tmpbuf,2,buffer,2); + return image->xsize; + } + /* NOTREACHED */ + + default: + i_errhdlr("getrow: weird bpp\n",0,0,0,0); + break; + } + } else + i_errhdlr("getrow: weird image type\n",0,0,0,0); + return(-1) ; +} + +RGB_IMAGE *imgopen(int, const char *, const char *,unsigned int, unsigned int, unsigned int, unsigned int, unsigned int); + +RGB_IMAGE *iopen(const char *file, const char *mode, unsigned int type, unsigned int dim, unsigned int xsize, unsigned int ysize, unsigned int zsize) { + return(imgopen(0, file, mode, type, dim, xsize, ysize, zsize)); +} + +RGB_IMAGE *fiopen(int f, const char *mode, unsigned int type, unsigned int dim, unsigned int xsize, unsigned int ysize, unsigned int zsize) { + return(imgopen(f, 0, mode, type, dim, xsize, ysize, zsize)); +} + +RGB_IMAGE *imgopen(int f, const char *file, const char *mode, unsigned int type, unsigned int dim, unsigned int xsize, unsigned int ysize, unsigned int zsize) { + register RGB_IMAGE *image; + register int rw; + int tablesize; + register int i, max; + + image = (RGB_IMAGE*)calloc(1,sizeof(RGB_IMAGE)); + if (!image ) { + i_errhdlr("iopen: error on image struct alloc\n",0,0,0,0); + return NULL; + } + rw = mode[1] == '+'; + if (rw) { + i_errhdlr("iopen: read/write mode not supported\n",0,0,0,0); + return NULL; + } + if (*mode=='w') { + if (file) { + f = creat(file, 0666); + if (rw && f>=0) { + close(f); + f = open(file, 2); + } + } + if (f < 0) { + i_errhdlr("iopen: can't open output file %s\n",0,0,0,0); + return NULL; + } + image->imagic = IMAGIC; + image->type = type; + image->xsize = xsize; + image->ysize = 1; + image->zsize = 1; + if (dim>1) + image->ysize = ysize; + if (dim>2) + image->zsize = zsize; + if (image->zsize == 1) { + image->dim = 2; + if (image->ysize == 1) + image->dim = 1; + } else { + image->dim = 3; + } + image->min = 10000000; + image->max = 0; + isetname(image,"no name"); + image->wastebytes = 0; + image->dorev = 0; + swapImage(image) ; + if (write(f,image,sizeof(RGB_IMAGE)) != sizeof(RGB_IMAGE)) { + i_errhdlr("iopen: error on write of image header\n",0,0,0,0); + return NULL; + } + swapImage(image) ; + } else { + if (file) + f = open(file, rw? 2: 0); + if (f < 0) + return(NULL); + if (read(f,image,sizeof(RGB_IMAGE)) != sizeof(RGB_IMAGE)) { + i_errhdlr("iopen: error on read of image header\n",0,0,0,0); + return NULL; + } + if ( ((image->imagic>>8) | ((image->imagic&0xff)<<8)) + == IMAGIC ) { + image->dorev = 1; + cvtimage((long *)image); + } else + image->dorev = 0; + if (image->imagic != IMAGIC) { + i_errhdlr("iopen: bad magic in image file %x\n",image->imagic,0,0,0); + return NULL; + } + } + if (rw) + image->flags = _IORW; + else if (*mode != 'r') + image->flags = _IOWRT; + else + image->flags = _IOREAD; + if (ISRLE(image->type)) { + tablesize = image->ysize*image->zsize*sizeof(long); + image->rowstart = (unsigned int *)malloc(tablesize); + image->rowsize = (int *)malloc(tablesize); + if ( image->rowstart == 0 || image->rowsize == 0 ) { + i_errhdlr("iopen: error on table alloc\n",0,0,0,0); + return NULL; + } + image->rleend = 512L+2*tablesize; + if (*mode=='w') { + max = image->ysize*image->zsize; + for (i=0; irowstart[i] = 0; + image->rowsize[i] = -1; + } + } else { + tablesize = image->ysize*image->zsize*sizeof(long); + lseek(f, 512L, 0); + if (read(f,image->rowstart,tablesize) != tablesize) { + i_errhdlr("iopen: error on read of rowstart\n",0,0,0,0); + return NULL; + } + if (image->dorev) + cvtlongs((long *)image->rowstart,tablesize); + if (read(f,image->rowsize,tablesize) != tablesize) { + i_errhdlr("iopen: error on read of rowsize\n",0,0,0,0); + return NULL; + } + if (image->dorev) + cvtlongs((long *)image->rowsize,tablesize); + } + } + image->cnt = 0; + image->ptr = 0; + image->base = 0; + if ( (image->tmpbuf = ibufalloc(image)) == 0 ) { + i_errhdlr("iopen: error on tmpbuf alloc %d\n",image->xsize,0,0,0); + return NULL; + } + image->x = image->y = image->z = 0; + image->file = f; + image->offset = 512L; /* set up for img_optseek */ + lseek(image->file, 512L, 0); + return(image); +} + +unsigned short *ibufalloc(RGB_IMAGE *image) { + return (unsigned short *)malloc(IBUFSIZE(image->xsize)); +} + +long reverse(unsigned long lwrd) { + return ((lwrd>>24) | + (lwrd>>8 & 0xff00) | + (lwrd<<8 & 0xff0000) | + (lwrd<<24) ); +} + +void cvtshorts( unsigned short *buffer, long n) { + register short i; + register long nshorts = n>>1; + register unsigned short swrd; + + for (i=0; i>8) | (swrd<<8); + } +} + + +void cvtlongs( long *buffer, register long n) { + register short i; + register long nlongs = n>>2; + register unsigned long lwrd; + + for (i=0; i>24) | + (lwrd>>8 & 0xff00) | + (lwrd<<8 & 0xff0000) | + (lwrd<<24) ); + } +} + +void cvtimage( long *buffer) { + cvtshorts((unsigned short *)buffer,12); + cvtlongs(buffer+3,12); + cvtlongs(buffer+26,4); +} + +static void (*i_errfunc)(char *ebuf); + +/* error handler for the image library. If the iseterror() routine + has been called, sprintf's the args into a string and calls the + error function. Otherwise calls fprintf with the args and then + exit. This allows 'old' programs to assume that no errors + ever need be worried about, while programs that know how and + want to can handle the errors themselves. Olson, 11/88 +*/ +/* most args currently used is 2 */ +void i_errhdlr(const char *fmt, int a1, int a2, int a3, int a4) { + if (i_errfunc) { + char ebuf[2048]; /* be generous; if an error includes a + pathname, the maxlen is 1024, so we shouldn't ever + overflow this! */ + sprintf(ebuf, fmt, a1, a2, a3, a4); + (*i_errfunc)(ebuf); + return; + } + fprintf(stderr, fmt, a1, a2, a3, a4); + exit(1); +} + +/* this function sets the error handler for i_errhdlr */ +void i_seterror(void (*func)(char *)) { + i_errfunc = func; +} + +typedef union { + short s ; + char buf[sizeof(short)] ; +} SSWAP_SHORT ; + +typedef union { + float f ; + int i ; + char buf[4] ; + short s[2] ; +} SSWAP_LONG ; + +short tmpswapShort(short s) { + SSWAP_SHORT ss ; + char c ; + + /* first swap bytes in word */ + ss.s = s ; + c = ss.buf[0] ; + ss.buf[0] = ss.buf[1] ; + ss.buf[1] = c ; + + return(ss.s) ; +} + +int tmpswapInt(int i) { + SSWAP_LONG sl ; + short s ; + + /* first swap bytes in each word */ + sl.i = i ; + sl.s[0] = tmpswapShort(sl.s[0]) ; + sl.s[1] = tmpswapShort(sl.s[1]) ; + + /* now swap words */ + s = sl.s[0] ; + sl.s[0] = sl.s[1] ; + sl.s[1] = s ; + + return(sl.i) ; +} + +void swapImage(RGB_IMAGE *image) { +#if (BYTE_ORDER == LITTLE_ENDIAN) + image->imagic = tmpswapShort(image->imagic) ; + image->type = tmpswapShort(image->type) ; + image->dim = tmpswapShort(image->dim) ; + image->xsize = tmpswapShort(image->xsize) ; + image->ysize = tmpswapShort(image->ysize) ; + image->zsize = tmpswapShort(image->zsize) ; + image->min = tmpswapInt(image->min) ; + image->max = tmpswapInt(image->max) ; + image->wastebytes = tmpswapShort(image->wastebytes) ; + image->colormap = tmpswapInt(image->colormap) ; +#endif +} diff --git a/utils/romp_support.c b/utils/romp_support.cpp similarity index 82% rename from utils/romp_support.c rename to utils/romp_support.cpp index 889241a1c30..bc79d2ed5aa 100644 --- a/utils/romp_support.c +++ b/utils/romp_support.cpp @@ -24,6 +24,7 @@ static const int debug = 0; * */ #include "romp_support.h" +#include "base.h" #ifdef HAVE_MALLOC_H #include @@ -72,26 +73,26 @@ typedef struct PerThreadScopeTreeData { struct PerThreadScopeTreeData* parent; struct PerThreadScopeTreeData* next_sibling; struct PerThreadScopeTreeData* first_child; - Nanosecs in_scope; - Nanosecs in_child_threads[ROMP_maxWatchedThreadNum]; + long in_scope; + long in_child_threads[ROMP_maxWatchedThreadNum]; // threads may be running in a different scope tree! } PerThreadScopeTreeData; static PerThreadScopeTreeData scopeTreeRoots[ROMP_maxWatchedThreadNum]; static PerThreadScopeTreeData* scopeTreeToS [ROMP_maxWatchedThreadNum]; -static struct { NanosecsTimer timer; int inited; } tidStartTime[ROMP_maxWatchedThreadNum]; +static struct { Timer timer; bool inited = false; } tidStartTime[ROMP_maxWatchedThreadNum]; static void maybeInitTidStartTime(int tid) { if (tidStartTime[tid].inited) return; - TimerStartNanosecs(&tidStartTime[tid].timer); - tidStartTime[tid].inited = 1; + tidStartTime[tid].timer.reset(); + tidStartTime[tid].inited = true; } static PerThreadScopeTreeData* enterScope(PerThreadScopeTreeData* parent, ROMP_pf_static_struct* key) { PerThreadScopeTreeData** prev = &parent->first_child; while (*prev && (*prev)->key != key) { prev = &(*prev)->next_sibling; } // might need speeding up with a hash table if (!*prev) { - PerThreadScopeTreeData* ptr = calloc(1, sizeof(PerThreadScopeTreeData)); + PerThreadScopeTreeData* ptr = (PerThreadScopeTreeData *)calloc(1, sizeof(PerThreadScopeTreeData)); ptr->key = key; ptr->parent = parent; *prev = ptr; @@ -102,15 +103,15 @@ static PerThreadScopeTreeData* enterScope(PerThreadScopeTreeData* parent, ROMP_p typedef struct StaticData { ROMP_pf_static_struct* next; int skip_pflb_timing; - Nanosecs in_pf_sum, in_pfThread_sum, in_pflb_sum; + long in_pf_sum, in_pfThread_sum, in_pflb_sum; ROMP_level level; } StaticData; ROMP_pf_static_struct* known_ROMP_pf; -static Nanosecs cpuTimeUsed() { - clockid_t clockid; +static long cpuTimeUsed() { + clockid_t clockid = clockid_t(); int s = pthread_getcpuclockid(pthread_self(), &clockid); if (s != 0) { fprintf(stderr, "%s:%d pthread_getcpuclockid failed", __FILE__, __LINE__); @@ -127,7 +128,7 @@ static Nanosecs cpuTimeUsed() { fprintf(stderr, "%s:%d gettime failed", __FILE__, __LINE__); exit(1); } - Nanosecs t; t.ns = timespec.tv_sec * 1000000000L + timespec.tv_nsec; + long t = timespec.tv_sec * 1000000000L + timespec.tv_nsec; return t; } @@ -195,7 +196,7 @@ static void rompExitHandler(void) int tid; for (tid = 0; tid < ROMP_maxWatchedThreadNum; tid++) { PerThreadScopeTreeData* root = &scopeTreeRoots[tid]; - if (tidStartTime[tid].inited) root->in_scope = TimerElapsedNanosecs(&tidStartTime[tid].timer); + if (tidStartTime[tid].inited) root->in_scope = tidStartTime[tid].timer.nanoseconds(); } ROMP_show_stats(stderr); @@ -216,13 +217,13 @@ static void rompExitHandler(void) #endif } -static NanosecsTimer mainTimer; +static Timer mainTimer; static void initMainTimer() { static int once; if (once++ == 0) { - TimerStartNanosecs(&mainTimer); - atexit(rompExitHandler); + mainTimer.reset(); + atexit(rompExitHandler); } } @@ -251,14 +252,14 @@ static StaticData* initStaticData(ROMP_pf_static_struct * pf_static) omp_set_lock(&lock); #endif { // Might have been made by another thread - ptr = (StaticData*)pf_static->ptr; - if (!ptr) { - initMainTimer(); - ptr = (StaticData*)calloc(1, sizeof(StaticData)); - pf_static->ptr = ptr; - ptr->next = known_ROMP_pf; - known_ROMP_pf = pf_static; - } + ptr = (StaticData*)pf_static->ptr; + if (!ptr) { + initMainTimer(); + ptr = (StaticData*)calloc(1, sizeof(StaticData)); + pf_static->ptr = ptr; + ptr->next = known_ROMP_pf; + known_ROMP_pf = pf_static; + } } #ifdef HAVE_OPENMP omp_unset_lock(&lock); @@ -291,7 +292,7 @@ void ROMP_pf_begin( int i; for (i = 0; i < ROMP_maxWatchedThreadNum; i++) { - pf_stack->watchedThreadBeginCPUTimes[i].ns = 0; + pf_stack->watchedThreadBeginCPUTimes[i] = 0; } if (romp_level >= ROMP_level__size) { @@ -321,14 +322,13 @@ void ROMP_pf_begin( } for (i = 0; i < ROMP_maxWatchedThreadNum; i++) { - Nanosecs* startCPUTime = &pf_stack->watchedThreadBeginCPUTimes[i]; - if (startCPUTime->ns == 0) { + if (pf_stack->watchedThreadBeginCPUTimes[i] == 0) { if (debug) fprintf(stderr, "%s:%d no start time for %d\n", __FILE__, __LINE__, i); } } } - TimerStartNanosecs(&pf_stack->beginTime); + pf_stack->timer.reset(); } @@ -341,22 +341,22 @@ static void pf_end_one_thread(int tid, ROMP_pf_stack_struct * pf_stack, PerThrea 0; #endif if (childTid >= ROMP_maxWatchedThreadNum) return; - - Nanosecs* startCPUTime = &pf_stack->watchedThreadBeginCPUTimes[childTid]; - if (startCPUTime->ns == -1) { + + long &startCPUTime = pf_stack->watchedThreadBeginCPUTimes[childTid]; + if (startCPUTime == -1) { return; } - if (startCPUTime->ns == 0) { + if (startCPUTime == 0) { if (debug) fprintf(stderr, "%s:%d no corresponding start time for tid:%d pf_stack:%p\n", __FILE__, __LINE__, tid, pf_stack); return; } - Nanosecs threadCpuTime; - threadCpuTime.ns = cpuTimeUsed().ns - startCPUTime->ns; - startCPUTime->ns = -1; // copes when another iteration of this loop is executed on the same thread + long threadCpuTime; + threadCpuTime = cpuTimeUsed() - startCPUTime; + startCPUTime = -1; // copes when another iteration of this loop is executed on the same thread - if (debug) fprintf(stderr, "Adding to tid:%d childTid:%d ns:%ld\n", tid, childTid, threadCpuTime.ns); - tos->in_child_threads[childTid].ns += threadCpuTime.ns; + if (debug) fprintf(stderr, "Adding to tid:%d childTid:%d ns:%ld\n", tid, childTid, threadCpuTime); + tos->in_child_threads[childTid] += threadCpuTime; } @@ -372,44 +372,44 @@ void ROMP_pf_end( #else 0; #endif - if (tid >= ROMP_maxWatchedThreadNum) goto Done; - - PerThreadScopeTreeData* tos = scopeTreeToS[tid]; - if (!tos) goto Done; - - Nanosecs delta = TimerElapsedNanosecs(&pf_stack->beginTime); - - tos->in_scope.ns += delta.ns; - - if (pf_stack->gone_parallel) - if (debug) fprintf(stderr, "ROMP_pf_end tid:%d pf_stack:%p getting other thread times\n", - omp_get_thread_num(), pf_stack); - - if (!pf_stack->gone_parallel) { - // Not the same as putting a condition on the else loop - // The later is implemented by openmp choosing any available thread to execute the loop body, not the current thread - pf_end_one_thread(tid, pf_stack, tos); - } else { - int i; - #ifdef HAVE_OPENMP - #pragma omp parallel for schedule(static,1) - #endif - for (i = 0; i < ROMP_maxWatchedThreadNum; i++) pf_end_one_thread(tid, pf_stack, tos); - } + if (tid < ROMP_maxWatchedThreadNum) { + + PerThreadScopeTreeData* tos = scopeTreeToS[tid]; + if (tos) { + + long delta = pf_stack->timer.nanoseconds(); + tos->in_scope += delta; + + if (pf_stack->gone_parallel) + if (debug) fprintf(stderr, "ROMP_pf_end tid:%d pf_stack:%p getting other thread times\n", + omp_get_thread_num(), pf_stack); + + if (!pf_stack->gone_parallel) { + // Not the same as putting a condition on the else loop + // The later is implemented by openmp choosing any available thread to execute the loop body, not the current thread + pf_end_one_thread(tid, pf_stack, tos); + } else { + int i; + #ifdef HAVE_OPENMP + #pragma omp parallel for schedule(static,1) + #endif + for (i = 0; i < ROMP_maxWatchedThreadNum; i++) pf_end_one_thread(tid, pf_stack, tos); + } - if (romp_level < ROMP_level__size) { - int i; - for (i = 0; i < ROMP_maxWatchedThreadNum; i++) { - Nanosecs* startCPUTime = &pf_stack->watchedThreadBeginCPUTimes[i]; - if (startCPUTime->ns != 0 && startCPUTime->ns != -1) { - if (debug) fprintf(stderr, "%s:%d no end time for %d\n", __FILE__, __LINE__, tid); + if (romp_level < ROMP_level__size) { + int i; + for (i = 0; i < ROMP_maxWatchedThreadNum; i++) { + long startCPUTime = pf_stack->watchedThreadBeginCPUTimes[i]; + if (startCPUTime != 0 && startCPUTime != -1) { + if (debug) fprintf(stderr, "%s:%d no end time for %d\n", __FILE__, __LINE__, tid); + } + } } - } + + scopeTreeToS[tid] = tos->parent; + } } - - scopeTreeToS[tid] = tos->parent; -Done: romp_level = pf_stack->entry_level; } @@ -430,14 +430,14 @@ static void node_show_stats(FILE* file, PerThreadScopeTreeData* node, unsigned i ROMP_pf_static_struct* pf = node->key; StaticData* sd = pf ? (StaticData*)(pf->ptr) : (StaticData*)(NULL); - Nanosecs inAllThreads; inAllThreads.ns = 0; + long inAllThreads; inAllThreads = 0; int tid; for (tid = 0; tid < ROMP_maxWatchedThreadNum; tid++) { - inAllThreads.ns += node->in_child_threads[tid].ns; + inAllThreads += node->in_child_threads[tid]; } - { int d; - for (d = 0; d < depth; d++) fprintf(file, " "); + { + for (unsigned int d = 0; d < depth; d++) fprintf(file, " "); } fprintf(file, "%s:%s, %d, %d, %12ld, %12ld, %12ld, %6.3g, %6.3g\n", @@ -445,8 +445,8 @@ static void node_show_stats(FILE* file, PerThreadScopeTreeData* node, unsigned i pf ? pf->func : "", pf ? pf->line : 0, sd ? sd->level : 0, - node->in_scope.ns, 0L, inAllThreads.ns, - 0.0, (double)inAllThreads.ns/(double)node->in_scope.ns); + node->in_scope, 0L, inAllThreads, + 0.0, (double)inAllThreads/(double)node->in_scope); PerThreadScopeTreeData* child; for (child = node->first_child; child; child = child->next_sibling) { @@ -456,16 +456,13 @@ static void node_show_stats(FILE* file, PerThreadScopeTreeData* node, unsigned i void ROMP_show_stats(FILE* file) { - fprintf(file, "ROMP_show_stats %s\n", current_date_time_noOverride()); + fprintf(file, "ROMP_show_stats %s\n", currentDateTime(false).c_str()); fprintf(file, "file, line, level, in pf, in pflb, in_pfThread, pflb/elapsed, pft/elapsed\n"); if (getMainFile()) { - Nanosecs mainDuration = TimerElapsedNanosecs(&mainTimer); - fprintf(file, "%s, %d, 0, %12ld, %12ld, %12ld, %6.3g, %6.3g\n", - mainFile, mainLine, - mainDuration.ns, 0L, 0L, - 1.0, - 1.0); + long mainDuration = mainTimer.nanoseconds(); + fprintf(file, "%s, %d, 0, %12ld, %12ld, %12ld, %6.3g, %6.3g\n", mainFile, mainLine, + mainDuration, 0L, 0L, 1.0, 1.0); } int tid; diff --git a/utils/selxavgio.c b/utils/selxavgio.cpp similarity index 100% rename from utils/selxavgio.c rename to utils/selxavgio.cpp diff --git a/utils/sig.c b/utils/sig.cpp similarity index 100% rename from utils/sig.c rename to utils/sig.cpp diff --git a/utils/signa.c b/utils/signa.cpp similarity index 100% rename from utils/signa.c rename to utils/signa.cpp diff --git a/utils/sort.c b/utils/sort.cpp similarity index 100% rename from utils/sort.c rename to utils/sort.cpp diff --git a/utils/stats.c b/utils/stats.cpp similarity index 99% rename from utils/stats.c rename to utils/stats.cpp index b882629c4c7..c29719843fa 100644 --- a/utils/stats.c +++ b/utils/stats.cpp @@ -296,7 +296,8 @@ SV *StatReadVolume(const char *prefix) char path[STRLEN], fname[STRLEN], line[MAX_LINE_LEN], *cp; STAT_VOLUME *sv; FILE *fp; - int dof_mean, dof_sigma, event_number, slice_number, which_alloc, width, height, nframes, nslices, t, event, nitems, + unsigned int nitems; + int dof_mean, dof_sigma, event_number, slice_number, which_alloc, width, height, nframes, nslices, t, event, x, y, z; float *buf, fval; int DatVersion, DOF; @@ -1164,7 +1165,8 @@ int StatWriteVolume(SV *sv, const char *prefix) { char path[STRLEN], fname[STRLEN]; FILE *fp; - int event_number, width, height, nslices, t, event, nitems, x, y, z, nframes; + unsigned int nitems; + int event_number, width, height, nslices, t, event, x, y, z, nframes; float *buf, fval; width = sv->slice_width; diff --git a/utils/stc.c b/utils/stc.c deleted file mode 100644 index e0abd53a604..00000000000 --- a/utils/stc.c +++ /dev/null @@ -1,202 +0,0 @@ -/** - * @file stc.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.5 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include - -#include "const.h" -#include "error.h" -#include "fio.h" -#include "matrix.h" -#include "proto.h" -#include "stc.h" - -int StcWrite(char *fname, MATRIX *m_data, float epoch_begin_lat, float sample_period, int *vertices, int nvertices) -{ - int vno, ntime, row, col; - FILE *fp; - float val; - - ntime = m_data->cols; - -#if 0 - sprintf(fname,"%s.stc",fstem); -#endif - fp = fopen(fname, "w"); - if (fp == NULL) ErrorReturn(ERROR_NOFILE, (ERROR_NOFILE, "MRISwriteStc: can't open file %s\n", fname)); - - fwriteFloat(epoch_begin_lat, fp); - fwriteFloat(sample_period, fp); - fwriteInt(nvertices, fp); - for (vno = 0; vno < nvertices; vno++) fwriteInt(vertices[vno], fp); - - fwriteInt(ntime, fp); - for (col = 1; col <= m_data->cols; col++) { - for (row = 1; row <= m_data->rows; row++) { - /* row is dipole, and col is time */ - val = *MATRIX_RELT(m_data, row, col); - fwriteFloat(val, fp); - } - } - fclose(fp); - printf("sol timecourse file %s written\n", fname); - return (NO_ERROR); -} - -STC_FILE *StcOpen(char *fstem) -{ - STC_FILE *stc_file; - char fname[STRLEN]; - int vno; - - stc_file = (STC_FILE *)calloc(1, sizeof(STC_FILE)); - - sprintf(fname, "%s.stc", fstem); - stc_file->file_handle = fopen(fname, "r"); - if (stc_file->file_handle == NULL) ErrorReturn(NULL, (ERROR_NOFILE, "StcRead: could not open %s", fname)); - - stc_file->epoch_begin_lat = freadFloat(stc_file->file_handle); - stc_file->sample_period = freadFloat(stc_file->file_handle); - stc_file->nvertices = freadInt(stc_file->file_handle); - stc_file->vertices = (int *)calloc(stc_file->nvertices, sizeof(int)); - if (!stc_file->vertices) - ErrorExit(ERROR_NOMEMORY, "StcRead(%s): could not allocated %d vector", fname, stc_file->nvertices); - - for (vno = 0; vno < stc_file->nvertices; vno++) { - stc_file->vertices[vno] = freadInt(stc_file->file_handle); - } - stc_file->ntimepts = freadInt(stc_file->file_handle); - - return stc_file; -} - -void StcClose(STC_FILE *stc_file) -{ - if (stc_file->file_handle) fclose(stc_file->file_handle); - - if (stc_file->vertices) { - free(stc_file->vertices); - stc_file->vertices = 0; - stc_file->nvertices = 0; - } -} - -STC_FRAME *StcReadFrame(int fno, STC_FILE *stc_file) -{ - STC_FRAME *stc; - int baseoffset, offset; - int framesize, vno; - - assert(stc_file->file_handle); - - stc = (STC_FRAME *)calloc(1, sizeof(STC_FRAME)); - - stc->nperdip = stc_file->nperdip; - stc->ndipoles = stc_file->ndipoles; - stc->nvertices = stc_file->nvertices; - - baseoffset = 12 + 4 * stc_file->nvertices + 4; - framesize = 4 * stc_file->ndipoles * stc_file->nperdip; - offset = baseoffset + fno * framesize; - fseek(stc_file->file_handle, offset, SEEK_SET); - - stc->m_vals = MatrixAlloc(stc->nperdip * stc->nvertices, 1, MATRIX_REAL); - - if (!stc->m_vals) - ErrorExit( - ERROR_NOMEMORY, "StcReadFrame could not allocate %dx%d matrix", stc_file->nperdip * stc_file->nvertices, 1); - - for (vno = 0; vno < stc->m_vals->rows; vno++) { - *MATRIX_RELT(stc->m_vals, vno + 1, 1) = freadFloat(stc_file->file_handle); - } - - return stc; -} - -STC *StcRead(char *fstem) -{ - int j, vno; - char fname[STRLEN]; - FILE *fp; - STC *stc; - long here, there; - - stc = (STC *)calloc(1, sizeof(STC)); - - sprintf(fname, "%s.stc", fstem); - fp = fopen(fname, "r"); - if (fp == NULL) ErrorReturn(NULL, (ERROR_NOFILE, "StcRead: could not open %s", fname)); - - stc->epoch_begin_lat = freadFloat(fp); - stc->sample_period = freadFloat(fp); - stc->nvertices = freadInt(fp); - printf("StcRead: epoch_begin_lat=%f, sample_period=%f, nvertices=%d\n", - stc->epoch_begin_lat, - stc->sample_period, - stc->nvertices); - stc->vertices = (int *)calloc(stc->nvertices, sizeof(int)); - if (!stc->vertices) ErrorExit(ERROR_NOMEMORY, "StcRead(%s): could not allocated %d vector", fname, stc->nvertices); - - for (vno = 0; vno < stc->nvertices; vno++) { - stc->vertices[vno] = freadInt(fp); - } - stc->ntimepts = freadInt(fp); - printf("ntime=%d\n", stc->ntimepts); - here = ftell(fp); - fseek(fp, 0L, SEEK_END); - there = ftell(fp); - fseek(fp, here, SEEK_SET); - - stc->ndipoles = nint((there - here) / (sizeof(float)) / stc->ntimepts); - stc->nperdip = nint(stc->ndipoles / (float)stc->nvertices); - fprintf(stderr, "%d dipoles detected - %d per location\n", stc->ndipoles, stc->nperdip); - - stc->m_vals = MatrixAlloc(stc->nperdip * stc->nvertices, stc->ntimepts, MATRIX_REAL); - if (!stc->m_vals) - ErrorExit(ERROR_NOMEMORY, - "StcRead(%s) could not allocate %dx%d matrix", - fname, - stc->nperdip * stc->nvertices, - stc->ntimepts); - - for (j = 0; j < stc->ntimepts; j++) { - for (vno = 0; vno < stc->m_vals->rows; vno++) { - *MATRIX_RELT(stc->m_vals, vno + 1, j + 1) = freadFloat(fp); - } - } - fclose(fp); - /* printf("soltimecourse file %s read\n",fname); */ - return (stc); -} - -void StcFree(STC *stc) -{ - if (stc->vertices) free(stc->vertices); - if (stc->m_vals) MatrixFree(&stc->m_vals); - - free(stc); -} diff --git a/utils/surfcluster.c b/utils/surfcluster.cpp similarity index 99% rename from utils/surfcluster.c rename to utils/surfcluster.cpp index 760a0bdb7c8..936056e1510 100644 --- a/utils/surfcluster.c +++ b/utils/surfcluster.cpp @@ -398,14 +398,13 @@ SCS *SurfClusterSummaryFast(MRI_SURFACE *Surf, MATRIX *T, int *nClusters) SURFCLUSTERSUM *scs; MATRIX *xyz, *xyzxfm; float vtxarea, vtxval; - struct timeb mytimer; int msecTime; double *weightvtx, *weightarea; // to be consistent with orig code VERTEX *v; if (Gdiag_no > 0) printf("SurfClusterSummaryFast()\n"); - TimerStart(&mytimer); + Timer mytimer; *nClusters = sclustCountClusters(Surf); if (*nClusters == 0) return (NULL); @@ -488,7 +487,7 @@ SCS *SurfClusterSummaryFast(MRI_SURFACE *Surf, MATRIX *T, int *nClusters) MatrixFree(&xyzxfm); free(weightvtx); free(weightarea); - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); if (Gdiag_no > 0) printf("SurfClusterSumFast: n=%d, t = %g\n", *nClusters, msecTime / 1000.0); return (scs); @@ -501,9 +500,8 @@ SCS *SurfClusterSummary(MRI_SURFACE *Surf, MATRIX *T, int *nClusters) SURFCLUSTERSUM *scs; MATRIX *xyz, *xyzxfm; double centroidxyz[3]; - struct timeb mytimer; int msecTime; - char *UFSS; + const char *UFSS; // Must explicity "setenv USE_FAST_SURF_SMOOTHER 0" to turn off fast UFSS = getenv("USE_FAST_SURF_SMOOTHER"); @@ -514,7 +512,7 @@ SCS *SurfClusterSummary(MRI_SURFACE *Surf, MATRIX *T, int *nClusters) } if (Gdiag_no > 0) printf("SurfClusterSummary()\n"); - TimerStart(&mytimer); + Timer mytimer; *nClusters = sclustCountClusters(Surf); if (*nClusters == 0) return (NULL); @@ -559,7 +557,7 @@ SCS *SurfClusterSummary(MRI_SURFACE *Surf, MATRIX *T, int *nClusters) MatrixFree(&xyz); MatrixFree(&xyzxfm); - msecTime = TimerStop(&mytimer); + msecTime = mytimer.milliseconds(); if (Gdiag_no > 0) printf("SurfClusterSum: n=%d, t = %g\n", *nClusters, msecTime / 1000.0); return (scs); diff --git a/utils/surfgrad.c b/utils/surfgrad.cpp similarity index 100% rename from utils/surfgrad.c rename to utils/surfgrad.cpp diff --git a/utils/svm.c b/utils/svm.cpp similarity index 100% rename from utils/svm.c rename to utils/svm.cpp diff --git a/utils/tags.c b/utils/tags.cpp similarity index 99% rename from utils/tags.c rename to utils/tags.cpp index 6e9509b0cc8..bd9ced73457 100644 --- a/utils/tags.c +++ b/utils/tags.cpp @@ -31,6 +31,7 @@ #include "machine.h" #include "tags.h" + int TAGskip(FILE *fp, int tag, long long len) { #if 1 diff --git a/utils/talairachex.c b/utils/talairachex.cpp similarity index 100% rename from utils/talairachex.c rename to utils/talairachex.cpp diff --git a/utils/test/MRISresampleOntoSphere.cpp b/utils/test/MRISresampleOntoSphere.cpp index 4d7204d6076..4290e51ed07 100644 --- a/utils/test/MRISresampleOntoSphere.cpp +++ b/utils/test/MRISresampleOntoSphere.cpp @@ -78,7 +78,7 @@ int main(int argc, char *argv[]) { int nargs, msec, order, i; - struct timeb then ; + Timer then ; MRIS *mris_in, *mris_out; double volume; // T[5][5] the transformation matrx (using index 1-4) @@ -97,7 +97,7 @@ main(int argc, char *argv[]) ErrorExit(ERROR_BADPARM, "usage: %s ", Progname); - TimerStart(&then) ; + then.reset() ; //order = atoi (argv[3]); order = 7; @@ -165,7 +165,7 @@ main(int argc, char *argv[]) MRISfree(&mris_out) ; } - msec = TimerStop(&then) ; + msec = then.milliseconds() ; fprintf(stdout, "spherical sampling took %2.1f minutes\n", (float)msec/(1000.0f*60.0f)); exit(0) ; return(0) ; diff --git a/utils/test/MRISwaveletsTransform.cpp b/utils/test/MRISwaveletsTransform.cpp index f6cf8d2f27f..3dcda64f1c5 100644 --- a/utils/test/MRISwaveletsTransform.cpp +++ b/utils/test/MRISwaveletsTransform.cpp @@ -110,7 +110,7 @@ int main(int argc, char *argv[]) { int nargs, msec, order, i, number; - struct timeb then ; + Timer then ; MRIS *mris_in, *mris_out; double volume; // T[5][5] the transformation matrx (using index 1-4) @@ -129,7 +129,7 @@ main(int argc, char *argv[]) ErrorExit(ERROR_BADPARM, "usage: %s ", Progname); - TimerStart(&then) ; + then.reset() ; //order = atoi (argv[3]); order = 7; @@ -780,7 +780,7 @@ main(int argc, char *argv[]) } MRISfree(&mris_out); - msec = TimerStop(&then) ; + msec = then.milliseconds() ; fprintf(stdout, "spherical wavelet took %2.1f minutes\n", (float)msec/(1000.0f*60.0f)); exit(0) ; return(0) ; diff --git a/utils/test/mri_concatenate_lta.c b/utils/test/mri_concatenate_lta.c index aaee187268a..47a11d388d9 100644 --- a/utils/test/mri_concatenate_lta.c +++ b/utils/test/mri_concatenate_lta.c @@ -477,7 +477,7 @@ LTA *ltaMNIreadEx(const char *fname) } -#include "minc_volume_io.h" +#include "minc.h" int ltaMNIwrite(LTA *lta, char *fname) { diff --git a/utils/test/mri_ms_LDA.c b/utils/test/mri_ms_LDA.c index 973e3e56b41..7215a5c5abf 100644 --- a/utils/test/mri_ms_LDA.c +++ b/utils/test/mri_ms_LDA.c @@ -137,7 +137,7 @@ main(int argc, char *argv[]) int ac, nargs, i, j, x, y, z, width, height, depth; MRI *mri_flash[MAX_IMAGES], *mri_label, *mri_mask, *mri_tmp; int msec, minutes, seconds, nvolumes, nvolumes_total ; - struct timeb start ; + Timer start ; float max_val, min_val, value; float *LDAmean1, *LDAmean2, *LDAweight; int label; @@ -156,7 +156,7 @@ main(int argc, char *argv[]) ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; - TimerStart(&start) ; + start.reset() ; ac = argc ; av = argv ; @@ -526,7 +526,7 @@ main(int argc, char *argv[]) free(LDAmean2); free(LDAweight); - msec = TimerStop(&start) ; + msec = start.milliseconds() ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; diff --git a/utils/test/mri_ms_compute_CNR.c b/utils/test/mri_ms_compute_CNR.c index 50345d98865..7efa7331d1c 100644 --- a/utils/test/mri_ms_compute_CNR.c +++ b/utils/test/mri_ms_compute_CNR.c @@ -151,7 +151,7 @@ main(int argc, char *argv[]) MRI *mri_flash[MAX_IMAGES], *mri_label, *mri_mask; int index; int msec, minutes, seconds, nvolumes, nvolumes_total ; - struct timeb start ; + Timer start ; float max_val, min_val, value; float *LDAweight = NULL; float **LDAmeans = NULL; /* Centroid for each considered class */ @@ -175,7 +175,7 @@ main(int argc, char *argv[]) ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; - TimerStart(&start) ; + start.reset() ; ac = argc ; av = argv ; @@ -654,7 +654,7 @@ main(int argc, char *argv[]) free(LDAweight); - msec = TimerStop(&start) ; + msec = start.milliseconds() ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; diff --git a/utils/test/mri_ms_gca_EM.c b/utils/test/mri_ms_gca_EM.c index 1c8e242a790..52a6d0de7dc 100644 --- a/utils/test/mri_ms_gca_EM.c +++ b/utils/test/mri_ms_gca_EM.c @@ -162,7 +162,7 @@ main(int argc, char *argv[]) MRI *mri_flash[MAX_IMAGES], *mri_mem[MAX_CLASSES], *mri_mask, *mri_label, *mri_tmp; char *out_prefx ; int msec, minutes, seconds, nvolumes, nvolumes_total, label ; - struct timeb start ; + Timer start ; MATRIX *F[MAX_CLASSES]; float *centroids[MAX_CLASSES]; float value; @@ -193,7 +193,7 @@ main(int argc, char *argv[]) DiagInit(NULL, NULL, NULL) ; - TimerStart(&start) ; + start.reset() ; ac = argc ; av = argv ; @@ -768,7 +768,7 @@ main(int argc, char *argv[]) MRIfree(&mri_tmp); } - msec = TimerStop(&start) ; + msec = start.milliseconds() ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; diff --git a/utils/test/mris_indirect_morph.cpp b/utils/test/mris_indirect_morph.cpp index 50f5ccb8fee..3251e49196b 100644 --- a/utils/test/mris_indirect_morph.cpp +++ b/utils/test/mris_indirect_morph.cpp @@ -122,7 +122,7 @@ int main(int argc, char *argv[]) char **av, *in_surf_fname, *out_fname; int fno, vno0, vno1, vno2; int nargs, ac, msec; - struct timeb then; + Timer then; MRI_SURFACE *mris, *mris_template, *mris_template_map; FACE *face; @@ -136,7 +136,7 @@ int main(int argc, char *argv[]) exit (0); argc -= nargs; - TimerStart(&then) ; + then.reset() ; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; @@ -341,7 +341,7 @@ int main(int argc, char *argv[]) MRISfree(&mris); MRISfree(&mris_template); - msec = TimerStop(&then) ; + msec = then.milliseconds() ; fprintf(stderr, "indirect spherical mapping or morphing took %2.2f hours\n", (float)msec/(1000.0f*60.0f*60.0f)); diff --git a/utils/test/sse_mathfun_test.c b/utils/test/sse_mathfun_test.c deleted file mode 100644 index d9f78db7830..00000000000 --- a/utils/test/sse_mathfun_test.c +++ /dev/null @@ -1,1183 +0,0 @@ -/* -results on a macbook with 1.83GHz Core 1 Duo (apple gcc 4.0.1) -command line: gcc -O2 -Wall -W -DHAVE_VECLIB -msse sse_mathfun_test.c -framework Accelerate - -checking sines on [0*Pi, 1*Pi] -max deviation from sinf(x): 5.96046e-08 at 0.679296388013*Pi, max deviation from cephes_sin(x): 0 -max deviation from cosf(x): 5.96046e-08 at 0.755605310477*Pi, max deviation from cephes_cos(x): 0 -deviation of sin(x)^2+cos(x)^2-1: 1.78814e-07 (ref deviation is 1.19209e-07) - ->> precision OK for the sin_ps / cos_ps / sincos_ps <<- - -checking sines on [-1000*Pi, 1000*Pi] -max deviation from sinf(x): 5.96046e-08 at 1821.37678456*Pi, max deviation from cephes_sin(x): 0 -max deviation from cosf(x): 5.96046e-08 at -999.820056289*Pi, max deviation from cephes_cos(x): 0 -deviation of sin(x)^2+cos(x)^2-1: 1.78814e-07 (ref deviation is 1.19209e-07) - ->> precision OK for the sin_ps / cos_ps / sincos_ps <<- - -checking exp/log [-60, 60] -max (relative) deviation from expf(x): 1.18758e-07 at 45.0583610535, max deviation from cephes_expf(x): 0 -max (absolute) deviation from logf(x): 1.19209e-07 at 1.66063511372, max deviation from cephes_logf(x): 0 -deviation of x - log(exp(x)): 1.19209e-07 (ref deviation is 5.96046e-08) - ->> precision OK for the exp_ps / log_ps <<- - -exp([ -1000, -100, 100, 1000]) = [ 0, 0, -2.4061436e+38, 2.4061436e+38] exp([ nan, inf, -inf, nan]) = -[2.4061436e+38, 2.4061436e+38, 0, 2.4061436e+38] log([ 0, -10, -1e+30, 1.0005271e-42]) = [ nan, nan, 69.077553, -87.336548] log([ nan, inf, --inf, nan]) = [ -87.336548, 88.722839, nan, -87.336548] sin([ nan, inf, --inf, nan]) = [ nan, nan, nan, nan] cos([ nan, inf, --inf, nan]) = [ nan, nan, nan, nan] sin([ -1e+30, -100000, -1e+30, 100000]) = [ inf, -0.035749275, -inf, 0.035749275] cos([ -1e+30, -100000, -1e+30, 100000]) = [ nan, -0.9993608, nan, -0.9993608] benching sinf .. --> 3.2 millions of vector evaluations/second -> 142 cycles/value on a 1830MHz computer benching cosf -.. -> 3.2 millions of vector evaluations/second -> 142 cycles/value on a 1830MHz computer benching sincos -(x87) .. -> 2.8 millions of vector evaluations/second -> 161 cycles/value on a 1830MHz computer benching -expf .. -> 3.0 millions of vector evaluations/second -> 148 cycles/value on a 1830MHz computer benching -logf .. -> 3.0 millions of vector evaluations/second -> 150 cycles/value on a 1830MHz computer benching -cephes_sinf .. -> 4.5 millions of vector evaluations/second -> 100 cycles/value on a 1830MHz computer benching -cephes_cosf .. -> 4.9 millions of vector evaluations/second -> 92 cycles/value on a 1830MHz computer benching -cephes_expf .. -> 3.0 millions of vector evaluations/second -> 151 cycles/value on a 1830MHz computer benching -cephes_logf .. -> 2.6 millions of vector evaluations/second -> 172 cycles/value on a 1830MHz computer benching -sin_ps .. -> 18.1 millions of vector evaluations/second -> 25 cycles/value on a 1830MHz computer benching -cos_ps .. -> 18.2 millions of vector evaluations/second -> 25 cycles/value on a 1830MHz computer benching -sincos_ps .. -> 15.0 millions of vector evaluations/second -> 30 cycles/value on a 1830MHz computer benching -exp_ps .. -> 17.6 millions of vector evaluations/second -> 26 cycles/value on a 1830MHz computer benching -log_ps .. -> 15.5 millions of vector evaluations/second -> 29 cycles/value on a 1830MHz computer benching -vsinf .. -> 14.3 millions of vector evaluations/second -> 32 cycles/value on a 1830MHz computer benching -vcosf .. -> 14.4 millions of vector evaluations/second -> 32 cycles/value on a 1830MHz computer benching -vexpf .. -> 12.0 millions of vector evaluations/second -> 38 cycles/value on a 1830MHz computer benching -vlogf .. -> 13.1 millions of vector evaluations/second -> 35 cycles/value on a 1830MHz computer - - -on a 2600MHz opteron running linux, with the 64 bits acml math vector lib (gcc 4.2): -command line: gcc-4.2 -msse -O3 -Wall -W sse_mathfun_test.c -lm -DHAVE_ACML -I /usr/local/acml3.6.0/pathscale64/include -/usr/local/acml3.6.0/pathscale64/lib/libacml_mv.a - -benching sinf .. -> 6.3 millions of vector evaluations/second -> 103 cycles/value on a 2600MHz -computer benching cosf .. -> 5.6 millions of vector evaluations/second -> 115 cycles/value on a -2600MHz computer benching sincos (x87) .. -> 4.2 millions of vector evaluations/second -> 153 cycles/value on -a 2600MHz computer benching expf .. -> 1.1 millions of vector evaluations/second -> 546 cycles/value -on a 2600MHz computer benching logf .. -> 4.7 millions of vector evaluations/second -> 138 -cycles/value on a 2600MHz computer benching cephes_sinf .. -> 11.6 millions of vector evaluations/second -> -56 cycles/value on a 2600MHz computer benching cephes_cosf .. -> 8.7 millions of vector evaluations/second --> 74 cycles/value on a 2600MHz computer benching cephes_expf .. -> 3.7 millions of vector -evaluations/second -> 172 cycles/value on a 2600MHz computer benching cephes_logf .. -> 5.5 millions of -vector evaluations/second -> 117 cycles/value on a 2600MHz computer benching sin_ps .. -> 26.1 millions -of vector evaluations/second -> 25 cycles/value on a 2600MHz computer benching cos_ps .. -> 26.1 -millions of vector evaluations/second -> 25 cycles/value on a 2600MHz computer benching sincos_ps .. -> -23.7 millions of vector evaluations/second -> 27 cycles/value on a 2600MHz computer benching exp_ps .. --> 22.9 millions of vector evaluations/second -> 28 cycles/value on a 2600MHz computer benching log_ps -.. -> 21.6 millions of vector evaluations/second -> 30 cycles/value on a 2600MHz computer benching acml -vrs4_sinf .. -> 17.9 millions of vector evaluations/second -> 36 cycles/value on a 2600MHz computer benching -acml vrs4_cosf .. -> 18.3 millions of vector evaluations/second -> 35 cycles/value on a 2600MHz computer benching -acml vrs4_expf .. -> 28.6 millions of vector evaluations/second -> 23 cycles/value on a 2600MHz computer benching -acml vrs4_logf .. -> 23.6 millions of vector evaluations/second -> 27 cycles/value on a 2600MHz computer - -on a 2GHz athlon-xp 2400+ , using mingw (gcc 3.4.5) -command line: gcc -mfpmath=sse -msse -O2 -Wall -W sse_mathfun_test.c -benching sinf .. -> 3.4 millions of vector evaluations/second -> 144 cycles/value on a 2000MHz -computer benching cosf .. -> 5.1 millions of vector evaluations/second -> 97 cycles/value on a -2000MHz computer benching sincos (x87) .. -> 2.3 millions of vector evaluations/second -> 214 cycles/value on -a 2000MHz computer benching expf .. -> 1.8 millions of vector evaluations/second -> 272 cycles/value -on a 2000MHz computer benching logf .. -> 2.5 millions of vector evaluations/second -> 200 -cycles/value on a 2000MHz computer benching cephes_sinf .. -> 3.7 millions of vector evaluations/second -> -132 cycles/value on a 2000MHz computer benching cephes_cosf .. -> 3.2 millions of vector evaluations/second --> 153 cycles/value on a 2000MHz computer benching cephes_expf .. -> 1.2 millions of vector -evaluations/second -> 407 cycles/value on a 2000MHz computer benching cephes_logf .. -> 1.4 millions of -vector evaluations/second -> 355 cycles/value on a 2000MHz computer benching sin_ps .. -> 17.2 millions -of vector evaluations/second -> 29 cycles/value on a 2000MHz computer benching cos_ps .. -> 17.0 -millions of vector evaluations/second -> 29 cycles/value on a 2000MHz computer benching sincos_ps .. -> -14.7 millions of vector evaluations/second -> 34 cycles/value on a 2000MHz computer benching exp_ps .. --> 17.2 millions of vector evaluations/second -> 29 cycles/value on a 2000MHz computer benching log_ps -.. -> 14.7 millions of vector evaluations/second -> 34 cycles/value on a 2000MHz computer - - -on the same 2GHz athlon-xp 2400+ , using cl.exe (visual c++ express 2005) -command line: cl.exe //arch:SSE //O2 //TP //MD sse_mathfun_test.c - -benching sinf .. -> 3.1 millions of vector evaluations/second -> 160 cycles/value on a 2000MHz -computer benching cosf .. -> 3.9 millions of vector evaluations/second -> 127 cycles/value on a -2000MHz computer benching sincos (x87) .. -> 2.8 millions of vector evaluations/second -> 175 cycles/value on -a 2000MHz computer benching expf .. -> 2.0 millions of vector evaluations/second -> 239 cycles/value -on a 2000MHz computer benching logf .. -> 2.6 millions of vector evaluations/second -> 192 -cycles/value on a 2000MHz computer benching cephes_sinf .. -> 2.5 millions of vector evaluations/second -> -198 cycles/value on a 2000MHz computer benching cephes_cosf .. -> 2.8 millions of vector evaluations/second --> 176 cycles/value on a 2000MHz computer benching cephes_expf .. -> 0.9 millions of vector -evaluations/second -> 546 cycles/value on a 2000MHz computer benching cephes_logf .. -> 1.3 millions of -vector evaluations/second -> 370 cycles/value on a 2000MHz computer benching sin_ps .. -> 17.2 millions -of vector evaluations/second -> 29 cycles/value on a 2000MHz computer benching cos_ps .. -> 17.3 -millions of vector evaluations/second -> 29 cycles/value on a 2000MHz computer benching sincos_ps .. -> -15.5 millions of vector evaluations/second -> 32 cycles/value on a 2000MHz computer benching exp_ps .. --> 17.8 millions of vector evaluations/second -> 28 cycles/value on a 2000MHz computer benching log_ps -.. -> 10.4 millions of vector evaluations/second -> 48 cycles/value on a 2000MHz computer - -*/ - -#include -#include - -/* useful when debuggin.. */ -void print4(__m128 v) -{ - float *p = (float *)&v; -#ifndef USE_SSE2 - _mm_empty(); -#endif - printf("[%13.8g, %13.8g, %13.8g, %13.8g]", p[0], p[1], p[2], p[3]); -} - -void print2i(__m64 v) -{ - unsigned *p = (unsigned *)&v; - printf("[%08x %08x]", p[0], p[1]); -} - -#ifdef USE_SSE2 -#include -void print4i(__m128i v) -{ - unsigned *p = (unsigned *)&v; - printf("[%08x %08x %08x %08x]", p[0], p[1], p[2], p[3]); -} -#endif - -#include -#include -#include -#include -#include "sse_mathfun.h" - -#ifdef HAVE_SYS_TIMES -#include -#include -#endif - -#ifdef HAVE_VECLIB -#include -#endif -#ifdef HAVE_ACML -#include -#endif - -typedef ALIGN16_BEG union { - float f[4]; - int i[4]; - v4sf v; -} ALIGN16_END V4SF; - -#define MAX(a, b) (((a) > (b)) ? (a) : (b)) - -double frand() { return rand() / (double)RAND_MAX; } - -#if defined(HAVE_SYS_TIMES) -inline double uclock_sec(void) -{ - static double ttclk = 0.; - if (ttclk == 0.) ttclk = sysconf(_SC_CLK_TCK); - struct tms t; - return ((double)times(&t)) / ttclk; -} -#else -inline double uclock_sec(void) { return (double)clock() / (double)CLOCKS_PER_SEC; } -#endif - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -#ifndef M_LN2 -#define M_LN2 0.69314718055994530942 -#endif - -int bitdiff(float a, float b) -{ - if (a == b) - return 24; - else if (a == 0) { - int j = -log(fabs(b)) / M_LN2; - if (j > 24) j = 24; - return j; - } - else - return log(fabs(a)) / M_LN2 - log(fabs(b - a)) / M_LN2; -} - -/* they are defined at the bottom of the file */ -float cephes_sinf(float); -float cephes_cosf(float); -float cephes_logf(float); -float cephes_expf(float); - -int check_sincos_precision(float xmin, float xmax) -{ - unsigned nb_trials = 100000; - printf("checking sines on [%g*Pi, %g*Pi]\n", xmin, xmax); - - float max_err_sin_ref = 0, max_err_sin_cep = 0, max_err_sin_x = 0; - float max_err_cos_ref = 0, max_err_cos_cep = 0, max_err_cos_x = 0; - float max_err_sum_sqr_test = 0; - float max_err_sum_sqr_ref = 0; - xmin *= M_PI; - xmax *= M_PI; - unsigned i; - for (i = 0; i < nb_trials; ++i) { - V4SF vx, sin4, cos4, sin4_2, cos4_2; - vx.f[0] = i * (xmax - xmin) / (nb_trials - 1) + xmin; - vx.f[1] = (i + .5) * (xmax - xmin) / (nb_trials - 1) + xmin; - vx.f[2] = frand() * (xmax - xmin); - vx.f[3] = (i / 32) * M_PI / ((i % 32) + 1); - if (vx.f[3] < xmin || vx.f[3] > xmax) vx.f[3] = frand() * (xmax - xmin); - - /* - vx.f[0] = M_PI/2; - vx.f[1] = M_PI; - vx.f[2] = M_PI/3; - vx.f[3] = M_PI/4; - */ - sin4.v = sin_ps(vx.v); - cos4.v = cos_ps(vx.v); - sincos_ps(vx.v, &sin4_2.v, &cos4_2.v); - unsigned j; - for (j = 0; j < 4; ++j) { - float x = vx.f[j]; - float sin_test = sin4.f[j]; - float cos_test = cos4.f[j]; - if (sin_test != sin4_2.f[j]) { - printf("sin / sincos mismatch at x=%g\n", x); - exit(1); - return 1; - } - if (cos_test != cos4_2.f[j]) { - printf("cos / sincos mismatch at x=%g\n", x); - return 1; - } - float sin_ref = sinf(x); - float sin_cep = cephes_sinf(x); - float err_sin_ref = fabs(sin_ref - sin_test); - float err_sin_cep = fabs(sin_cep - sin_test); - if (err_sin_ref > max_err_sin_ref) { - max_err_sin_ref = err_sin_ref; - max_err_sin_x = x; - } - max_err_sin_cep = MAX(max_err_sin_cep, err_sin_cep); - float cos_ref = cosf(x); - float cos_cep = cephes_cosf(x); - float err_cos_ref = fabs(cos_ref - cos_test); - float err_cos_cep = fabs(cos_cep - cos_test); - if (err_cos_ref > max_err_cos_ref) { - max_err_cos_ref = err_cos_ref; - max_err_cos_x = x; - } - max_err_cos_cep = MAX(max_err_cos_cep, err_cos_cep); - float err_sum_sqr_test = fabs(1 - cos_test * cos_test - sin_test * sin_test); - float err_sum_sqr_ref = fabs(1 - cos_ref * cos_ref - sin_ref * sin_ref); - max_err_sum_sqr_ref = MAX(max_err_sum_sqr_ref, err_sum_sqr_ref); - max_err_sum_sqr_test = MAX(max_err_sum_sqr_test, err_sum_sqr_test); - // printf("sin(%g) = %g %g err=%g\n", x, sin_ref, sin_test, err_sin_ref); - } - } - printf("max deviation from sinf(x): %g at %14.12g*Pi, max deviation from cephes_sin(x): %g\n", - max_err_sin_ref, - max_err_sin_x / M_PI, - max_err_sin_cep); - printf("max deviation from cosf(x): %g at %14.12g*Pi, max deviation from cephes_cos(x): %g\n", - max_err_cos_ref, - max_err_cos_x / M_PI, - max_err_cos_cep); - - printf("deviation of sin(x)^2+cos(x)^2-1: %g (ref deviation is %g)\n", max_err_sum_sqr_test, max_err_sum_sqr_ref); - - if (max_err_sum_sqr_ref < 2e-7 && max_err_sin_ref < 2e-7 && max_err_cos_ref < 2e-7) { - printf(" ->> precision OK for the sin_ps / cos_ps / sincos_ps <<-\n\n"); - return 0; - } - else { - printf("\n WRONG PRECISION !! there is a problem\n\n"); - return 1; - } -} - -union float_int_union { - int i; - float f; -} QNAN = {0xFFC00000}, QNAN2 = {0x7FC00000}, PINF = {0x7F800000}, MINF = {0xFF800000}; - -int check_explog_precision(float xmin, float xmax) -{ - unsigned nb_trials = 100000; - printf("checking exp/log [%g, %g]\n", xmin, xmax); - - float max_err_exp_ref = 0, max_err_exp_cep = 0, max_err_exp_x = 0; - float max_err_log_ref = 0, max_err_log_cep = 0, max_err_log_x = 0; - float max_err_logexp_test = 0; - float max_err_logexp_ref = 0; - unsigned i; - for (i = 0; i < nb_trials; ++i) { - V4SF vx, exp4, log4; - vx.f[0] = frand() * (xmax - xmin) + xmin; - vx.f[1] = frand() * (xmax - xmin) + xmin; - vx.f[2] = frand() * (xmax - xmin) + xmin; - vx.f[3] = frand() * (xmax - xmin) + xmin; - exp4.v = exp_ps(vx.v); - log4.v = log_ps(exp4.v); - unsigned j; - for (j = 0; j < 4; ++j) { - float x = vx.f[j]; - float exp_test = exp4.f[j]; - float log_test = log4.f[j]; - float exp_ref = expf(x); - float exp_cep = cephes_expf(x); - float err_exp_ref = fabs(exp_ref - exp_test) / exp_ref; - float err_exp_cep = fabs(exp_cep - exp_test) / exp_ref; - if (err_exp_ref > max_err_exp_ref) { - max_err_exp_ref = err_exp_ref; - max_err_exp_x = x; - } - max_err_exp_cep = MAX(max_err_exp_cep, err_exp_cep); - - float log_ref = logf(exp_test); - float log_cep = cephes_logf(exp_test); - float err_log_ref = fabs(log_ref - log_test); - float err_log_cep = fabs(log_cep - log_test); - if (err_log_ref > max_err_log_ref) { - max_err_log_ref = err_log_ref; - max_err_log_x = x; - } - max_err_log_cep = MAX(max_err_log_cep, err_log_cep); - float err_logexp_test = fabs(x - log_test); - float err_logexp_ref = fabs(x - logf(expf(x))); - max_err_logexp_ref = MAX(max_err_logexp_ref, err_logexp_ref); - max_err_logexp_test = MAX(max_err_logexp_test, err_logexp_test); - } - } - printf("max (relative) deviation from expf(x): %g at %14.12g, max deviation from cephes_expf(x): %g\n", - max_err_exp_ref, - max_err_exp_x, - max_err_exp_cep); - printf("max (absolute) deviation from logf(x): %g at %14.12g, max deviation from cephes_logf(x): %g\n", - max_err_log_ref, - max_err_log_x, - max_err_log_cep); - - printf("deviation of x - log(exp(x)): %g (ref deviation is %g)\n", max_err_logexp_test, max_err_logexp_ref); - - if (max_err_logexp_test < 2e-7 && max_err_exp_ref < 2e-7 && max_err_log_ref < 2e-7) { - printf(" ->> precision OK for the exp_ps / log_ps <<-\n\n"); - return 0; - } - else { - printf("\n WRONG PRECISION !! there is a problem\n\n"); - return 1; - } -} - -void dumb() -{ - V4SF x = {{0.0903333798051, 0.0903333798051, 0.0903333798051, 0.0903333798051}}; - V4SF w; - w.v = log_ps(x.v); - float z = cephes_logf(x.f[0]); - printf("log_ps returned "); - print4(w.v); - printf("\ncephes returned: %14.12g and logf(%g)=%14.12g\n", z, x.f[0], logf(x.f[0])); - - print4(_mm_cmpeq_ps(x.v, x.v)); - printf("\n"); - exit(1); -} - -void check_special_values() -{ - V4SF vx; - vx.f[0] = -1000; - vx.f[1] = -100; - vx.f[2] = 100; - vx.f[3] = 1000; - printf("exp("); - print4(vx.v); - printf(") = "); - print4(exp_ps(vx.v)); - printf("\n"); - vx.f[0] = QNAN.f; - vx.f[1] = PINF.f; - vx.f[2] = MINF.f; - vx.f[3] = QNAN2.f; - printf("exp("); - print4(vx.v); - printf(") = "); - print4(exp_ps(vx.v)); - printf("\n"); - vx.f[0] = 0; - vx.f[1] = -10; - vx.f[2] = 1e30f; - vx.f[3] = 1e-42f; - printf("log("); - print4(vx.v); - printf(") = "); - print4(log_ps(vx.v)); - printf("\n"); - vx.f[0] = QNAN.f; - vx.f[1] = PINF.f; - vx.f[2] = MINF.f; - vx.f[3] = QNAN2.f; - printf("log("); - print4(vx.v); - printf(") = "); - print4(log_ps(vx.v)); - printf("\n"); - printf("sin("); - print4(vx.v); - printf(") = "); - print4(sin_ps(vx.v)); - printf("\n"); - printf("cos("); - print4(vx.v); - printf(") = "); - print4(cos_ps(vx.v)); - printf("\n"); - vx.f[0] = -1e30; - vx.f[1] = -100000; - vx.f[2] = 1e30; - vx.f[3] = 100000; - printf("sin("); - print4(vx.v); - printf(") = "); - print4(sin_ps(vx.v)); - printf("\n"); - printf("cos("); - print4(vx.v); - printf(") = "); - print4(cos_ps(vx.v)); - printf("\n"); -} - -#define DECL_SCALAR_FN_BENCH(fn) \ - int bench_##fn() \ - { \ - int niter = 10000, i, j; \ - float x = 0.5f, y = 0; \ - for (i = 0; i < niter; ++i) { \ - for (j = 0; j < 4; ++j) { \ - x += 1e-6f; \ - y += fn(x + 5 * (j & 1)); \ - } \ - } \ - if (y == 2.32132323232f) niter--; \ - return niter; \ - } - -#define DECL_VECTOR_FN_BENCH(fn) \ - int bench_##fn() \ - { \ - int niter = 10000, i; \ - v4sf bmin = _mm_set_ps1(0.5), bmax = _mm_set_ps1(1.0); \ - v4sf x = _mm_set_ps1(0.75); \ - for (i = 0; i < niter; ++i) { \ - x = fn(x); \ - x = _mm_min_ps(x, bmax); \ - x = _mm_max_ps(x, bmin); \ - } \ - if (((float *)&x)[0] == 2.32132323232f) niter--; \ - return niter; \ - } - -#ifdef __GNUC__ -#define HAVE_SINCOS_X86_FPU -void sincos_x86_fpu(double t, double *st, double *ct) -{ - asm("fsincos;" : "=t"(*ct), "=u"(*st) : "0"(t) : "st(7)"); - //*st = sin(t); *ct = cos(t); -} -#elif defined(_MSC_VER) && !defined(_WIN64) -#define HAVE_SINCOS_X86_FPU -void sincos_x86_fpu(double t, double *st_, double *ct_) -{ - _asm { - fld QWORD PTR [t] - fsincos - mov ebx,[ct_] - fstp QWORD PTR [ebx] - mov ebx,[st_] - fstp QWORD PTR [ebx] - } -} -#endif - -#ifdef HAVE_SINCOS_X86_FPU -float stupid_sincos_x86_fpu(float x) -{ - double s, c; - sincos_x86_fpu(x, &s, &c); - return s + c; -} -#endif - -v4sf stupid_sincos_ps(v4sf x) -{ - v4sf s, c; - sincos_ps(x, &s, &c); - return s; -} - -DECL_SCALAR_FN_BENCH(sinf); -DECL_SCALAR_FN_BENCH(cosf); -#ifdef HAVE_SINCOS_X86_FPU -DECL_SCALAR_FN_BENCH(stupid_sincos_x86_fpu); -#endif -DECL_SCALAR_FN_BENCH(logf); -DECL_SCALAR_FN_BENCH(expf); -DECL_SCALAR_FN_BENCH(cephes_sinf); -DECL_SCALAR_FN_BENCH(cephes_cosf); -DECL_SCALAR_FN_BENCH(cephes_expf); -DECL_SCALAR_FN_BENCH(cephes_logf); -DECL_VECTOR_FN_BENCH(sin_ps); -DECL_VECTOR_FN_BENCH(cos_ps); -DECL_VECTOR_FN_BENCH(stupid_sincos_ps); -DECL_VECTOR_FN_BENCH(exp_ps); -DECL_VECTOR_FN_BENCH(log_ps); -#ifdef HAVE_VECLIB -DECL_VECTOR_FN_BENCH(vsinf); -DECL_VECTOR_FN_BENCH(vcosf); -DECL_VECTOR_FN_BENCH(vlogf); -DECL_VECTOR_FN_BENCH(vexpf); -#endif -#ifdef HAVE_ACML -DECL_VECTOR_FN_BENCH(__vrs4_sinf); -DECL_VECTOR_FN_BENCH(__vrs4_cosf); -DECL_VECTOR_FN_BENCH(__vrs4_expf); -DECL_VECTOR_FN_BENCH(__vrs4_logf); -#endif - -void run_bench(const char *s, int (*fn)()) -{ - printf("benching %20s ..", s); - fflush(stdout); - double t0 = uclock_sec(), t1, tmax = 1.0; - double niter = 0; - do { - niter += fn(); - t1 = uclock_sec(); - } while (t1 - t0 < tmax); -#define REF_FREQ_MHZ 2000.0 - printf(" -> %6.1f millions of vector evaluations/second -> %3.0f cycles/value on a %gMHz computer\n", - floor(niter / (t1 - t0) / 1e5) / 10, - (t1 - t0) * REF_FREQ_MHZ * 1e6 / niter / 4, - REF_FREQ_MHZ); -} - -void sanity_check() -{ - printf("doing some sanity checks...\n"); -#ifndef USE_SSE2 - V4SF v = {{1, 2, 3, 4}}, z = {{5, 6, 7, 8}}; - v2si mm0, mm1; - COPY_XMM_TO_MM(v.v, mm0, mm1); - COPY_MM_TO_XMM(mm0, mm1, v.v); - printf("truncation to int: "); - print2i(mm0); - print2i(mm1); - printf("\n"); - _mm_empty(); - printf("float vector: "); - print4(v.v); - printf("\n"); - fflush(stdout); - assert(v.f[0] == 1); - assert(v.f[1] == 2); - assert(v.f[2] == 3); - assert(v.f[3] == 4); - - V4SF w; - w.v = v.v; - // printf("float vector: "); print4(w); printf("\n"); - mm0 = _mm_cvttps_pi32(w.v); - w.v = _mm_movehl_ps(w.v, w.v); - mm1 = _mm_cvttps_pi32(w.v); - /*_mm_empty(); - printf("truncation to int: "); print2i(mm0); print2i(mm1); printf("\n"); - */ - w.v = _mm_cvtpi32x2_ps(mm0, mm1); - print2i(((v2si *)&w.v)[0]); - print2i(((v2si *)&w.v)[1]); - _mm_empty(); - v.v = w.v; - assert((((long)&v.v) & 0xf) == 0); - printf("converted back to float: "); - print4(v.v); - printf("\n"); - fflush(stdout); - assert(v.f[0] == 1); - assert(v.f[1] == 2); - assert(v.f[2] == 3); - assert(v.f[3] == 4); - - w.v = _mm_movehl_ps(z.v, w.v); - printf("test for _mm_movehl_ps bug..\n"); - print4(w.v); - printf("\n"); - fflush(stdout); - if (w.f[0] != 3 || w.f[1] != 4 || w.f[2] != 7 || w.f[3] != 8) { - printf("your compiler has the nasty bug on _mm_movehl_ps: IT IS BROKEN\n"); - exit(1); - } - - printf("test for _mm_cmpxx_ps bug..\n"); - V4SF r; - r.v = _mm_cmplt_ps(w.v, w.v); - if (r.i[0] != 0 || r.i[1] != 0 || r.i[2] != 0 || r.i[3] != 0) { - printf("your compiler has the nasty bug on all _mm_cmp*_ps functions: IT IS BROKEN\n"); - exit(1); - } - r.v = _mm_cmpeq_ps(w.v, w.v); - if (r.i[0] != -1 || r.i[1] != -1 || r.i[2] != -1 || r.i[3] != -1) { - printf("your compiler has the nasty bug on all _mm_cmp*_ps functions: IT IS BROKEN\n"); - exit(1); - } -#endif // USE_SSE2 -} - -int main() -{ - // dumb(); - // sanity_check(); - int err = 0; - err += check_sincos_precision(0., 1.0); - err += check_sincos_precision(-1000, 1000); - err += check_explog_precision(-60, 60); - - if (err) { - printf("some precision tests have failed\n"); - } - - check_special_values(); - run_bench("sinf", bench_sinf); - run_bench("cosf", bench_cosf); -#ifdef HAVE_SINCOS_X86_FPU - run_bench("sincos (x87)", bench_stupid_sincos_x86_fpu); -#endif - run_bench("expf", bench_expf); - run_bench("logf", bench_logf); - - run_bench("cephes_sinf", bench_cephes_sinf); - run_bench("cephes_cosf", bench_cephes_cosf); - run_bench("cephes_expf", bench_cephes_expf); - run_bench("cephes_logf", bench_cephes_logf); - - run_bench("sin_ps", bench_sin_ps); - run_bench("cos_ps", bench_cos_ps); - run_bench("sincos_ps", bench_stupid_sincos_ps); - run_bench("exp_ps", bench_exp_ps); - run_bench("log_ps", bench_log_ps); - -#ifdef HAVE_VECLIB - run_bench("vsinf", bench_vsinf); - run_bench("vcosf", bench_vcosf); - run_bench("vexpf", bench_vexpf); - run_bench("vlogf", bench_vlogf); -#endif -#ifdef HAVE_ACML - run_bench("acml vrs4_sinf", bench___vrs4_sinf); - run_bench("acml vrs4_cosf", bench___vrs4_cosf); - run_bench("acml vrs4_expf", bench___vrs4_expf); - run_bench("acml vrs4_logf", bench___vrs4_logf); -#endif - return err; -} - -/* cephes functions, copied here to serve as a reference */ - -/* sinf.c - * - * Circular sine - * - * - * - * SYNOPSIS: - * - * float x, y, sinf(); - * - * y = sinf( x ); - * - * - * - * DESCRIPTION: - * - * Range reduction is into intervals of pi/4. The reduction - * error is nearly eliminated by contriving an extended precision - * modular arithmetic. - * - * Two polynomial approximating functions are employed. - * Between 0 and pi/4 the sine is approximated by - * x + x**3 P(x**2). - * Between pi/4 and pi/2 the cosine is represented as - * 1 - x**2 Q(x**2). - * - * - * ACCURACY: - * - * Relative error: - * arithmetic domain # trials peak rms - * IEEE -4096,+4096 100,000 1.2e-7 3.0e-8 - * IEEE -8192,+8192 100,000 3.0e-7 3.0e-8 - * - * ERROR MESSAGES: - * - * message condition value returned - * sin total loss x > 2^24 0.0 - * - * Partial loss of accuracy begins to occur at x = 2^13 - * = 8192. Results may be meaningless for x >= 2^24 - * The routine as implemented flags a TLOSS error - * for x >= 2^24 and returns 0.0. - */ - -/* cosf.c - * - * Circular cosine - * - * - * - * SYNOPSIS: - * - * float x, y, cosf(); - * - * y = cosf( x ); - * - * - * - * DESCRIPTION: - * - * Range reduction is into intervals of pi/4. The reduction - * error is nearly eliminated by contriving an extended precision - * modular arithmetic. - * - * Two polynomial approximating functions are employed. - * Between 0 and pi/4 the cosine is approximated by - * 1 - x**2 Q(x**2). - * Between pi/4 and pi/2 the sine is represented as - * x + x**3 P(x**2). - * - * - * ACCURACY: - * - * Relative error: - * arithmetic domain # trials peak rms - * IEEE -8192,+8192 100,000 3.0e-7 3.0e-8 - */ - -/* -Cephes Math Library Release 2.2: June, 1992 -Copyright 1985, 1987, 1988, 1992 by Stephen L. Moshier -Direct inquiries to 30 Frost Street, Cambridge, MA 02140 -*/ - -/* Single precision circular sine - * test interval: [-pi/4, +pi/4] - * trials: 10000 - * peak relative error: 6.8e-8 - * rms relative error: 2.6e-8 - */ - -static float FOPI = 1.27323954473516; -static float PIO4F = 0.7853981633974483096; -/* Note, these constants are for a 32-bit significand: */ -/* - static float DP1 = 0.7853851318359375; - static float DP2 = 1.30315311253070831298828125e-5; - static float DP3 = 3.03855025325309630e-11; - static float lossth = 65536.; -*/ - -/* These are for a 24-bit significand: */ -static float DP1 = 0.78515625; -static float DP2 = 2.4187564849853515625e-4; -static float DP3 = 3.77489497744594108e-8; -static float lossth = 8192.; -static float T24M1 = 16777215.; - -static float sincof[] = {-1.9515295891E-4, 8.3321608736E-3, -1.6666654611E-1}; -static float coscof[] = {2.443315711809948E-005, -1.388731625493765E-003, 4.166664568298827E-002}; - -float cephes_sinf(float xx) -{ - float *p; - float x, y, z; - register unsigned long j; - register int sign; - - sign = 1; - x = xx; - if (xx < 0) { - sign = -1; - x = -xx; - } - if (x > T24M1) { - // mtherr( "sinf", TLOSS ); - return (0.0); - } - j = FOPI * x; /* integer part of x/(PI/4) */ - y = j; - /* map zeros to origin */ - if (j & 1) { - j += 1; - y += 1.0; - } - j &= 7; /* octant modulo 360 degrees */ - /* reflect in x axis */ - if (j > 3) { - sign = -sign; - j -= 4; - } - if (x > lossth) { - // mtherr( "sinf", PLOSS ); - x = x - y * PIO4F; - } - else { - /* Extended precision modular arithmetic */ - x = ((x - y * DP1) - y * DP2) - y * DP3; - } - /*einits();*/ - z = x * x; - // printf("my_sinf: corrected oldx, x, y = %14.10g, %14.10g, %14.10g\n", oldx, x, y); - if ((j == 1) || (j == 2)) { - /* measured relative error in +/- pi/4 is 7.8e-8 */ - /* - y = (( 2.443315711809948E-005 * z - - 1.388731625493765E-003) * z - + 4.166664568298827E-002) * z * z; - */ - p = coscof; - y = *p++; - y = y * z + *p++; - y = y * z + *p++; - y *= z; - y *= z; - y -= 0.5 * z; - y += 1.0; - } - else { - /* Theoretical relative error = 3.8e-9 in [-pi/4, +pi/4] */ - /* - y = ((-1.9515295891E-4 * z - + 8.3321608736E-3) * z - - 1.6666654611E-1) * z * x; - y += x; - */ - p = sincof; - y = *p++; - y = y * z + *p++; - y = y * z + *p++; - y *= z; - y *= x; - y += x; - } - /*einitd();*/ - // printf("my_sinf: j=%d result = %14.10g * %d\n", j, y, sign); - if (sign < 0) y = -y; - return (y); -} - -/* Single precision circular cosine - * test interval: [-pi/4, +pi/4] - * trials: 10000 - * peak relative error: 8.3e-8 - * rms relative error: 2.2e-8 - */ - -float cephes_cosf(float xx) -{ - float x, y, z; - int j, sign; - - /* make argument positive */ - sign = 1; - x = xx; - if (x < 0) x = -x; - - if (x > T24M1) { - // mtherr( "cosf", TLOSS ); - return (0.0); - } - - j = FOPI * x; /* integer part of x/PIO4 */ - y = j; - /* integer and fractional part modulo one octant */ - if (j & 1) /* map zeros to origin */ - { - j += 1; - y += 1.0; - } - j &= 7; - if (j > 3) { - j -= 4; - sign = -sign; - } - - if (j > 1) sign = -sign; - - if (x > lossth) { - // mtherr( "cosf", PLOSS ); - x = x - y * PIO4F; - } - else - /* Extended precision modular arithmetic */ - x = ((x - y * DP1) - y * DP2) - y * DP3; - - // printf("xx = %g -> x corrected = %g sign=%d j=%d y=%g\n", xx, x, sign, j, y); - - z = x * x; - - if ((j == 1) || (j == 2)) { - y = (((-1.9515295891E-4f * z + 8.3321608736E-3f) * z - 1.6666654611E-1f) * z * x) + x; - } - else { - y = ((2.443315711809948E-005f * z - 1.388731625493765E-003f) * z + 4.166664568298827E-002f) * z * z; - y -= 0.5 * z; - y += 1.0; - } - if (sign < 0) y = -y; - return (y); -} - -/* expf.c - * - * Exponential function - * - * - * - * SYNOPSIS: - * - * float x, y, expf(); - * - * y = expf( x ); - * - * - * - * DESCRIPTION: - * - * Returns e (2.71828...) raised to the x power. - * - * Range reduction is accomplished by separating the argument - * into an integer k and fraction f such that - * - * x k f - * e = 2 e. - * - * A polynomial is used to approximate exp(f) - * in the basic range [-0.5, 0.5]. - * - * - * ACCURACY: - * - * Relative error: - * arithmetic domain # trials peak rms - * IEEE +- MAXLOG 100000 1.7e-7 2.8e-8 - * - * - * Error amplification in the exponential function can be - * a serious matter. The error propagation involves - * exp( X(1+delta) ) = exp(X) ( 1 + X*delta + ... ), - * which shows that a 1 lsb error in representing X produces - * a relative error of X times 1 lsb in the function. - * While the routine gives an accurate result for arguments - * that are exactly represented by a double precision - * computer number, the result contains amplified roundoff - * error for large arguments not exactly represented. - * - * - * ERROR MESSAGES: - * - * message condition value returned - * expf underflow x < MINLOGF 0.0 - * expf overflow x > MAXLOGF MAXNUMF - * - */ - -/* -Cephes Math Library Release 2.2: June, 1992 -Copyright 1984, 1987, 1989 by Stephen L. Moshier -Direct inquiries to 30 Frost Street, Cambridge, MA 02140 -*/ - -/* Single precision exponential function. - * test interval: [-0.5, +0.5] - * trials: 80000 - * peak relative error: 7.6e-8 - * rms relative error: 2.8e-8 - */ - -static float MAXNUMF = 3.4028234663852885981170418348451692544e38; -static float MAXLOGF = 88.72283905206835; -static float MINLOGF = -103.278929903431851103; /* log(2^-149) */ - -static float LOG2EF = 1.44269504088896341; - -static float C1 = 0.693359375; -static float C2 = -2.12194440e-4; - -float cephes_expf(float xx) -{ - float x, z; - int n; - - x = xx; - - if (x > MAXLOGF) { - // mtherr( "expf", OVERFLOW ); - return (MAXNUMF); - } - - if (x < MINLOGF) { - // mtherr( "expf", UNDERFLOW ); - return (0.0); - } - - /* Express e**x = e**g 2**n - * = e**g e**( n loge(2) ) - * = e**( g + n loge(2) ) - */ - z = floorf(LOG2EF * x + 0.5); /* floor() truncates toward -infinity. */ - - x -= z * C1; - x -= z * C2; - n = z; - - z = x * x; - /* Theoretical peak relative error in [-0.5, +0.5] is 4.2e-9. */ - z = (((((1.9875691500E-4f * x + 1.3981999507E-3f) * x + 8.3334519073E-3f) * x + 4.1665795894E-2f) * x + - 1.6666665459E-1f) * - x + - 5.0000001201E-1f) * - z + - x + 1.0; - - /* multiply by power of 2 */ - x = ldexpf(z, n); - - return (x); -} - -/* logf.c - * - * Natural logarithm - * - * - * - * SYNOPSIS: - * - * float x, y, logf(); - * - * y = logf( x ); - * - * - * - * DESCRIPTION: - * - * Returns the base e (2.718...) logarithm of x. - * - * The argument is separated into its exponent and fractional - * parts. If the exponent is between -1 and +1, the logarithm - * of the fraction is approximated by - * - * log(1+x) = x - 0.5 x**2 + x**3 P(x) - * - * - * - * ACCURACY: - * - * Relative error: - * arithmetic domain # trials peak rms - * IEEE 0.5, 2.0 100000 7.6e-8 2.7e-8 - * IEEE 1, MAXNUMF 100000 2.6e-8 - * - * In the tests over the interval [1, MAXNUM], the logarithms - * of the random arguments were uniformly distributed over - * [0, MAXLOGF]. - * - * ERROR MESSAGES: - * - * logf singularity: x = 0; returns MINLOG - * logf domain: x < 0; returns MINLOG - */ - -/* -Cephes Math Library Release 2.2: June, 1992 -Copyright 1984, 1987, 1988, 1992 by Stephen L. Moshier -Direct inquiries to 30 Frost Street, Cambridge, MA 02140 -*/ - -/* Single precision natural logarithm - * test interval: [sqrt(2)/2, sqrt(2)] - * trials: 10000 - * peak relative error: 7.1e-8 - * rms relative error: 2.7e-8 - */ -float LOGE2F = 0.693147180559945309; -float SQRTHF = 0.707106781186547524; -float PIF = 3.141592653589793238; -float PIO2F = 1.5707963267948966192; -float MACHEPF = 5.9604644775390625E-8; - -float cephes_logf(float xx) -{ - register float y; - float x, z, fe; - int e; - - x = xx; - fe = 0.0; - /* Test for domain */ - if (x <= 0.0) { - // ERROR - return (MINLOGF); - } - - x = frexpf(x, &e); - // printf("\nmy_logf: frexp -> e = %d x = %g\n", e, x); - if (x < SQRTHF) { - e -= 1; - x = x + x - 1.0; /* 2x - 1 */ - } - else { - x = x - 1.0; - } - z = x * x; - /* 3.4e-9 */ - /* - p = logfcof; - y = *p++ * x; - for( i=0; i<8; i++ ) - { - y += *p++; - y *= x; - } - y *= z; - */ - - y = ((((((((7.0376836292E-2f * x - 1.1514610310E-1f) * x + 1.1676998740E-1f) * x - 1.2420140846E-1f) * x + - 1.4249322787E-1f) * - x - - 1.6668057665E-1f) * - x + - 2.0000714765E-1f) * - x - - 2.4999993993E-1f) * - x + - 3.3333331174E-1f) * - x * z; - - // printf("my_logf: poly = %g\n", y); - - if (e) { - fe = e; - y += -2.12194440e-4f * fe; - } - y += -0.5 * z; /* y - 0.5 x^2 */ - - // printf("my_logf: x = %g y = %g\n", x, y); - z = x + y; /* ... + x */ - - if (e) z += 0.693359375f * fe; - - return (z); -} diff --git a/utils/thread.c b/utils/thread.c deleted file mode 100644 index 3c5b70e96de..00000000000 --- a/utils/thread.c +++ /dev/null @@ -1,449 +0,0 @@ -/** - * @file thread.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -/* - @(#)thread.c 1.3 - 4/7/94 -*/ -/*------------------------------------------------------------------------ - File Name: thread.c - - Author: Bruce Fischl - - Created: Jan. 1994 - - Description: Generic multi-threading utility. Does not contain any - platform-specific code. - -------------------------------------------------------------------------*/ - -#include -#include -#include - -#include "error.h" -#include "mailbox.h" -#include "mthread.h" -#include "queue.h" -#include "thread.h" - -/*------------------------------------------------------------------------ - CONSTANTS -------------------------------------------------------------------------*/ - -#define QSIZE 20 - -/*------------------------------------------------------------------------ - STRUCTURES -------------------------------------------------------------------------*/ - -typedef struct -{ - char *name; - int iMtid; /* machine specific id of this thread */ - int iSusSignal; - QUEUE *inQ; /* input queue for thread */ -} THREAD; - -/*------------------------------------------------------------------------ - GLOBAL DATA -------------------------------------------------------------------------*/ - -int iDone = 0; /* will cause shutdown when set to 1 */ - -/*------------------------------------------------------------------------ - STATIC DATA -------------------------------------------------------------------------*/ - -static int iMaxThreads = 0; /* max allowable # of threads */ -static int iNthreads = 0; /* number of current threads */ -static THREAD *pthrTable; -static int iMachineId = 0; - -/*------------------------------------------------------------------------ - FUNCTIONS -------------------------------------------------------------------------*/ - -/*------------------------------------------------------------------------ - Parameters: - - Description: - initialize the thread utility, setting up a hard maximum on - the number of allowable threads. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadInit(int mid, int iMaxThr, int stacksize, int npriorities) -{ - THREAD *thread; - int iError; - - iMaxThreads = iMaxThr + 1; - pthrTable = (THREAD *)calloc(iMaxThreads, sizeof(THREAD)); - if (!pthrTable) return (ErrorSet(ERROR_NO_MEMORY, "ThreadInit(%d, %d) - could not allocate table\n", mid, iMaxThr)); - - iMachineId = mid; - iError = MachThreadInit(iMaxThr, stacksize, npriorities); - if (iError < 0) return (iError); - - /* thread #0 is reserved for main */ - thread = &pthrTable[iNthreads++]; - thread->name = "main"; - thread->iMtid = MachThreadGetTid(); - thread->inQ = Qalloc(QSIZE); - return (0); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Kill the thread specified by the iTid field. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadEnd(int iTid) -{ - int iMtid; - - if (iTid >= iNthreads) return (ErrorSet(ERROR_NO_MEMORY, "ThreadEnd(%d) - invalid thread #\n", iTid)); - - if (iTid == TID_SELF) iTid = ThreadGetTid(); - - iMtid = pthrTable[iTid].iMtid; - - return (MachThreadKill(iMtid)); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Start a new thread. The entry point for the thread is specified - by the 'func' parameter. It will be passed it's thread id (iTid), - and a parameter of its own choosing. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadStart(const char *name, void (*func)(int iTid, void *parm), void *parm, int priority) -{ - char* name_nonconstchar = (char*)name; // work around bugs in THREAD and MachThreadStart definition - int iMtid, iTid; - THREAD *pthr; - - if (iNthreads >= iMaxThreads) return (ErrorSet(ERROR_NO_MEMORY, "ThreadStart() - no more threads available\n")); - - iTid = iNthreads++; - pthr = &pthrTable[iTid]; - pthr->name = name_nonconstchar; - pthr->inQ = Qalloc(QSIZE); - if (!pthr->inQ) return (ErrorSet(ERROR_NO_MEMORY, "ThreadStart(%s): could not allocate Q\n", name)); - - iMtid = MachThreadStart(name_nonconstchar, func, iTid, parm, priority); - if (iMtid < 0) { - Qfree(pthr->inQ); - iNthreads--; - return (iMtid); - } - pthr->iMtid = iMtid; - - ThreadResume(iTid, SIG_ALL); - - return (iTid); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Suspend the thread specified by iTid. The thread will not gain - control of the machine again until either ThreadResume is called - explicitly, or ThreadSignal (not yet implemented) is called with - the signal that this thread is waiting for. Note that the iSignal - field is a bit field, and any overlap between the incoming signal - and that which is being waited for will result in the thread being - returned to the active pool. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadSuspend(int iTid, int iSignal) -{ - int iMtid; - THREAD *pthr; - - if (iTid >= iNthreads) return (ErrorSet(ERROR_NO_MEMORY, "ThreadSuspend(%d) - invalid thread\n", iTid)); - - if (iTid == TID_SELF) iTid = ThreadGetTid(); - - pthr = &pthrTable[iTid]; - pthr->iSusSignal |= iSignal; - iMtid = pthr->iMtid; - - return (MachThreadSuspend(iMtid)); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Wake up a thread that was previously slept or suspended. - iSignal is currently unused. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadResume(int iTid, int iSignal) -{ - THREAD *pthr; - int iMtid; - - if (iTid >= iNthreads) return (ErrorSet(ERROR_NO_MEMORY, "ThreadResume(%d) - invalid thread\n", iTid)); - - if (iTid == TID_ALL) { - for (iTid = 0; iTid < iNthreads; iTid++) ThreadResume(iTid, iSignal); - - return (0); - } - else { - if (iTid == TID_SELF) iTid = ThreadGetTid(); - - pthr = &pthrTable[iTid]; - iMtid = pthr->iMtid; - pthr->iSusSignal = 0; - - return (MachThreadResume(iMtid)); - } -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Put the thread specified by iTid to sleep for 'usec' micro - seconds. The thread will wake up after the specified amount of - time, or if ThreadResume is called in the interim. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadSleep(int iTid, long usec) -{ - int iMtid; - - if (iTid >= iNthreads) return (ErrorSet(ERROR_NO_MEMORY, "ThreadSleep(%d) - invalid thread #\n", iTid)); - - if (iTid == TID_SELF) - iMtid = TID_SELF; - else - iMtid = pthrTable[iTid].iMtid; - - return (MachThreadSleep(iMtid, usec)); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Signal a thread that an event that is has (possibly) been waiting - for has occurred. If the thread iSusSignal field has any bits in - common with the incoming signal than the thread will be woken up. - - Return Values: - 1 if the thread was woken up, 0 if not. - -------------------------------------------------------------------------*/ -int ThreadSignal(int iTid, int iSignal) -{ - THREAD *pthr; - - if (iTid >= iNthreads) return (ErrorSet(ERROR_NO_MEMORY, "ThreadSignal(%d) - invalid thread #\n", iTid)); - - if (iTid == TID_SELF) iTid = ThreadGetTid(); - - pthr = &pthrTable[iTid]; - if (pthr->iSusSignal & iSignal) { - ThreadResume(iTid, iSignal); - return (1); - } - else - return (0); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Yield control of the machine. The caller will not return from - this function until other processes (if any) on the machine have - run, and this thread is rescheduled. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadYield(void) -{ - int iMtid, iTid; - - /* ThreadCheckMailbox() ;*/ - iTid = ThreadGetTid(); - iMtid = pthrTable[iTid].iMtid; - - return (MachThreadYield(iMtid)); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Enqueue a message for the thread specified by iTid. If iTid is - set to TID_ALL, the message will be iteratively enqueued on all - threads incoming queues. If the threads in question are in a - state of SIG_Q_PENDING (i.e. they have called Qget and are waiting - for data), they will be woken up, and will return from the call. - - Return Values: - 0 on success, < 0 otherwise. - -------------------------------------------------------------------------*/ -int ThreadEnqueue(int iTid, void *msg) -{ - THREAD *thr; - - if (iTid >= iNthreads) return (ErrorSet(ERROR_NO_MEMORY, "ThreadEnqueue(%d) - invalid thread #\n", iTid)); - - if (iTid == TID_ALL) { - for (iTid = 0; iTid < iNthreads; iTid++) ThreadEnqueue(iTid, msg); - } - else { - thr = &pthrTable[iTid]; - if (msg) Qput(thr->inQ, msg); - if (thr->iSusSignal & SIG_Q_PENDING) ThreadResume(iTid, SIG_Q_PENDING); - } - - return (0); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Read an element off of the the thread's in queue. If no data - is present, and the caller has specified Q_WAIT_FOR_DATA, - then suspend the thread until data is available. - - Return Values: - NULL if nothing is in the Q, pointer to the object at the - head of the Q otherwise. - -------------------------------------------------------------------------*/ -void *ThreadDequeue(int mode) -{ - int iTid; - THREAD *thr; - - iTid = ThreadGetTid(); - - if ((iTid >= iNthreads) || (iTid < 0)) { - ErrorSet(ERROR_NO_MEMORY, "ThreadDequeue(%d) - invalid thread # (max %d)\n", iTid, iNthreads); - return (NULL); - } - - thr = &pthrTable[iTid]; - - if ((mode == Q_WAIT_FOR_DATA) && (Qempty(thr->inQ))) { - ThreadSuspend(iTid, SIG_Q_PENDING); - } - - return (Qget(thr->inQ, mode)); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Get the id of the currently running thread. - - Return Values: - the TID on success (> 0), < 0 on error. - -------------------------------------------------------------------------*/ -int ThreadGetTid(void) -{ - int iMtid, iTid; - - iMtid = MachThreadGetTid(); - - for (iTid = 0; iTid < iNthreads; iTid++) - if (pthrTable[iTid].iMtid == iMtid) return (iTid); - - return (TID_NONE); -} -/*------------------------------------------------------------------------ - Parameters: - - Description: - Kill all threads and exit. This call will not return. - - Return Values: - -------------------------------------------------------------------------*/ -void ThreadExit(int status) { MachThreadExit(status); } -/*------------------------------------------------------------------------ - Parameters: - - Description: - get the machine id. - - Return Values: - the ID of the local machine. - -------------------------------------------------------------------------*/ -int ThreadGetMid(void) { return (iMachineId); } -/*------------------------------------------------------------------------ - Parameters: - - Description: - Check the threads incoming queue, dequeing all elements and - invoking the appropriate mailbox handler for each. - - Return Values: - the number of elements processed. - -------------------------------------------------------------------------*/ -int ThreadCheckMailbox(void) -{ - MSG *msg; - int iNcalls = 0; - - msg = ThreadDequeue(Q_DONT_WAIT); - while (msg) { - iNcalls++; - /* MBinvoke(msg) ;*/ - msg = ThreadDequeue(Q_DONT_WAIT); - } - - return (iNcalls); -} diff --git a/utils/timer.c b/utils/timer.c deleted file mode 100644 index 8e56ab4c18a..00000000000 --- a/utils/timer.c +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @file timer.c - * @brief TimerStart and TimerStop routines for timing programs - * - */ -/* - * Original Author: Bruce Fischl - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include - -#include "proto.h" -#include "sys/timeb.h" -#include "timer.h" - - -// clock_gettime is not available on osx < 10.12 sierra -// mach_gettime is a custom replacement for that -#if defined(__APPLE__) && !defined(HAVE_CLOCK_GETTIME) -#include -#include - -int mach_gettime(clockid_t clk_id, struct timespec *tp) -{ - int ret; - clock_serv_t cclock; - mach_timespec_t mts; - host_get_clock_service(mach_host_self(), clk_id, &cclock); - ret = clock_get_time(cclock, &mts); - mach_port_deallocate(mach_task_self(), cclock); - tp->tv_sec = mts.tv_sec; - tp->tv_nsec = mts.tv_nsec; - return ret; -} -#endif - - -struct timeb *TimerStart(struct timeb *then) -{ -/* according to the header ftime() is obsolete */ -#if 0 - ftime(then) ; - return(then) ; -#endif - /* struct timeval { long tv_sec; long tv_usec; }; */ - struct timeval tv; - gettimeofday(&tv, 0); - then->time = tv.tv_sec; - then->millitm = (tv.tv_usec + 500) / 1000; - then->dstflag = 0; - return then; -} - - -int TimerStop(struct timeb *then) -{ -#if 0 - struct timeb now ; - int msec, now_msec, then_msec ; - - ftime(&now) ; - then_msec = (int)then->time * 1000 + (int)then->millitm ; - now_msec = (int)now.time * 1000 + (int)now.millitm ; - msec = now_msec - then_msec ; - return(msec) ; -#endif - int msec; - struct timeval tvnow, tvthen; - gettimeofday(&tvnow, 0); - tvthen.tv_sec = then->time; - tvthen.tv_usec = ((long)(then->millitm)) * 1000; - msec = 1000 * (tvnow.tv_sec - tvthen.tv_sec) + (tvnow.tv_usec - tvthen.tv_usec + 500) / 1000; - return msec; -} - - -void TimerStartNanosecs(struct NanosecsTimer * nst) -{ -#if defined(__APPLE__) && !defined(HAVE_CLOCK_GETTIME) - mach_gettime(CALENDAR_CLOCK, &nst->now); -#else - clock_gettime(CLOCK_REALTIME, &nst->now); -#endif -} - - -struct Nanosecs TimerElapsedNanosecs(struct NanosecsTimer * nst) // returns delta in nanosecs -{ - struct timespec now; -#if defined(__APPLE__) && !defined(HAVE_CLOCK_GETTIME) - mach_gettime(CALENDAR_CLOCK, &now); -#else - clock_gettime(CLOCK_REALTIME, &now); -#endif - struct timespec * then = &nst->now; - struct Nanosecs result; - result.ns = (long)(now.tv_sec - then->tv_sec)*1000000000 + (long)(now.tv_nsec - then->tv_nsec); - return result; -} - - -// Use this string for writing into files etc. which are not compared by the test system. -// -const char* current_date_time_noOverride() { - time_t tt = time(&tt); - const char* time_str = ctime(&tt); - return time_str; -} - -// Use this string for writing into files etc. where it might be compared by -// the test system. The string is usually the current date and time but -// can be overridden with a string that can the same across runs. -// -const char* current_date_time() { - const char* override_time_str = - getenv("FREESURFER_REPLACEMENT_FOR_CREATION_TIME_STRING"); - const char* time_str = - (!!override_time_str) ? override_time_str : current_date_time_noOverride(); - return time_str; -} - diff --git a/utils/timer.cpp b/utils/timer.cpp new file mode 100644 index 00000000000..c59b7d8f6bb --- /dev/null +++ b/utils/timer.cpp @@ -0,0 +1,53 @@ +#include "timer.h" + + +/// Returns the elapsed time in nanoseconds. +long Timer::nanoseconds() { + return std::chrono::duration_cast(clock::now() - begin).count(); +} + +/// Returns the elapsed time in milliseconds. +long Timer::milliseconds() { + return std::chrono::duration_cast(clock::now() - begin).count(); +} + +/// Returns the elapsed time in seconds. +double Timer::seconds() { + return std::chrono::duration_cast>(clock::now() - begin).count(); +} + +/// Returns the elapsed time in minutes. +double Timer::minutes() { + return std::chrono::duration_cast>>(clock::now() - begin).count(); +} + +/// Returns the elapsed time in minutes. +double Timer::hours() { + return std::chrono::duration_cast>>(clock::now() - begin).count(); +} + +/// Resets the clock. +void Timer::reset() { + begin = clock::now(); +} + + +/// Returns the current date and time in the standard format. +/// +/// For debugging and comparison purposes, it might be appropriate to always print the +/// same datetime string. Setting the 'FREESURFER_REPLACEMENT_FOR_CREATION_TIME_STRING' +/// environment variable to the desired replacement will override the true datetime +/// unless the `allowOverride` argument is set to `false`. + +std::string currentDateTime(bool allowOverride) { + const char* overrideString = getenv("FREESURFER_REPLACEMENT_FOR_CREATION_TIME_STRING"); + if (allowOverride && overrideString) { + return overrideString; + } else { + char datetime[1000]; + time_t t = std::time(nullptr); + struct tm *now = localtime(&t); + std::strftime(datetime, 1000, "%c", now); + return datetime; + } +} diff --git a/utils/transform.c b/utils/transform.cpp similarity index 99% rename from utils/transform.c rename to utils/transform.cpp index 182c600f194..26337183faf 100644 --- a/utils/transform.c +++ b/utils/transform.cpp @@ -603,7 +603,7 @@ int LTAwrite(LTA *lta, const char *fname) if (!user) user = "UNKNOWN" ; fprintf(fp, "# transform file %s\n# created by %s on %s\n", - fname, user, current_date_time()) ; + fname, user, currentDateTime().c_str()) ; fprintf(fp, "type = %d ", lta->type) ; if(lta->type == LINEAR_VOX_TO_VOX) fprintf(fp, "# LINEAR_VOX_TO_VOX"); if(lta->type == LINEAR_RAS_TO_RAS) fprintf(fp, "# LINEAR_RAS_TO_RAS"); @@ -1628,7 +1628,7 @@ static int ltaFSLwrite(const LTA *lta, const char *fname) return (NO_ERROR); } -#include "minc_volume_io.h" +#include "minc.h" static int ltaMNIwrite(const LTA *lta, const char *fname) { @@ -3322,7 +3322,7 @@ int // (NOT TRUE ANYMORE: OK means 1, BAD means 0 ) use standard ERROR returns LTAwriteEx(const LTA *lta, const char *fname) { FILE *fp; - char *user; + const char *user; char ext[STRLEN]; if (!stricmp(FileNameExtension((char *)fname, ext), "XFM") || lta->type == MNI_TRANSFORM_TYPE) { @@ -3353,7 +3353,7 @@ LTAwriteEx(const LTA *lta, const char *fname) user = getenv("USER"); if (!user) user = getenv("LOGNAME"); if (!user) user = "UNKNOWN"; - fprintf(fp, "# transform file %s\n# created by %s on %s\n", fname, user, current_date_time()); + fprintf(fp, "# transform file %s\n# created by %s on %s\n", fname, user, currentDateTime().c_str()); LTAprint(fp, lta); fclose(fp); @@ -5119,7 +5119,7 @@ void TransformInvertReplace(TRANSFORM *transform, const MRI *mri) GCAMfree(&gcam); break; default: - lta = transform->xform; + lta = (LTA *)transform->xform; transform->xform = (void *)LTAinvert(lta, NULL); LTAfree(<a); break; diff --git a/utils/tritri.c b/utils/tritri.cpp similarity index 100% rename from utils/tritri.c rename to utils/tritri.cpp diff --git a/utils/tukey.c b/utils/tukey.cpp similarity index 100% rename from utils/tukey.c rename to utils/tukey.cpp diff --git a/utils/utils.c b/utils/utils.cpp similarity index 99% rename from utils/utils.c rename to utils/utils.cpp index 89aa045396e..3bba1635a36 100644 --- a/utils/utils.c +++ b/utils/utils.cpp @@ -393,7 +393,8 @@ char *StrReplace(const char *src, char *dst, char csrc, int cdst) ------------------------------------------------------------------------*/ char *FileNameOnly(const char *full_name, char *fname) { - char *slash, *number, *at; + const char *slash; + char *number, *at; slash = strrchr(full_name, '/'); @@ -409,7 +410,6 @@ char *FileNameOnly(const char *full_name, char *fname) // best solution: copy full_name to fname // fname = strcpyalloc(full_name); - *slash = 0; } number = strrchr(fname, '#'); @@ -629,17 +629,22 @@ char *FileFullName(char *full_name) Return Values: pointer to the filename ------------------------------------------------------------------------*/ -char *FileTmpName(char *basename) +char *FileTmpName(const char *basename) { static char fname[STR_LEN]; int i; FILE *fp; - if (!basename) basename = "tmp"; + const char *realname; + if (!basename) { + realname = "tmp"; + } else { + realname = basename; + } i = 0; do { - sprintf(fname, "%s%d", basename, i++); + sprintf(fname, "%s%d", realname, i++); fp = fopen(fname, "r"); if (fp) fclose(fp); } while (fp); @@ -977,7 +982,7 @@ char *FileNameExtension(const char *fname, char *ext) char *FileNameFromWildcard(const char *inStr, char *outStr) { - char *cp; + const char *cp; glob_t gbuf; if (inStr != outStr) strcpy(outStr, inStr); @@ -1097,12 +1102,12 @@ int ItemsInString(const char *str) char *deblank(const char *str) { char *dbstr; - int n, m; + int m; dbstr = (char *)calloc(strlen(str) + 1, sizeof(char)); m = 0; - for (n = 0; n < strlen(str); n++) { + for (unsigned int n = 0; n < strlen(str); n++) { // printf("%d %c %d\n",n,str[n],isspace(str[n])); if (isspace(str[n])) continue; dbstr[m] = str[n]; @@ -1119,8 +1124,7 @@ char *deblank(const char *str) */ char *str_toupper(char *str) { - int n; - for (n = 0; n < strlen(str); n++) str[n] = toupper(str[n]); + for (unsigned int n = 0; n < strlen(str); n++) str[n] = toupper(str[n]); return (0); } diff --git a/utils/version.c b/utils/version.cpp similarity index 98% rename from utils/version.c rename to utils/version.cpp index da9c2697462..5fdb1c983cd 100644 --- a/utils/version.c +++ b/utils/version.cpp @@ -200,7 +200,7 @@ int make_cmd_version_string( // TODO: build_timestamp really ought to be passed-in as a parameter // from the calling binary, to get a more accurate build time, but for // now, the build time of this version.c (libutils) is better than nothing - char build_timestamp[] = __DATE__ " "__TIME__; + char build_timestamp[] = __DATE__ " " __TIME__; char argstr[CMD_LINE_LEN]; if (strlen(arguments) > CMD_LINE_LEN / 2) @@ -298,7 +298,7 @@ int handle_version_option(int argc, char **argv, const char *id_string, const ch /* Copy later args one step back. */ for (nnarg = narg; nnarg < argc - num_processed_args; nnarg++) { - myarg = malloc(strlen(argv[nnarg + 1]) + 1); + myarg = (char *)malloc(strlen(argv[nnarg + 1]) + 1); strcpy(myarg, argv[nnarg + 1]); argv[nnarg] = myarg; } @@ -368,7 +368,7 @@ int handle_version_option(int argc, char **argv, const char *id_string, const ch // TODO: build_timestamp really ought to be passed-in as a parameter // from the calling binary, to get a more accurate build time, but for // now, the build time of version.c (libutils) is better than nothing - char build_timestamp[] = __DATE__ " "__TIME__; + char build_timestamp[] = __DATE__ " " __TIME__; /* Build the info string. */ fprintf(stdout, @@ -394,7 +394,7 @@ int handle_version_option(int argc, char **argv, const char *id_string, const ch /* Copy later args one step back. */ for (nnarg = narg; nnarg < argc - num_processed_args; nnarg++) { - myarg = malloc(strlen(argv[nnarg + 1]) + 1); + myarg = (char *)malloc(strlen(argv[nnarg + 1]) + 1); strcpy(myarg, argv[nnarg + 1]); argv[nnarg] = myarg; } diff --git a/utils/vertexRotator.c b/utils/vertexRotator.cpp similarity index 98% rename from utils/vertexRotator.c rename to utils/vertexRotator.cpp index 59fc948e5fc..1b80fda2d11 100644 --- a/utils/vertexRotator.c +++ b/utils/vertexRotator.cpp @@ -47,9 +47,7 @@ static void rotateVertices1axis_wkr( float const sa = sin(alpha); float const ca = cos(alpha); - int vno; - - for (vno = 0; vno < nvertices; vno++) { + for (unsigned vno = 0; vno < nvertices; vno++) { float x = xv_inp[vno]; float y = yv_inp[vno]; float xp = x * ca + y * sa; @@ -59,7 +57,7 @@ static void rotateVertices1axis_wkr( } if (zv_out) { - for (vno = 0; vno < nvertices; vno++) { + for (unsigned int vno = 0; vno < nvertices; vno++) { zv_out[vno] = zv_inp[vno]; } } @@ -97,10 +95,8 @@ static inline void rotateVertices_wkr( float const sasbsg = sa * sb * sg; float const cbcg = cb * cg; float const cbsg = cb * sg; - - int vno; - for (vno = 0; vno < nvertices; vno++) { + for (unsigned int vno = 0; vno < nvertices; vno++) { float x = xv_inp[vno]; float y = yv_inp[vno]; diff --git a/utils/vlabels.c b/utils/vlabels.cpp similarity index 100% rename from utils/vlabels.c rename to utils/vlabels.cpp diff --git a/utils/volcluster.c b/utils/volcluster.cpp similarity index 100% rename from utils/volcluster.c rename to utils/volcluster.cpp diff --git a/utils/voxlist.c b/utils/voxlist.cpp similarity index 100% rename from utils/voxlist.c rename to utils/voxlist.cpp diff --git a/utils/x3DList.c b/utils/x3DList.c deleted file mode 100644 index bd040751379..00000000000 --- a/utils/x3DList.c +++ /dev/null @@ -1,538 +0,0 @@ -/** - * @file x3DList.c - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.10 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "x3DList.h" -#include -#include -#include "xDebug.h" -#include "xList.h" - -char *x3Lst_ksaErrorString[x3Lst_knNumErrorCodes] = {"No error.", - "Invalid space ptr.", - "Invalid signature.", - "Error accessing the list.", - "Item not found in space.", - "Invalid space (probably not initialized).", - "Invalid location (location is out of bounds of the space).", - "Invalid plane number, out of range.", - "Couldn't allocate space, memory full?", - "Couldn't allocate list, memory full?", - "Invalid error code."}; - -/* init the space */ -x3Lst_tErr x3Lst_New(x3DListRef *op3DList, int inListSize) -{ - x3DListRef this = NULL; - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - x3Lst_tPlane plane = 0; - int list = 0; - xList_tErr eList = xList_tErr_NoErr; - - /* allocate us */ - this = (x3DListRef)malloc(sizeof(x3DList)); - if (NULL == this) { - eResult = x3Lst_tErr_CouldntAllocateSpace; - goto error; - } - - /* set the sig */ - this->mSignature = x3Lst_kSignature; - - /* set the plane size */ - this->mnPlaneSize = inListSize; - - /* allocate our lists. */ - for (plane = 0; plane < x3Lst_knNumPlanes; plane++) { - this->mPlane[plane] = (xListRef *)calloc(sizeof(xList), this->mnPlaneSize); - if (NULL == this->mPlane[plane]) { - eResult = x3Lst_tErr_CouldntAllocateSpace; - goto error; - } - - /* init all the lists */ - for (list = 0; list < this->mnPlaneSize; list++) { - eList = xList_New(&(this->mPlane[plane][list])); - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_CouldntAllocateList; - goto error; - } - } - } - - /* return us */ - *op3DList = this; - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_New: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_Delete(x3DListRef *iop3DList) -{ - x3DListRef this = NULL; - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - x3Lst_tPlane plane = 0; - int list = 0; - xList_tErr eList = xList_tErr_NoErr; - - if (NULL == iop3DList) { - eResult = x3Lst_tErr_InvalidPtr; - goto error; - } - - this = *iop3DList; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - /* for each plane.. */ - for (plane = 0; plane < x3Lst_knNumPlanes; plane++) { - /* delete all the lists */ - for (list = 0; list < this->mnPlaneSize; list++) { - eList = xList_Delete(&(this->mPlane[plane][list])); - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_CouldntAllocateList; - goto error; - } - } - - /* delete the plane */ - free(this->mPlane[plane]); - } - - /* trash the sig */ - this->mSignature = 0x1; - - /* delete us */ - free(this); - - /* return null */ - *iop3DList = NULL; - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_GetPlaneSize(x3DListRef this, int *onPlaneSize) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - if (NULL == onPlaneSize) { - eResult = x3Lst_tErr_InvalidPtr; - goto error; - } - - /* Return the value */ - *onPlaneSize = this->mnPlaneSize; - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_GetPlaneSize: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_AddItem(x3DListRef this, xVoxelRef iWhere, void *ipItem) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - xList_tErr eList = xList_tErr_NoErr; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - eResult = x3Lst_VerifyLocation(this, iWhere); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - /* add it to the every plane at the approriate voxel */ - eList = xList_PushItem(this->mPlane[x3Lst_tPlane_X][xVoxl_GetX(iWhere)], ipItem); - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_ErrorAccessingList; - goto error; - } - - eList = xList_PushItem(this->mPlane[x3Lst_tPlane_Y][xVoxl_GetY(iWhere)], ipItem); - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_ErrorAccessingList; - goto error; - } - - eList = xList_PushItem(this->mPlane[x3Lst_tPlane_Z][xVoxl_GetZ(iWhere)], ipItem); - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_ErrorAccessingList; - goto error; - } - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_AddItem: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_RemoveItem(x3DListRef this, xVoxelRef iWhere, void **iopItemToRemove) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - xList_tErr eList = xList_tErr_NoErr; - void *pItemToRemove = NULL; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - eResult = x3Lst_VerifyLocation(this, iWhere); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - /* remove it from every plane at the approriate voxel */ - pItemToRemove = *iopItemToRemove; - eList = xList_RemoveItem(this->mPlane[x3Lst_tPlane_X][xVoxl_GetX(iWhere)], &pItemToRemove); - if (xList_tErr_NoErr != eList) { - goto error; - } - - pItemToRemove = *iopItemToRemove; - eList = xList_RemoveItem(this->mPlane[x3Lst_tPlane_Y][xVoxl_GetY(iWhere)], &pItemToRemove); - if (xList_tErr_NoErr != eList) { - goto error; - } - - pItemToRemove = *iopItemToRemove; - eList = xList_RemoveItem(this->mPlane[x3Lst_tPlane_Z][xVoxl_GetZ(iWhere)], &pItemToRemove); - if (xList_tErr_NoErr != eList) { - goto error; - } - - /* return the removed item */ - *iopItemToRemove = pItemToRemove; - - goto cleanup; - -error: - - if (xList_tErr_NoErr != eList) { - if (xList_tErr_ItemNotInList == eList) { - eResult = x3Lst_tErr_ItemNotInSpace; - } - else { - eResult = x3Lst_tErr_ErrorAccessingList; - } - } - - if (x3Lst_tErr_NoErr != eResult && x3Lst_tErr_ItemNotInSpace != eResult) { - DebugPrint(("Error %d in x3Lst_RemoveItem: %s\n", eResult, x3Lst_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_Clear(x3DListRef this) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - xList_tErr eList = xList_tErr_NoErr; - x3Lst_tPlane plane = 0; - int list = 0; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - /* for each plane.. */ - for (plane = 0; plane < x3Lst_knNumPlanes; plane++) { - /* clear all the lists */ - for (list = 0; list < this->mnPlaneSize; list++) { - eList = xList_Clear(this->mPlane[plane][list]); - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_ErrorAccessingList; - goto error; - } - } - } - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_Clear: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_IsInList(x3DListRef this, void *ipData, tBoolean *outIsInList) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - xList_tErr eList = xList_tErr_NoErr; - x3Lst_tPlane plane = 0; - int list = 0; - tBoolean isInList = FALSE; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - /* for each plane.. */ - for (plane = 0; plane < x3Lst_knNumPlanes; plane++) { - /* ask if it's in this list. */ - for (list = 0; list < this->mnPlaneSize; list++) { - eList = xList_IsInList(this->mPlane[plane][list], ipData, &isInList); - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_ErrorAccessingList; - goto error; - } - - if (isInList) { - *outIsInList = isInList; - } - } - } - - *outIsInList = FALSE; - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_IsInList: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_GetItemsInXPlane(x3DListRef this, int inXPlane, xListRef *opList) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - eResult = x3Lst_GetItemsInPlane_(this, x3Lst_tPlane_X, inXPlane, opList); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_GetItemsInXPlane: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_GetItemsInYPlane(x3DListRef this, int inYPlane, xListRef *opList) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - eResult = x3Lst_GetItemsInPlane_(this, x3Lst_tPlane_Y, inYPlane, opList); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_GetItemsInYPlane: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_GetItemsInZPlane(x3DListRef this, int inZPlane, xListRef *opList) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - eResult = x3Lst_GetItemsInPlane_(this, x3Lst_tPlane_Z, inZPlane, opList); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_GetItemsInZPlane: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_GetItemsInPlane_(x3DListRef this, x3Lst_tPlane iPlane, int inPlaneIndex, xListRef *opList) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - - /* make sure the index is in bounds */ - if (inPlaneIndex < 0 || inPlaneIndex >= this->mnPlaneSize) { - eResult = x3Lst_tErr_InvalidPlaneNumber; - goto error; - } - - /* return a ptr to the list */ - *opList = this->mPlane[iPlane][inPlaneIndex]; - - goto cleanup; - -error: - - DebugPrint(("Error %d in x3Lst_GetItemsInPlane_: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_SetComparator(x3DListRef this, xList_tCompare (*iComparator)(void *, void *)) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - x3Lst_tPlane plane = 0; - int list = 0; - xList_tErr eList = xList_tErr_NoErr; - - eResult = x3Lst_Verify(this); - if (x3Lst_tErr_NoErr != eResult) { - goto error; - } - - /* for each plane.. */ - for (plane = 0; plane < x3Lst_knNumPlanes; plane++) { - /* set comparator in all the lists */ - for (list = 0; list < this->mnPlaneSize; list++) { - eList = xList_SetComparator(this->mPlane[plane][list], iComparator); - if (xList_tErr_NoErr != eList) { - goto error; - } - } - } - - goto cleanup; - -error: - - if (xList_tErr_NoErr != eList) { - eResult = x3Lst_tErr_ErrorAccessingList; - } - - DebugPrint(("Error %d in x3Lst_: %s\n", eResult, x3Lst_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_Verify(x3DListRef this) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - - if (NULL == this) { - eResult = x3Lst_tErr_InvalidPtr; - goto cleanup; - } - - if (x3Lst_kSignature != this->mSignature) { - eResult = x3Lst_tErr_InvalidSignature; - goto cleanup; - } - -cleanup: - - return eResult; -} - -x3Lst_tErr x3Lst_VerifyLocation(x3DListRef this, xVoxelRef iWhere) -{ - x3Lst_tErr eResult = x3Lst_tErr_NoErr; - - if (xVoxl_GetX(iWhere) < 0 || xVoxl_GetX(iWhere) >= this->mnPlaneSize || xVoxl_GetY(iWhere) < 0 || - xVoxl_GetY(iWhere) >= this->mnPlaneSize || xVoxl_GetZ(iWhere) < 0 || xVoxl_GetZ(iWhere) >= this->mnPlaneSize) { - eResult = x3Lst_tErr_InvalidLocation; - } - - return eResult; -} - -char *x3Lst_GetErrorString(x3Lst_tErr ieCode) -{ - x3Lst_tErr eCode = ieCode; - - if (ieCode < 0 || ieCode >= x3Lst_knNumErrorCodes) { - eCode = x3Lst_tErr_InvalidErrorCode; - } - - return x3Lst_ksaErrorString[eCode]; -} diff --git a/utils/xDebug.c b/utils/xDebug.cpp similarity index 99% rename from utils/xDebug.c rename to utils/xDebug.cpp index e192337e981..93648cddc26 100644 --- a/utils/xDebug.c +++ b/utils/xDebug.cpp @@ -149,7 +149,7 @@ void xDbg_PopStack() } } -char *xDbg_GetCurrentFunction() +const char *xDbg_GetCurrentFunction() { if (mCurrentStackDepth > 0) { return masStackTitle[mCurrentStackDepth - 1]; diff --git a/utils/xGLutWindow.c b/utils/xGLutWindow.c deleted file mode 100644 index a87101815c9..00000000000 --- a/utils/xGLutWindow.c +++ /dev/null @@ -1,756 +0,0 @@ -/** - * @file xGLutWindow.c - * @brief general purpose utils - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.11 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#ifdef HAVE_OPENGL - -#include "xGLutWindow.h" -#include -#include "xDebug.h" - -static xGLutWindowRef mLookupList[xGWin_knMaxNumWindows]; - -static char *ksErrorStrings[xGWin_knNumErrorCodes] = {"No error.", - "Invalid window ptr (probably NULL).", - "Invalid window signature.", - "Memory allocation failed.", - "Invalid input paramter.", - "Invalid error code."}; - -xGWin_tErr xGWin_New(xGLutWindowRef *oppWindow, int inWidth, int inHeight, char *isTitle) -{ - xGWin_tErr eResult = xGWin_tErr_NoErr; - xGLutWindowRef this = NULL; - - // check our params. - if (NULL == isTitle || inWidth < 0 || inHeight < 0) { - eResult = xGWin_tErr_InvalidParameter; - goto error; - } - - // allocate the window. - this = (xGLutWindowRef)malloc(sizeof(xGLutWindow)); - if (NULL == this) { - eResult = xGWin_tErr_AllocationFailed; - goto error; - } - - // set signature. - this->mSignature = xGWin_kSignature; - - // set the window size. - glutInitWindowSize(inWidth, inHeight); - - // create an glut window and save its id - this->mnGLutWindowID = glutCreateWindow(isTitle); - - // set the glut window's handlers to our handlers. - glutDisplayFunc(xGWin_GLutDrawCallback); - glutKeyboardFunc(xGWin_GLutKeyboardCallback); - glutSpecialFunc(xGWin_GLutSpecialCallback); - glutMouseFunc(xGWin_GLutMouseCallback); - glutMotionFunc(xGWin_GLutMotionCallback); - glutReshapeFunc(xGWin_GLutResizeCallback); - - // set func ptrs and data to nil. - this->mpHandlerFunc = NULL; - this->mpHandlerFuncData = NULL; - - // add this window to the window list. - xGWin_AddWindowIDToLookupList(this->mnGLutWindowID, this); - - // return it. - *oppWindow = this; - - goto cleanup; - -error: - - // delete window if it was allocated. - if (NULL != this) { - free(this); - } - - DebugPrint(("Error %d in xGWin_New: %s", eResult, xGWin_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xGWin_tErr xGWin_Delete(xGLutWindowRef *ioppWindow) -{ - xGWin_tErr eResult = xGWin_tErr_NoErr; - xGLutWindowRef this = NULL; - - // grab window. - this = *ioppWindow; - - // verify it. - eResult = xGWin_Verify(this); - if (xGWin_tErr_NoErr != eResult) { - goto error; - } - - // destroy the glut window. - glutDestroyWindow(this->mnGLutWindowID); - - // trash signature. - this->mSignature = 0x1; - - // delete window. - free(this); - - // return nill. - *ioppWindow = NULL; - - goto cleanup; - -error: - - DebugPrint(("Error %d in xGWin_Delete: %s", eResult, xGWin_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xGWin_tErr xGWin_SetWindowTitle(xGLutWindowRef this, char *isTitle) -{ - xGWin_tErr eResult = xGWin_tErr_NoErr; - - // verify it. - eResult = xGWin_Verify(this); - if (xGWin_tErr_NoErr != eResult) { - goto error; - } - - /* set window title */ - glutSetWindowTitle(isTitle); - - goto cleanup; - -error: - - DebugPrint(("Error %d in xGWin_SetWindowTitle: %s", eResult, xGWin_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xGWin_tErr xGWin_SetEventHandlerFunc(xGLutWindowRef this, xGWin_tEventHandlerFunc ipFunc, void *ipData) -{ - xGWin_tErr eResult = xGWin_tErr_NoErr; - - // verify it. - eResult = xGWin_Verify(this); - if (xGWin_tErr_NoErr != eResult) { - goto error; - } - - // set func and data. - this->mpHandlerFunc = ipFunc; - this->mpHandlerFuncData = ipData; - - goto cleanup; - -error: - - DebugPrint(("Error %d in xGWin_SetEventHandlerFunc: %s", eResult, xGWin_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xGWin_tErr xGWin_ActivateIdleEvents(xGLutWindowRef this) -{ - xGWin_tErr eResult = xGWin_tErr_NoErr; - int nSaveWindowID = 0; - - // verify it. - eResult = xGWin_Verify(this); - if (xGWin_tErr_NoErr != eResult) { - goto error; - } - - // save the current window and set the window to this window. - nSaveWindowID = glutGetWindow(); - glutSetWindow(this->mnGLutWindowID); - - // register our idle callback. - glutIdleFunc(xGWin_GLutIdleCallback); - - // restore the window. - glutSetWindow(nSaveWindowID); - - goto cleanup; - -error: - - DebugPrint(("Error %d in xGWin_ActivateIdleEvents: %s", eResult, xGWin_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xGWin_tErr xGWin_ActivatePassiveMotionEvents(xGLutWindowRef this) -{ - xGWin_tErr eResult = xGWin_tErr_NoErr; - int nSaveWindowID = 0; - - // verify it. - eResult = xGWin_Verify(this); - if (xGWin_tErr_NoErr != eResult) { - goto error; - } - - // save the current window and set the window to this window. - nSaveWindowID = glutGetWindow(); - glutSetWindow(this->mnGLutWindowID); - - // register our passive motion callback. - glutPassiveMotionFunc(xGWin_GLutPassiveMotionCallback); - - // restore the window. - glutSetWindow(nSaveWindowID); - - goto cleanup; - -error: - - DebugPrint(("Error %d in xGWin_ActivatePassiveMotionEvents: %s", eResult, xGWin_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xGWin_tErr xGWin_Verify(xGLutWindowRef this) -{ - xGWin_tErr eResult = xGWin_tErr_NoErr; - - // check ptr. - if (NULL == this) { - eResult = xGWin_tErr_InvalidWindowPtr; - goto error; - } - - // check signature. - if (xGWin_kSignature != this->mSignature) { - eResult = xGWin_tErr_InvalidWindowSignature; - goto error; - } - - goto cleanup; - -error: -cleanup: - - return eResult; -} - -char *xGWin_GetErrorString(xGWin_tErr ieCode) -{ - if (ieCode < 0 || ieCode >= xGWin_knNumErrorCodes) { - ieCode = xGWin_tErr_InvalidErrorCode; - } - - return ksErrorStrings[ieCode]; -} - -void xGWin_AddWindowIDToLookupList(int inWindowID, xGLutWindowRef ipWindow) -{ - /* this used to be a list of number/ptr nodes, but the glut specification - says that numbers always start at 1 and increase sequentially, so i - guess it's okay to use an arrray if you don't mind a fixed number - of max windows. */ - - // check the bounds. - if (inWindowID < 0 || inWindowID >= xGWin_knMaxNumWindows) { - DebugPrint(("xGWin_AddWindowIDToLookupList: invalid ID: %d\n", inWindowID)); - return; - } - - // save this ptr. - mLookupList[inWindowID] = ipWindow; -} - -void xGWin_GetWindowFromID(int inWindowID, xGLutWindowRef *oppWindow) -{ - // check the bounds. - if (inWindowID < 0 || inWindowID >= xGWin_knMaxNumWindows) { - DebugPrint(("xGWin_AddWindowIDToLookupList: invalid ID: %d\n", inWindowID)); - return; - } - - // return this window ptr. - *oppWindow = mLookupList[inWindowID]; -} - -void xGWin_RemoveWindowIDFromLookupList(int inWindowID) -{ - // check the bounds. - if (inWindowID < 0 || inWindowID >= xGWin_knMaxNumWindows) { - DebugPrint(("xGWin_AddWindowIDToLookupList: invalid ID: %d\n", inWindowID)); - return; - } - - // set the ptr to null. - mLookupList[inWindowID] = NULL; -} - -void xGWin_PassEventToCurrentWindow(xGWin_tEventRef ipEvent) -{ - int nWindowID = 0; - xGLutWindowRef pWindow = NULL; - - // get current window id. - nWindowID = glutGetWindow(); - - // get a window ptr. - xGWin_GetWindowFromID(nWindowID, &pWindow); - - if (NULL != pWindow) { - // call the window's event handler with the window handler data - // and this event. - pWindow->mpHandlerFunc(pWindow->mpHandlerFuncData, ipEvent); - } - else { - DebugPrint( - ("xGWin_PassEventToCurrentWindow: Couldn't find current" - "window, id is %d", - nWindowID)); - } -} - -void xGWin_PassEventToAllWindows(xGWin_tEventRef ipEvent) -{ - int nSaveWindowID = 0; - int nWindowID = 0; - xGLutWindowRef pWindow = NULL; - - // save the current window. - nSaveWindowID = glutGetWindow(); - - // for all windows... - for (nWindowID = 0; nWindowID < xGWin_knMaxNumWindows; nWindowID++) { - // try to get a window ptr. - xGWin_GetWindowFromID(nWindowID, &pWindow); - - // if we got one... - if (NULL != pWindow) { - // set the window - glutSetWindow(nWindowID); - - // call the window's event handler with the window handler data - // and this event. - pWindow->mpHandlerFunc(pWindow->mpHandlerFuncData, ipEvent); - } - } - - // restore the window. - glutSetWindow(nSaveWindowID); -} - -void xGWin_GLutKeyboardCallback(unsigned char icKey, int inX, int inY) -{ - xGWin_tEventRef pEvent = NULL; - int nState = 0; - unsigned char ucModifiedKey = 0; - - /* in all these funcs, we just create an event, set the relevant fields, - and pass it to the event sender */ - xGWin_NewEvent(&pEvent); - - pEvent->mType = xGWin_tEventType_KeyDown; - pEvent->mKey = icKey; - pEvent->mWhere.mnX = inX; - pEvent->mWhere.mnY = inY; - - /* finds the state of modifer keys and set booleans appropriatly */ - nState = glutGetModifiers(); - if (nState & GLUT_ACTIVE_SHIFT) { - pEvent->mbShiftKey = TRUE; - } - if (nState & GLUT_ACTIVE_CTRL) { - pEvent->mbCtrlKey = TRUE; - } - if (nState & GLUT_ACTIVE_ALT) { - pEvent->mbAltKey = TRUE; - } - - /* if control is down, the char we got was not an actual char, it was - a special character. so we'll add the value of a minus the value of - ctrl-a. */ - if (pEvent->mbCtrlKey) { - ucModifiedKey = (unsigned char)((int)icKey + ((int)'a' - xGWin_knCtrlA)); - if ((ucModifiedKey >= 'a' && ucModifiedKey <= 'z') || (ucModifiedKey >= 'A' && ucModifiedKey <= 'Z')) { - pEvent->mKey = ucModifiedKey; - } - else { - /* we also have special codes for the control-number keys. check - those. */ - switch (icKey) { - case xGWin_knCtrl0: - pEvent->mKey = '0'; - break; - case xGWin_knCtrl1: - pEvent->mKey = '1'; - break; - case xGWin_knCtrl2: - pEvent->mKey = '2'; - break; - case xGWin_knCtrl3: - pEvent->mKey = '3'; - break; - case xGWin_knCtrl4: - pEvent->mKey = '4'; - break; - case xGWin_knCtrl5: - pEvent->mKey = '5'; - break; - case xGWin_knCtrl6: - pEvent->mKey = '6'; - break; - case xGWin_knCtrl7: - pEvent->mKey = '7'; - break; - case xGWin_knCtrl8: - pEvent->mKey = '8'; - break; - case xGWin_knCtrl9: - pEvent->mKey = '9'; - break; - } - } - } - - xGWin_PassEventToCurrentWindow(pEvent); -} - -void xGWin_GLutSpecialCallback(int inKey, int inX, int inY) -{ - xGWin_tEventRef pEvent = NULL; - int nState = 0; - - xGWin_NewEvent(&pEvent); - - pEvent->mType = xGWin_tEventType_KeyDown; - pEvent->mWhere.mnX = inX; - pEvent->mWhere.mnY = inY; - - /* choose the proper key. */ - switch (inKey) { - case GLUT_KEY_LEFT: - pEvent->mKey = xGWin_tKey_LeftArrow; - break; - case GLUT_KEY_UP: - pEvent->mKey = xGWin_tKey_UpArrow; - break; - case GLUT_KEY_RIGHT: - pEvent->mKey = xGWin_tKey_RightArrow; - break; - case GLUT_KEY_DOWN: - pEvent->mKey = xGWin_tKey_DownArrow; - break; - case GLUT_KEY_PAGE_UP: - pEvent->mKey = xGWin_tKey_PageUp; - break; - case GLUT_KEY_PAGE_DOWN: - pEvent->mKey = xGWin_tKey_PageDown; - break; - case GLUT_KEY_HOME: - pEvent->mKey = xGWin_tKey_Home; - break; - case GLUT_KEY_END: - pEvent->mKey = xGWin_tKey_End; - break; - case GLUT_KEY_INSERT: - pEvent->mKey = xGWin_tKey_Insert; - break; - } - - /* finds the state of modifer keys and set booleans appropriatly */ - nState = glutGetModifiers(); - if (nState & GLUT_ACTIVE_SHIFT) { - pEvent->mbShiftKey = TRUE; - } - if (nState & GLUT_ACTIVE_CTRL) { - pEvent->mbCtrlKey = TRUE; - } - if (nState & GLUT_ACTIVE_ALT) { - pEvent->mbAltKey = TRUE; - } - - xGWin_PassEventToCurrentWindow(pEvent); -} - -/* we use these variables to save the button pressed and modifers when - the mouse is first pressed down. we use these values when generating - mouse-moved events, because glut doesn't let us glutGetModifiers on - a mouse-moved callback. */ -static xGWin_tButton mButton = 0; -static tBoolean mbShiftKey = FALSE; -static tBoolean mbCtrlKey = FALSE; -static tBoolean mbAltKey = FALSE; - -void xGWin_GLutMouseCallback(int inButton, int inState, int inX, int inY) -{ - xGWin_tEventRef pEvent = NULL; - int nState = 0; - - xGWin_NewEvent(&pEvent); - - /* find out if it was up or down. */ - if (GLUT_DOWN == inState) { - pEvent->mType = xGWin_tEventType_MouseDown; - } - if (GLUT_UP == inState) { - pEvent->mType = xGWin_tEventType_MouseUp; - } - - /* find out which button */ - if (GLUT_LEFT_BUTTON == inButton) { - pEvent->mButton = 1; - } - if (GLUT_MIDDLE_BUTTON == inButton) { - pEvent->mButton = 2; - } - if (GLUT_RIGHT_BUTTON == inButton) { - pEvent->mButton = 3; - } - mButton = pEvent->mButton; - - /* set location */ - pEvent->mWhere.mnX = inX; - pEvent->mWhere.mnY = inY; - - /* finds the state of modifer keys and set booleans appropriatly */ - nState = glutGetModifiers(); - if (nState & GLUT_ACTIVE_SHIFT) { - pEvent->mbShiftKey = TRUE; - mbShiftKey = TRUE; - } - else { - mbShiftKey = FALSE; - } - if (nState & GLUT_ACTIVE_CTRL) { - pEvent->mbCtrlKey = TRUE; - mbCtrlKey = TRUE; - } - else { - mbCtrlKey = FALSE; - } - if (nState & GLUT_ACTIVE_ALT) { - pEvent->mbAltKey = TRUE; - mbAltKey = TRUE; - } - else { - mbAltKey = FALSE; - } - - xGWin_PassEventToCurrentWindow(pEvent); -} - -void xGWin_GLutMotionCallback(int inX, int inY) -{ - xGWin_tEventRef pEvent = NULL; - - xGWin_NewEvent(&pEvent); - - pEvent->mType = xGWin_tEventType_MouseMoved; - - /* get button from last mouse down.*/ - pEvent->mButton = mButton; - - /* set location */ - pEvent->mWhere.mnX = inX; - pEvent->mWhere.mnY = inY; - - /* get modifiers from last mouse down. */ - pEvent->mbShiftKey = mbShiftKey; - pEvent->mbCtrlKey = mbCtrlKey; - pEvent->mbAltKey = mbAltKey; - - xGWin_PassEventToCurrentWindow(pEvent); -} - -void xGWin_GLutPassiveMotionCallback(int inX, int inY) -{ - xGWin_tEventRef pEvent = NULL; - - xGWin_NewEvent(&pEvent); - - pEvent->mType = xGWin_tEventType_MouseMoved; - - /* no mouse down.*/ - pEvent->mButton = 0; - - /* set location */ - pEvent->mWhere.mnX = inX; - pEvent->mWhere.mnY = inY; - - /* no modifiers */ - pEvent->mbShiftKey = FALSE; - pEvent->mbCtrlKey = FALSE; - pEvent->mbAltKey = FALSE; - - xGWin_PassEventToCurrentWindow(pEvent); -} - -void xGWin_GLutResizeCallback(int inWidth, int inHeight) -{ - xGWin_tEventRef pEvent; - - xGWin_NewEvent(&pEvent); - - pEvent->mType = xGWin_tEventType_Resize; - pEvent->mWhere.mnX = inWidth; - pEvent->mWhere.mnY = inHeight; - - xGWin_PassEventToCurrentWindow(pEvent); -} - -void xGWin_GLutDrawCallback() -{ - xGWin_tEventRef pEvent; - - xGWin_NewEvent(&pEvent); - - pEvent->mType = xGWin_tEventType_Draw; - - xGWin_PassEventToCurrentWindow(pEvent); -} - -void xGWin_GLutIdleCallback() -{ - xGWin_tEventRef pEvent; - - xGWin_NewEvent(&pEvent); - - pEvent->mType = xGWin_tEventType_Idle; - - xGWin_PassEventToCurrentWindow(pEvent); -} - -void xGWin_RedrawAllWindows() -{ - int nSaveWindowID = 0; - int nWindowID = 0; - xGLutWindowRef pWindow = NULL; - - // save the current window. - nSaveWindowID = glutGetWindow(); - - // for all windows... - for (nWindowID = 0; nWindowID < xGWin_knMaxNumWindows; nWindowID++) { - // try to get a window ptr. - xGWin_GetWindowFromID(nWindowID, &pWindow); - - // if we got one... - if (NULL != pWindow) { - // set the window - glutSetWindow(nWindowID); - - // post a redisplay for it. - glutPostRedisplay(); - } - } - - // restore the window. - glutSetWindow(nSaveWindowID); -} - -void xGWin_NewEvent(xGWin_tEventRef *oppEvent) -{ - xGWin_tEventRef this = NULL; - - // allocate event storage. - this = (xGWin_tEventRef)malloc(sizeof(xGWin_tEvent)); - - // set all to defaults. - this->mType = xGWin_tEventType_NoEvent; - this->mWhere.mnX = -1; - this->mWhere.mnY = -1; - this->mButton = -1; - this->mKey = (xGWin_tKey)' '; - this->mbCtrlKey = FALSE; - this->mbAltKey = FALSE; - this->mbShiftKey = FALSE; - - *oppEvent = this; -} - -void xGWin_DeleteEvent(xGWin_tEventRef *ioppEvent) -{ - xGWin_tEventRef this = NULL; - - this = *ioppEvent; - - // just delete the event. - free(this); - - *ioppEvent = NULL; -} - -void xGWin_DebugPrintEvent(xGWin_tEventRef this) -{ - DebugPrint(("XGWin_tEvent:\n")); - - switch (this->mType) { - case xGWin_tEventType_Draw: - DebugPrint(("\tType: Draw\n")); - break; - case xGWin_tEventType_KeyDown: - DebugPrint(("\tType: KeyDown\n")); - break; - case xGWin_tEventType_MouseDown: - DebugPrint(("\tType: MouseDown\n")); - break; - case xGWin_tEventType_MouseUp: - DebugPrint(("\tType: MouseUp\n")); - break; - case xGWin_tEventType_MouseMoved: - DebugPrint(("\tType: MouseMoved\n")); - break; - case xGWin_tEventType_Resize: - DebugPrint(("\tType: Resize\n")); - break; - default: - break; - } - - DebugPrint(("\tWhere: %d %d\n", this->mWhere.mnX, this->mWhere.mnY)); - DebugPrint(("\tButton: %d\n", this->mButton)); - DebugPrint(("\tKey: %c (%d)\n", this->mKey, (int)this->mKey)); - DebugPrint(("\tModifiers: ctrl %d alt %d shift %d\n", - (int)(this->mbCtrlKey), - (int)(this->mbAltKey), - (int)(this->mbShiftKey))); - DebugPrint(("\n")); -} - -#endif // #ifdef HAVE_OPENGL diff --git a/utils/xGrowableArray.c b/utils/xGrowableArray.c deleted file mode 100644 index aa4e2e1cbc6..00000000000 --- a/utils/xGrowableArray.c +++ /dev/null @@ -1,295 +0,0 @@ -/** - * @file xGrowableArray.c - * @brief arrays that grow - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.10 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "xGrowableArray.h" -#include -#include -#include "xDebug.h" - -char *xGArr_ksaErrorStrings[xGArr_knNumErrorCodes] = { - - "No error.", "Invalid object.", "Invalid signature.", "Allocation failed.", "Last item.", "Invalid error code."}; - -xGArr_tErr xGArr_New(xGrowableArrayRef *opList, int inSize, int inInitialNumItems) -{ - xGArr_tErr eResult = xGArr_tErr_NoErr; - xGrowableArrayRef this = NULL; - - this = (xGrowableArrayRef)malloc(sizeof(xGrowableArray)); - ; - if (NULL == this) { - eResult = xGArr_tErr_AllocationFailed; - goto error; - } - - /* init sig */ - this->mSignature = xGArr_kSignature; - - /* initial values */ - this->mnNumItems = 0; - this->mnMaxNumItems = inInitialNumItems; - this->mnItemSizeBytes = inSize; - this->mnMaxSizeBytes = inInitialNumItems * inSize; - this->mnNext = 0; - - /* allocate initial storage */ - this->mpData = malloc(this->mnMaxSizeBytes); - if (NULL == this->mpData) { - eResult = xGArr_tErr_AllocationFailed; - goto error; - } - - /* return us */ - *opList = this; - - goto cleanup; - -error: - - if (NULL != this) { - free(this); - } - - if (xGArr_tErr_NoErr != eResult) { - DebugPrint(("Error %d in xGArr_New: %s\n", eResult, xGArr_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -xGArr_tErr xGArr_Delete(xGrowableArrayRef *iopList) -{ - xGArr_tErr eResult = xGArr_tErr_NoErr; - xGrowableArrayRef this = NULL; - - if (iopList == NULL) { - eResult = xGArr_tErr_InvalidObject; - goto error; - } - - this = *iopList; - - eResult = xGArr_Verify(this); - if (xGArr_tErr_NoErr != eResult) { - goto error; - } - - /* trash sig */ - this->mSignature = 0x1; - - /* free us */ - free(this->mpData); - free(this); - - *iopList = NULL; - - goto cleanup; - -error: - - if (xGArr_tErr_NoErr != eResult) { - DebugPrint(("Error %d in xGArr_Delete: %s\n", eResult, xGArr_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -xGArr_tErr xGArr_Add(xGrowableArrayRef this, void *ipSrc) -{ - xGArr_tErr eResult = xGArr_tErr_NoErr; - void *pNewStorage = NULL; - - eResult = xGArr_Verify(this); - if (xGArr_tErr_NoErr != eResult) { - goto error; - } - - /* if our num items is not less than our max items.... */ - if (!(this->mnNumItems < this->mnMaxNumItems)) { - /* allocate twice the storage */ - pNewStorage = malloc(this->mnMaxSizeBytes * 2); - if (NULL == pNewStorage) { - eResult = xGArr_tErr_AllocationFailed; - goto error; - } - - /* copy our current data in */ - memmove(pNewStorage, this->mpData, this->mnMaxSizeBytes); - - /* delete old storage and point to new one */ - free(this->mpData); - this->mpData = pNewStorage; - pNewStorage = NULL; - - /* save our new storage size */ - this->mnMaxSizeBytes *= 2; - this->mnMaxNumItems = this->mnMaxSizeBytes / this->mnItemSizeBytes; - } - - /* copy data into this location */ - memmove(&((char *)this->mpData)[this->mnNumItems * this->mnItemSizeBytes], ipSrc, this->mnItemSizeBytes); - - /* inc num items */ - this->mnNumItems++; - - goto cleanup; - -error: - - if (xGArr_tErr_NoErr != eResult) { - DebugPrint(("Error %d in xGArr_Add: %s\n", eResult, xGArr_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -xGArr_tErr xGArr_ResetIterator(xGrowableArrayRef this) -{ - xGArr_tErr eResult = xGArr_tErr_NoErr; - - eResult = xGArr_Verify(this); - if (xGArr_tErr_NoErr != eResult) { - goto error; - } - - this->mnNext = 0; - - goto cleanup; - -error: - - if (xGArr_tErr_NoErr != eResult) { - DebugPrint(("Error %d in xGArr_ResetIterator: %s\n", eResult, xGArr_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -xGArr_tErr xGArr_NextItem(xGrowableArrayRef this, void *opDest) -{ - xGArr_tErr eResult = xGArr_tErr_NoErr; - - eResult = xGArr_Verify(this); - if (xGArr_tErr_NoErr != eResult) { - goto error; - } - - /* see if we're at the end */ - if (this->mnNext >= (this->mnNumItems)) { - eResult = xGArr_tErr_LastItem; - goto cleanup; - } - - /* return data at this location */ - memmove(opDest, &((char *)this->mpData)[this->mnNext * this->mnItemSizeBytes], this->mnItemSizeBytes); - - /* inc interator */ - this->mnNext++; - - goto cleanup; - -error: - - if (xGArr_tErr_NoErr != eResult) { - DebugPrint(("Error %d in xGArr_NextItem: %s\n", eResult, xGArr_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -xGArr_tErr xGArr_Clear(xGrowableArrayRef this) -{ - xGArr_tErr eResult = xGArr_tErr_NoErr; - - eResult = xGArr_Verify(this); - if (xGArr_tErr_NoErr != eResult) { - goto error; - } - - /* free our storage and realloc it */ - free(this->mpData); - this->mpData = malloc(this->mnMaxSizeBytes); - if (NULL == this->mpData) { - eResult = xGArr_tErr_AllocationFailed; - goto error; - } - - /* reset counter */ - this->mnNumItems = 0; - this->mnNext = 0; - - goto cleanup; - -error: - - if (xGArr_tErr_NoErr != eResult) { - DebugPrint(("Error %d in xGArr_Clear: %s\n", eResult, xGArr_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -xGArr_tErr xGArr_Verify(xGrowableArrayRef this) -{ - xGArr_tErr eResult = xGArr_tErr_NoErr; - - /* check for null ptr */ - if (NULL == this) { - eResult = xGArr_tErr_InvalidObject; - goto cleanup; - } - - /* check signature */ - if (xGArr_kSignature != this->mSignature) { - eResult = xGArr_tErr_InvalidSignature; - goto cleanup; - } - -cleanup: - - return eResult; -} - -char *xGArr_GetErrorString(xGArr_tErr ieCode) -{ - xGArr_tErr eCode = ieCode; - - if (ieCode < 0 || ieCode >= xGArr_knNumErrorCodes) { - eCode = xGArr_tErr_InvalidErrorCode; - } - - return xGArr_ksaErrorStrings[eCode]; -} diff --git a/utils/xList.c b/utils/xList.c deleted file mode 100644 index ca10c85d33c..00000000000 --- a/utils/xList.c +++ /dev/null @@ -1,632 +0,0 @@ -/** - * @file xList.c - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.9 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "xList.h" -#include -#include "xDebug.h" -#include "xTypes.h" - -static char *xList_ksaError[xList_knNumErrorCodes] = { - - "No error", - "List allocation failed.", - "Internal list allocation (RTS) failed.", - "Internal list deletion (RTS) failed.", - "List deleteion failed.", - "Invalid list pointer (was NULL).", - "List is full.", - "Item not in list.", - "Error finding item.", - "Error getting list size.", - "End of list.", - "List is empty.", - "Invalid error code."}; - -xList_tErr xList_New(xListRef *oppList) -{ - xListRef this = NULL; - xList_tErr eResult = xList_tErr_NoErr; - - // assume failure. - *oppList = NULL; - - // allocate our list structure and check it. - this = (xListRef)malloc(sizeof(xList)); - if (NULL == this) { - eResult = xList_tErr_AllocationFailed; - goto cleanup; - } - - // set the singnature. - this->mSignature = xList_kSignature; - - // null all ptrs - this->mpHead = NULL; - this->mpTail = NULL; - this->mpNext = NULL; - - /* no comparator by default */ - this->mComparator = NULL; - - // all good, set the outgoing ptr. - *oppList = this; - -cleanup: - - return eResult; -} - -xList_tErr xList_Delete(xListRef *ioppList) -{ - xListRef this = NULL; - xList_tErr eResult = xList_tErr_NoErr; - - // grab the list. - this = *ioppList; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // clear the list first. - xList_Clear(this); - - // mangle our signature - this->mSignature = 0x1; - - // delete our list structure. - free(this); - - // set list ptr to nil. - *ioppList = NULL; - -cleanup: - - return eResult; -} - -xList_tErr xList_InsertItem(xListRef this, void *ipItemToInsert) -{ - xList_tErr eResult = xList_tErr_NoErr; - xListNodeRef pNewNode = NULL; - tBoolean bIsInList = FALSE; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - /* make sure the item isn't already in here. */ - xList_IsInList(this, ipItemToInsert, &bIsInList); - if (bIsInList) { - goto cleanup; - } - - // make a new node. - pNewNode = (xListNodeRef)malloc(sizeof(xListNode)); - if (NULL == pNewNode) { - eResult = xList_tErr_InternalAllocationFailed; - goto cleanup; - } - - // set its data. - pNewNode->mSignature = xList_kSignature; - pNewNode->mpData = ipItemToInsert; - pNewNode->mpNext = NULL; - - // insert it at the tail. - if (NULL == this->mpHead) { - this->mpHead = pNewNode; - this->mpNext = pNewNode; - this->mpTail = pNewNode; - } - else { - this->mpTail->mpNext = pNewNode; - this->mpTail = pNewNode; - } - -cleanup: - - return eResult; -} - -xList_tErr xList_RemoveItem(xListRef this, void **iopItemToRemove) -{ - xList_tErr eResult = xList_tErr_NoErr; - xListNodeRef pCurNode = NULL; - xListNodeRef pBackNode = NULL; - tBoolean bFound = FALSE; - void *pItemToRemove = NULL; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // get the item to remove. - pItemToRemove = *iopItemToRemove; - - // scan through the list, keeping a back node. - pCurNode = this->mpHead; - while (NULL != pCurNode && !bFound) { - // compare the nodes. if we found it exit the loop. - if (xList_CompareItems_(this, pCurNode->mpData, pItemToRemove) == xList_tCompare_Match) { - bFound = TRUE; - } - else { - // next node. - pBackNode = pCurNode; - pCurNode = pCurNode->mpNext; - } - } - - // error if not found. - if (!bFound) { - eResult = xList_tErr_ItemNotInList; - goto cleanup; - } - - // remove this node. - if (NULL == pBackNode) { - // node to be deleted is head. - this->mpHead = pCurNode->mpNext; - } - else { - // wrap list around it. - pBackNode->mpNext = pCurNode->mpNext; - - // reattach tail if necessary. - if (this->mpTail == pCurNode) { - this->mpTail = pBackNode; - } - } - - // return the item. - *iopItemToRemove = pCurNode->mpData; - - // delete the node. - free(pCurNode); - -cleanup: - - return eResult; -} - -xList_tErr xList_IsInList(xListRef this, void *ipItemToFind, tBoolean *obpIsInList) -{ - xList_tErr eResult = xList_tErr_NoErr; - tBoolean bFound = FALSE; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // try and find the item. - bFound = (NULL != xList_FindItem_(this, ipItemToFind)); - - // set found var. - *obpIsInList = bFound; - -cleanup: - - return eResult; -} - -xListNodeRef xList_FindItem_(xListRef this, void *ipItem) -{ - xListNodeRef pCurNode = NULL; - - // if no comparator, return null. - if (NULL == this->mComparator) { - return NULL; - } - - // scan through the list. - pCurNode = this->mpHead; - while (NULL != pCurNode) { - // compare the nodes. if we found it, return it. - if (xList_CompareItems_(this, pCurNode->mpData, ipItem) == xList_tCompare_Match) { - return pCurNode; - } - else { - // next node. - pCurNode = pCurNode->mpNext; - } - } - - // not found. - return NULL; -} - -xList_tErr xList_Clear(xListRef this) -{ - xList_tErr eResult = xList_tErr_NoErr; - xListNodeRef pCurNode = NULL; - xListNodeRef pDelNode = NULL; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // go through the list...... - pCurNode = this->mpHead; - while (NULL != pCurNode) { - // mark this node. - pDelNode = pCurNode; - - // next node. - pCurNode = pCurNode->mpNext; - - // check the node. - if (xList_kSignature != pDelNode->mSignature) { - eResult = xList_tErr_InvalidListRef; - goto cleanup; - } - - // mangle sig. - pDelNode->mSignature = 0x1; - - // delete it. - free(pDelNode); - } - - this->mpHead = NULL; - this->mpTail = NULL; - this->mpNext = NULL; - -cleanup: - - return eResult; -} - -xList_tErr xList_GetCount(xListRef this, int *opnCount) -{ - xList_tErr eResult = xList_tErr_NoErr; - xListNodeRef pCurNode = NULL; - int nCount = 0; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // go through the list.. - nCount = 0; - pCurNode = this->mpHead; - while (NULL != pCurNode) { - // inc count - nCount++; - - // next node. - pCurNode = pCurNode->mpNext; - } - - // return count. - *opnCount = nCount; - -cleanup: - - return eResult; -} - -xList_tErr xList_GetFirstItem(xListRef this, void **oppFirstItem) -{ - xList_tErr eResult = xList_tErr_NoErr; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // assume failure. - *oppFirstItem = NULL; - - // if there's a head... - if (this->mpHead) { - // return the data ptr. - *oppFirstItem = this->mpHead->mpData; - } - else { - eResult = xList_tErr_ListEmpty; - } - -cleanup: - - return eResult; -} - -xList_tErr xList_GetNextItem(xListRef this, void *ipCurrentItem, void **oppNextItem) -{ - xList_tErr eResult = xList_tErr_NoErr; - xListNodeRef pCurNode = NULL; - void *pNextItem = NULL; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // assume failure. - *oppNextItem = FALSE; - - // try to find the item. - pCurNode = xList_FindItem_(this, ipCurrentItem); - if (NULL != pCurNode) { - // if there's a next one... - if (NULL != pCurNode->mpNext) { - // get its data. - pNextItem = ((xListNodeRef)pCurNode->mpNext)->mpData; - } - else { - // end of list. - eResult = xList_tErr_EndOfList; - } - } - else { - // couldn't find item. - eResult = xList_tErr_ItemNotInList; - } - - // return the result. - *oppNextItem = pNextItem; - -cleanup: - - return eResult; -} - -xList_tErr xList_ResetPosition(xListRef this) -{ - xList_tErr eResult = xList_tErr_NoErr; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // set current ptr to head. - this->mpNext = this->mpHead; - -cleanup: - - return eResult; -} - -xList_tErr xList_GetNextItemFromPosition(xListRef this, void **oppNextItem) -{ - xList_tErr eResult = xList_tErr_NoErr; - void *pNextItem = NULL; - - // assume failure. - *oppNextItem = FALSE; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // make sure we have an item. - if (NULL == this->mpNext) { - eResult = xList_tErr_EndOfList; - goto cleanup; - } - - // verify this item. - if (xList_kSignature != this->mpNext->mSignature) { - eResult = xList_tErr_InvalidListRef; - goto cleanup; - } - - // get its item. - pNextItem = this->mpNext->mpData; - - // advance the ptr. - this->mpNext = this->mpNext->mpNext; - - // return the ptr. - *oppNextItem = pNextItem; - -cleanup: - - return eResult; -} - -xList_tErr xList_NextFromPos(xListRef this, void **oppNextItem) -{ - return xList_GetNextItemFromPosition(this, oppNextItem); -} - -xList_tErr xList_PushItem(xListRef this, void *ipItemToInsert) -{ - xList_tErr eResult = xList_tErr_NoErr; - xListNodeRef pNewNode = NULL; - tBoolean bIsInList = FALSE; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - /* make sure the item isn't already in here. */ - xList_IsInList(this, ipItemToInsert, &bIsInList); - if (bIsInList) { - goto cleanup; - } - - // make a new node. - pNewNode = (xListNodeRef)malloc(sizeof(xListNode)); - if (NULL == pNewNode) { - eResult = xList_tErr_InternalAllocationFailed; - goto cleanup; - } - - // set its data. - pNewNode->mSignature = xList_kSignature; - pNewNode->mpData = ipItemToInsert; - pNewNode->mpNext = NULL; - - // insert it at the head. - if (NULL == this->mpHead) { - this->mpHead = pNewNode; - this->mpNext = pNewNode; - this->mpTail = pNewNode; - } - else { - pNewNode->mpNext = this->mpHead; - this->mpHead = pNewNode; - } - -cleanup: - - return eResult; -} - -xList_tErr xList_PopItem(xListRef this, void **oppItem) -{ - xList_tErr eResult = xList_tErr_NoErr; - xListNodeRef pDelNode = NULL; - void *pItem = NULL; - - // assume failure. - *oppItem = FALSE; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - // make sure we have a head. - if (NULL == this->mpHead) { - eResult = xList_tErr_EndOfList; - goto cleanup; - } - - // verify this item. - if (xList_kSignature != this->mpHead->mSignature) { - eResult = xList_tErr_InvalidListRef; - goto cleanup; - } - - // get the head's data. - pItem = this->mpHead->mpData; - - // remove the head. - pDelNode = this->mpHead; - this->mpHead = this->mpHead->mpNext; - - // delete the head. - free(pDelNode); - - // return the item. - *oppItem = pItem; - -cleanup: - - return eResult; -} - -xList_tErr xList_SetComparator(xListRef this, xList_tCompare (*iComparator)(void *, void *)) -{ - xList_tErr eResult = xList_tErr_NoErr; - - // verify the list. - eResult = xList_Verify(this); - if (xList_tErr_NoErr != eResult) { - goto cleanup; - } - - /* set the comparator */ - this->mComparator = iComparator; - - goto cleanup; - -cleanup: - - return eResult; -} - -xList_tCompare xList_CompareItems_(xListRef this, void *pItemA, void *pItemB) -{ - xList_tCompare eResult = xList_tCompare_Match; - - if (this->mComparator) { - eResult = this->mComparator(pItemA, pItemB); - } - else { - if (pItemA == pItemB) { - eResult = xList_tCompare_Match; - } - else { - eResult = xList_tCompare_GreaterThan; - } - } - - return eResult; -} - -xList_tErr xList_Verify(xListRef this) -{ - xList_tErr eResult = xList_tErr_NoErr; - - // check pointer. - if (NULL == this) { - eResult = xList_tErr_InvalidListRef; - goto cleanup; - } - - // check signature. - if (xList_kSignature != this->mSignature) { - eResult = xList_tErr_InvalidListRef; - goto cleanup; - } - -cleanup: - - return eResult; -} - -char *xList_GetErrorString(xList_tErr ieCode) -{ - xList_tErr eCode = ieCode; - - if (ieCode < xList_tErr_NoErr || ieCode >= xList_knNumErrorCodes) { - eCode = xList_tErr_InvalidErrorCode; - } - - return xList_ksaError[eCode]; -} diff --git a/utils/xSparseVolume.c b/utils/xSparseVolume.c deleted file mode 100644 index 49b76e3a45c..00000000000 --- a/utils/xSparseVolume.c +++ /dev/null @@ -1,380 +0,0 @@ -/** - * @file xSparseVolume.c - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.9 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "xSparseVolume.h" -#include -#include -#include -#include "xDebug.h" - -char *xSVol_ksaErrorStrings[xSVol_knNumErrorCodes] = { - - "No error.", - "Invalid pointer to object.", - "Invalid parameter.", - "Invalid signature.", - "Memory allocation failed.", - "Item not found.", - "Index out of bounds.", - "Index not allocated.", - "Invalid error code."}; - -xSVol_tErr xSVol_New(xSparseVolumeRef *opVolume, int inXDim, int inYDim, int inZDim) -{ - xSVol_tErr eResult = xSVol_tErr_NoErr; - xSparseVolumeRef this = NULL; - - if (NULL == opVolume || inXDim < 0 || inYDim < 0 || inZDim < 0) { - eResult = xSVol_tErr_InvalidParameter; - goto error; - } - - /* allocate us */ - this = (xSparseVolumeRef)malloc(sizeof(xSparseVolume)); - if (NULL == this) { - eResult = xSVol_tErr_AllocationFailed; - goto error; - } - - /* set signature and defaults */ - this->mSignature = xSVol_kSignature; - this->mnXDim = inXDim; - this->mnYDim = inYDim; - this->mnZDim = inZDim; - - /* allocate the zs */ - this->mStorage = (void ****)malloc(sizeof(void ***) * this->mnZDim); - if (NULL == this->mStorage) { - eResult = xSVol_tErr_AllocationFailed; - goto error; - } - memset(this->mStorage, 0, sizeof(void ***) * this->mnZDim); - - /* return us */ - *opVolume = this; - - goto cleanup; - -error: - - DebugPrint(("Error %d in xSVol_New: %s\n", eResult, xSVol_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xSVol_tErr xSVol_Delete(xSparseVolumeRef *iopVolume, xSVol_tDeleteEntryFuncPtr ipDeleteFunc) -{ - xSVol_tErr eResult = xSVol_tErr_NoErr; - xSparseVolumeRef this = NULL; - - if (NULL == iopVolume) { - eResult = xSVol_tErr_InvalidParameter; - goto error; - } - - this = *iopVolume; - eResult = xSVol_Verify(this); - if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - /* first purge the volume */ - eResult = xSVol_Purge(this, ipDeleteFunc); - if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - /* trash signature */ - this->mSignature = 0x1; - - /* delete us */ - free(this); - - /* return null */ - *iopVolume = NULL; - - goto cleanup; - -error: - - DebugPrint(("Error %d in xSVol_Delete: %s\n", eResult, xSVol_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xSVol_tErr xSVol_Get(xSparseVolumeRef this, xVoxelRef iWhere, void **oppItem) -{ - xSVol_tErr eResult = xSVol_tErr_NoErr; - void *pItem = NULL; - - eResult = xSVol_Verify(this); - if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - if (NULL == iWhere || NULL == oppItem) { - eResult = xSVol_tErr_InvalidParameter; - goto error; - } - - /* look at the index */ - eResult = xSVol_VerifyIndex_(this, iWhere); - - /* if it's not allocated, item is null. */ - if (xSVol_tErr_IndexNotAllocated == eResult) { - pItem = NULL; - eResult = xSVol_tErr_NoErr; - } - else if (xSVol_tErr_NoErr != eResult) { - goto error; - } - else { - /* find the item. */ - pItem = this->mStorage[xVoxl_GetZ(iWhere)][xVoxl_GetY(iWhere)][xVoxl_GetX(iWhere)]; - } - - /* return the item */ - *oppItem = pItem; - - goto cleanup; - -error: - - DebugPrint(("Error %d in xSVol_Get: %s\n", eResult, xSVol_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xSVol_tErr xSVol_Set(xSparseVolumeRef this, xVoxelRef iWhere, void *ipItem) -{ - xSVol_tErr eResult = xSVol_tErr_NoErr; - - eResult = xSVol_Verify(this); - if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - /* look at the index */ - eResult = xSVol_VerifyIndex_(this, iWhere); - - /* if it's not allocated, allocate it. */ - if (xSVol_tErr_IndexNotAllocated == eResult) { - /* allocate a y array */ - if (NULL == this->mStorage[xVoxl_GetZ(iWhere)]) { - this->mStorage[xVoxl_GetZ(iWhere)] = (void ***)malloc(sizeof(void **) * this->mnYDim); - if (NULL == this->mStorage) { - eResult = xSVol_tErr_AllocationFailed; - goto error; - } - memset(this->mStorage[xVoxl_GetZ(iWhere)], 0, sizeof(void *) * this->mnYDim); - } - - /* allocate an x array */ - if (NULL == this->mStorage[xVoxl_GetZ(iWhere)][xVoxl_GetY(iWhere)]) { - this->mStorage[xVoxl_GetZ(iWhere)][xVoxl_GetY(iWhere)] = (void **)malloc(sizeof(void *) * this->mnXDim); - if (NULL == this->mStorage) { - eResult = xSVol_tErr_AllocationFailed; - goto error; - } - memset(this->mStorage[xVoxl_GetZ(iWhere)][xVoxl_GetY(iWhere)], 0, sizeof(void **) * this->mnXDim); - } - - /* clear the error */ - eResult = xSVol_tErr_NoErr; - } - else if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - /* set the item. */ - this->mStorage[xVoxl_GetZ(iWhere)][xVoxl_GetY(iWhere)][xVoxl_GetX(iWhere)] = ipItem; - - goto cleanup; - -error: - - DebugPrint(("Error %d in xSVol_Set: %s\n", eResult, xSVol_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xSVol_tErr xSVol_Purge(xSparseVolumeRef this, xSVol_tDeleteEntryFuncPtr ipDeleteFunc) -{ - xSVol_tErr eResult = xSVol_tErr_NoErr; - int nZ = 0; - int nY = 0; - - eResult = xSVol_Verify(this); - if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - /* visit every node with the delete function */ - eResult = xSVol_VisitAll(this, ipDeleteFunc, NULL, NULL, NULL); - if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - /* for every y and z, delete the arrays */ - for (nZ = 0; nZ < this->mnZDim; nZ++) { - if (NULL != this->mStorage[nZ]) { - for (nY = 0; nY < this->mnYDim; nY++) { - if (NULL != this->mStorage[nZ][nY]) { - free(this->mStorage[nZ][nY]); - } - } - free(this->mStorage[nZ]); - } - } - - /* zero the z array */ - memset(this->mStorage, 0, sizeof(void ***) * this->mnZDim); - - goto cleanup; - -error: - - DebugPrint(("Error %d in xSVol_Purge: %s\n", eResult, xSVol_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xSVol_tErr xSVol_VisitAll(xSparseVolumeRef this, - void (*ipVisitFunction)(void *ipItem), - void (*ipXFunction)(int inIndex, tBoolean bEntering), - void (*ipYFunction)(int inIndex, tBoolean bEntering), - void (*ipZFunction)(int inIndex, tBoolean bEntering)) -{ - xSVol_tErr eResult = xSVol_tErr_NoErr; - int nX = 0; - int nY = 0; - int nZ = 0; - - eResult = xSVol_Verify(this); - if (xSVol_tErr_NoErr != eResult) { - goto error; - } - - for (nZ = 0; nZ < this->mnZDim; nZ++) { - if (NULL != this->mStorage[nZ]) { - if (NULL != ipZFunction) { - ipZFunction(nZ, TRUE); - } - for (nY = 0; nY < this->mnYDim; nY++) { - if (NULL != this->mStorage[nZ][nY]) { - if (NULL != ipYFunction) { - ipYFunction(nY, TRUE); - } - for (nX = 0; nX < this->mnXDim; nX++) { - if (NULL != this->mStorage[nZ][nY][nX]) { - if (NULL != ipXFunction) { - ipXFunction(nX, TRUE); - } - if (NULL != ipVisitFunction) { - ipVisitFunction(this->mStorage[nZ][nY][nX]); - } - if (NULL != ipXFunction) { - ipXFunction(nX, FALSE); - } - } - } - if (NULL != ipYFunction) { - ipYFunction(nY, FALSE); - } - } - } - if (NULL != ipZFunction) { - ipZFunction(nZ, FALSE); - } - } - } - - goto cleanup; - -error: - - DebugPrint(("Error %d in xSVol_: %s\n", eResult, xSVol_GetErrorString(eResult))); - -cleanup: - - return eResult; -} - -xSVol_tErr xSVol_VerifyIndex_(xSparseVolumeRef this, xVoxelRef iIndex) -{ - /* check for bounds */ - if (xVoxl_GetX(iIndex) < 0 || xVoxl_GetX(iIndex) >= this->mnXDim || xVoxl_GetY(iIndex) < 0 || - xVoxl_GetY(iIndex) >= this->mnYDim || xVoxl_GetZ(iIndex) < 0 || xVoxl_GetZ(iIndex) >= this->mnZDim) { - return xSVol_tErr_IndexOutOfBounds; - } - - /* check if it exists */ - if (NULL != this->mStorage[xVoxl_GetZ(iIndex)] && NULL != this->mStorage[xVoxl_GetZ(iIndex)][xVoxl_GetY(iIndex)]) { - return xSVol_tErr_NoErr; - } - else { - return xSVol_tErr_IndexNotAllocated; - } -} - -char *xSVol_GetErrorString(xSVol_tErr ieCode) -{ - xSVol_tErr eCode = ieCode; - - if (ieCode < 0 || ieCode >= xSVol_knNumErrorCodes) { - eCode = xSVol_tErr_InvalidErrorCode; - } - - return xSVol_ksaErrorStrings[eCode]; -} - -xSVol_tErr xSVol_Verify(xSparseVolumeRef this) -{ - xSVol_tErr eResult = xSVol_tErr_NoErr; - - /* check for null ptr */ - if (NULL == this) { - eResult = xSVol_tErr_InvalidObject; - goto cleanup; - } - - /* check signature */ - if (xSVol_kSignature != this->mSignature) { - eResult = xSVol_tErr_InvalidSignature; - goto cleanup; - } - -cleanup: - - return eResult; -} diff --git a/utils/xTypes.c b/utils/xTypes.cpp similarity index 100% rename from utils/xTypes.c rename to utils/xTypes.cpp diff --git a/utils/xUndoList.c b/utils/xUndoList.c deleted file mode 100644 index de68a6ef5ce..00000000000 --- a/utils/xUndoList.c +++ /dev/null @@ -1,460 +0,0 @@ -/** - * @file xUndoList.c - * @brief general-purpose utils - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.12 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "xUndoList.h" -#include -#include "xDebug.h" - -static char *xUndL_ksaError[xUndL_knNumErrorCodes] = { - - "No error.", - "Allocation of undo list structure failed.", - "Allocation of internal list structure failed.", - "Couldn't delete items from list.", - "Couldn't delete list.", - "Invalid swap or delete function ptr.", - "Couldn't add item to list.", - "Couldn't retrieve item from list.", - "Couldn't allocate swap list (non-fatal).", - "Couldn't add item to swap list (non-fatal).", - "Invalid undo list ptr.", - "Failed to clear the list.", - "Failed to count items in the list.", - "Failed to reset the list position.", - "Invalid print function.", - "Invalid error code."}; - -xUndL_tErr xUndL_New(xUndoListRef *oppList, - xUndL_tSwapFuncPtr ipSwapFunction, - xUndL_tDeleteEntryFuncPtr ipDeleteFunction) -{ - xUndoListRef this = NULL; - xUndL_tErr eResult = xUndL_tErr_NoErr; - - // assume failure. - *oppList = NULL; - - // check our functions. - if (NULL == ipSwapFunction || NULL == ipDeleteFunction) { - eResult = xUndL_tErr_InvalidFunctionPtr; - goto cleanup; - } - - // allocate our private structure. - this = (xUndoListRef)malloc(sizeof(xUndoList)); - if (NULL == this) { - eResult = xUndL_tErr_AllocationFailed; - goto cleanup; - } - - // set the sig. - this->mSignature = xUndL_kSignature; - - // allocate us a list. - eResult = xUndL_NewList_(&(this->mpList)); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // set the function ptrs. - this->mpSwapFunction = ipSwapFunction; - this->mpDeleteFunction = ipDeleteFunction; - this->mpPrintFunction = NULL; - - // return our list; - *oppList = this; - -cleanup: - - return eResult; -} - -xUndL_tErr xUndL_NewList_(xListRef *oppList) -{ - xListRef pList = NULL; - xList_tErr eListResult = xList_tErr_NoErr; - xUndL_tErr eResult = xUndL_tErr_NoErr; - - // assume failure. - *oppList = NULL; - - // try to allocate our xList. - eListResult = xList_New(&pList); - if (xList_tErr_NoErr != eListResult) { - eResult = xUndL_tErr_InternalAllocationFailed; - goto cleanup; - } - - // set the list. - *oppList = pList; - -cleanup: - - return eResult; -} - -xUndL_tErr xUndL_Delete(xUndoListRef *ioppList) -{ - xUndoListRef this = NULL; - xUndL_tErr eResult = xUndL_tErr_NoErr; - - // get and verify ourself. - this = *ioppList; - eResult = xUndL_Verify(this); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // delete the internal structure. - eResult = xUndL_DeleteList_(this, &(this->mpList)); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // mangle our signature - this->mSignature = 0x1; - - // delete the structure - free(this); - - // set outgoing ptr. - *ioppList = NULL; - -cleanup: - - return eResult; -} - -xUndL_tErr xUndL_DeleteList_(xUndoListRef ipUndoList, xListRef *ioppList) -{ - xUndL_tErr eResult = xUndL_tErr_NoErr; - xListRef pList = NULL; - xList_tErr eListResult = xList_tErr_NoErr; - xUndL_tEntryPtr pEntry = NULL; - - // get the list. - pList = *ioppList; - - // we need to pop every entry off the list... - pEntry = NULL; - eListResult = xList_tErr_NoErr; - while (xList_tErr_NoErr == eListResult) { - eListResult = xList_PopItem(pList, (void **)&pEntry); - - // if we got one, call our delete function on it. - if (pEntry) { - ipUndoList->mpDeleteFunction(&pEntry); - } - } - - // check for odd results. - if (xList_tErr_EndOfList != eListResult) { - eResult = xUndL_tErr_ItemDeletionFailed; - goto cleanup; - } - - // now delete the list. - eListResult = xList_Delete(&pList); - if (xList_tErr_NoErr != eListResult) { - eResult = xUndL_tErr_ListDeletionFailed; - goto cleanup; - } - -cleanup: - - DebugCode if (xList_tErr_NoErr != eListResult) - { - DebugPrint(("xUndL_DeleteInternalList(): Error in xList function %d: %s\n", - eListResult, - xList_GetErrorString(eListResult))); - } - EndDebugCode; - - return eResult; -} - -xUndL_tErr xUndL_Clear(xUndoListRef ipList) -{ - xUndoListRef this = NULL; - xUndL_tErr eResult = xUndL_tErr_NoErr; - xList_tErr eListResult = xList_tErr_NoErr; - xUndL_tEntryPtr pEntry = NULL; - - // get and verify ourself. - this = ipList; - eResult = xUndL_Verify(this); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // we need to pop every entry off the list... - pEntry = NULL; - eListResult = xList_tErr_NoErr; - while (xList_tErr_NoErr == eListResult) { - eListResult = xList_PopItem(this->mpList, (void **)&pEntry); - - // if we got one, call our delete function on it. - if (pEntry) { - this->mpDeleteFunction(&pEntry); - } - } - -cleanup: - - return eResult; -} - -xUndL_tErr xUndL_AddEntry(xUndoListRef ipList, xUndL_tEntryPtr ipEntry) -{ - xUndoListRef this = NULL; - xUndL_tErr eResult = xUndL_tErr_NoErr; - xList_tErr eListResult = xList_tErr_NoErr; - - // get and verify ourself. - this = ipList; - eResult = xUndL_Verify(this); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - /* push the entry on the list. we want to - actually add the ptr to the ptr to the - list, not thing it points to, so pass - in a ptr to the in ptr. */ - eListResult = xList_PushItem(this->mpList, ipEntry); - if (xList_tErr_NoErr != eListResult) { - eResult = xUndL_tErr_InsertionFailed; - goto cleanup; - } - -cleanup: - - DebugCode if (xList_tErr_NoErr != eListResult) - { - DebugPrint(("xUndL_AddEntry(): Error in xList function %d: %s\n", eListResult, xList_GetErrorString(eListResult))); - } - EndDebugCode; - - return eResult; -} - -xUndL_tErr xUndL_Restore(xUndoListRef ipList) -{ - xUndoListRef this = NULL; - xUndL_tErr eResult = xUndL_tErr_NoErr; - xListRef pSwapList = NULL; - xList_tErr eListResult = xList_tErr_NoErr; - xUndL_tEntryPtr pItem = NULL; - xUndL_tEntryPtr pSwapItem = NULL; - - // get and verify ourself. - this = ipList; - eResult = xUndL_Verify(this); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // make a swap list. - eResult = xUndL_NewList_(&pSwapList); - if (xUndL_tErr_NoErr != eResult) { - // if error, just mark the swap list empty, not the end of the world. - eResult = xUndL_tErr_AllocationOfSwapListFailed; - pSwapList = NULL; - } - - // pop every item on the list. for each one... - eListResult = xList_tErr_NoErr; - while (xList_tErr_EndOfList != eListResult) { - // pop the item. - eListResult = xList_PopItem(this->mpList, (void **)&pItem); - - // if we got one.. - if (NULL != pItem) { - // call our swap function on it. - this->mpSwapFunction(pItem, (void **)&pSwapItem); - - // if we have a swap list.. - if (NULL != pSwapList) { - // add the swapped item to the swap list. - eListResult = xList_PushItem(pSwapList, pSwapItem); - if (xList_tErr_NoErr != eListResult) { - eResult = xUndL_tErr_SwapListInsertionFailed; - goto cleanup; - } - } - - // call the deletion function on the item. - this->mpDeleteFunction(&pItem); - } - } - - // clear the end of list flag - if (xList_tErr_EndOfList == eListResult) { - eListResult = xList_tErr_NoErr; - } - else { - goto cleanup; - } - - // if we have a swap list... - if (NULL != pSwapList) { - // delete the old list. - eResult = xUndL_DeleteList_(this, &(this->mpList)); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // make our swap list the new one. - this->mpList = pSwapList; - } - -cleanup: - - DebugCode if (xList_tErr_NoErr != eListResult) - { - DebugPrint( - ("xUndL_RestoreList(): Error in xList function %d: %s\n", eListResult, xList_GetErrorString(eListResult))); - } - EndDebugCode; - - return eResult; -} - -xUndL_tErr xUndL_SetPrintFunction(xUndoListRef this, xUndL_tPrintEntryFuncPtr ipPrintFunction) -{ - xUndL_tErr eResult = xUndL_tErr_NoErr; - - // verify ourself. - eResult = xUndL_Verify(this); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // set the function. - this->mpPrintFunction = ipPrintFunction; - -cleanup: - - return eResult; -} - -xUndL_tErr xUndL_Print(xUndoListRef this) -{ - xUndL_tErr eResult = xUndL_tErr_NoErr; - xList_tErr eListResult = xList_tErr_NoErr; - xUndL_tEntryPtr pItem = NULL; - int nCount = 0; - - // verify ourself. - eResult = xUndL_Verify(this); - if (xUndL_tErr_NoErr != eResult) { - goto cleanup; - } - - // make sure we have a print function. - if (NULL == this->mpPrintFunction) { - eResult = xUndL_tErr_InvalidPrintFunction; - goto cleanup; - } - - DebugPrint(("Printing undo list....\n")); - - // get the count - eListResult = xList_GetCount(this->mpList, &nCount); - if (xList_tErr_NoErr != eListResult) { - eResult = xUndL_tErr_ListCountFailed; - goto cleanup; - } - - DebugPrint(("\nNum items = %d\n", nCount)); - - // start at the beginning. - eListResult = xList_ResetPosition(this->mpList); - if (xList_tErr_NoErr != eListResult) { - eResult = xUndL_tErr_ListResetFailed; - goto cleanup; - } - - // traverse the list. - pItem = NULL; - eListResult = xList_tErr_NoErr; - while (eListResult != xList_tErr_EndOfList) { - eListResult = xList_GetNextItemFromPosition(this->mpList, (void **)&pItem); - if (xList_tErr_NoErr != eListResult && xList_tErr_EndOfList != eListResult) { - eResult = xUndL_tErr_RetrievalFailed; - goto cleanup; - } - - // if we got an item, print it. - if (pItem) { - DebugPrint(("\t")); - this->mpPrintFunction(pItem); - } - } - - DebugPrint(("\tDone.\n\n")); - -cleanup: - - DebugCode if (xList_tErr_NoErr != eListResult) - { - DebugPrint(("xUndL_PrintList(): Error in xList function %d: %s\n", eListResult, xList_GetErrorString(eListResult))); - } - EndDebugCode; - - return eResult; -} - -xUndL_tErr xUndL_Verify(xUndoListRef ipList) -{ - xUndL_tErr eResult = xUndL_tErr_NoErr; - - // check for a null list ptr. - if (NULL == ipList) { - eResult = xUndL_tErr_InvalidListPtr; - } - - // check for our sig. - if (ipList->mSignature != xUndL_kSignature) { - eResult = xUndL_tErr_InvalidListPtr; - } - - // check for null function ptrs. - if (NULL == ipList->mpSwapFunction || NULL == ipList->mpDeleteFunction) { - eResult = xUndL_tErr_InvalidFunctionPtr; - } - - return eResult; -} - -char *xUndL_GetErrorString(xUndL_tErr ieCode) -{ - xUndL_tErr eCode = ieCode; - - if (ieCode < xUndL_tErr_NoErr || ieCode >= xUndL_knNumErrorCodes) { - eCode = xUndL_tErr_InvalidErrorCode; - } - - return xUndL_ksaError[eCode]; -} diff --git a/utils/xUtilities.c b/utils/xUtilities.c deleted file mode 100644 index f44cbf8d815..00000000000 --- a/utils/xUtilities.c +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @file xUtilities.c - * @brief general purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.11 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "xUtilities.h" -#include -#include -#include -#include -#include -#include -#include - -char *xUtil_ksaErrorString[xUtil_tErr_knNumErrorCodes] = {"No error.", "Invalid error code."}; - -int xUtil_gCancelListening = 0; -int xUtil_gCancelUserCanceled = 0; - -xUtil_tErr xUtil_BreakStringIntoPathAndStem(char *isPathAndStem, char *osPath, char *osStem) -{ - xUtil_tErr eResult = xUtil_tErr_NoError; - char *sSection = ""; - char sPathSection[20][60]; - int nSection = 0; - int nNumSections = 0; - - sSection = strtok(isPathAndStem, "/"); - if (NULL == sSection) { - /* no path, for some reason */ - strcpy(osPath, ""); - strcpy(osStem, isPathAndStem); - goto cleanup; - } - else { - /* got the first section of the path, now get the rest. */ - strcpy(sPathSection[0], sSection); - nSection = 1; - while (NULL != (sSection = strtok(NULL, "/"))) { - strcpy(sPathSection[nSection++], sSection); - } - - /* the last part was the stem */ - strcpy(osStem, sPathSection[--nSection]); - - /* now build the path into a single string */ - nNumSections = nSection; - strcpy(osPath, ""); - for (nSection = 0; nSection < nNumSections; nSection++) { - sprintf(osPath, "%s/%s", osPath, sPathSection[nSection]); - } - } - - goto cleanup; - - goto error; -error: - - if (xUtil_tErr_NoError != eResult) { - DebugPrint(("Error %d in xUtil_BreakStringIntoPathAndStem: %s\n", eResult, xUtil_GetErrorString(eResult))); - } - -cleanup: - - return eResult; -} - -char *xUtil_GetErrorString(xUtil_tErr ieCode) -{ - xUtil_tErr eCode = ieCode; - - if (ieCode < 0 || ieCode >= xUtil_tErr_knNumErrorCodes) { - eCode = xUtil_tErr_InvalidErrorCode; - } - - return xUtil_ksaErrorString[eCode]; -} - -struct timeval sStartTime = {}; -struct timeval sEndTime = {}; - -void xUtil_StartTimer() { gettimeofday(&sStartTime, NULL); } - -void xUtil_StopTimer(char *isMessage) -{ - gettimeofday(&sEndTime, NULL); - - if (NULL != isMessage) { - DebugPrint(("%s: %lu usec\n", - isMessage, - (sEndTime.tv_sec * 1000000 + sEndTime.tv_usec) - (sStartTime.tv_sec * 1000000 + sStartTime.tv_usec))); - } - else { - DebugPrint(("Timer stopped: %lu usec\n", - (sEndTime.tv_sec * 1000000 + sEndTime.tv_usec) - (sStartTime.tv_sec * 1000000 + sStartTime.tv_usec))); - } -} - -void xUtil_strcpy(char *ipDest, char *ipSrc) { strcpy(ipDest, ipSrc); } - -void xUtil_strncpy(char *ipDest, char *ipSrc, int inSize) -{ - strncpy(ipDest, ipSrc, inSize); - - if (ipDest[inSize - 1] != '\0') { - ipDest[inSize - 1] = '\0'; - - DebugPrint(("xUtil_strncpy: Buffer overflow while %s (inSize=%d)\n", DebugGetNote, inSize)); - xDbg_PrintStack(); - } -} - -void xUtil_sprintf(char *ipDest, char *isFormat, ...) -{ - va_list args; - - va_start(args, isFormat); - vsprintf(ipDest, isFormat, args); - va_end(args); -} - -void xUtil_snprintf(char *ipDest, int inSize, char *isFormat, ...) -{ - va_list args; - - memset(ipDest, 0, inSize); - - va_start(args, isFormat); -#ifdef IRIX - vsprintf(ipDest, isFormat, args); -#else - vsnprintf(ipDest, inSize, isFormat, args); -#endif - va_end(args); - - if (ipDest[inSize - 1] != '\0') { - ipDest[inSize - 1] = '\0'; - - DebugPrint(("xUtil_snprintf: Buffer overflow while %s (inSize=%d)\n", DebugGetNote, inSize)); - DebugPrintStack; - } -} - -void xUtil_InitializeUserCancel() -{ - /* init the flags and register our handler. */ - xUtil_gCancelListening = 0; - xUtil_gCancelUserCanceled = 0; - signal(SIGINT, xUtil_HandleUserCancelCallback); -} - -void xUtil_StartListeningForUserCancel() -{ - /* set our listening flag. */ - xUtil_gCancelListening = 1; -} - -void xUtil_StopListeningForUserCancel() -{ - /* stop listening and reset the canceled flag. */ - xUtil_gCancelListening = 0; - xUtil_gCancelUserCanceled = 0; -} - -int xUtil_DidUserCancel() -{ - /* just return the canceled flag. */ - return xUtil_gCancelUserCanceled; -} - -void xUtil_HandleUserCancelCallback(int signal) -{ - /* if we're listening, set the flag, if not, exit normally. */ - if (xUtil_gCancelListening) { - xUtil_gCancelUserCanceled = 1; - } - else { - printf("Killed\n"); - fflush(stdout); - exit(1); - } -} diff --git a/utils/xVoxel.c b/utils/xVoxel.c deleted file mode 100644 index 56db43c5743..00000000000 --- a/utils/xVoxel.c +++ /dev/null @@ -1,206 +0,0 @@ -/** - * @file xVoxel.c - * @brief general-purpose utils - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:55 $ - * $Revision: 1.15 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include "xVoxel.h" -#include -#include -#include "xDebug.h" - -void xVoxl_New(xVoxelRef *oppVoxel) -{ - xVoxelRef this = (xVoxelRef)calloc(1, sizeof(xVoxel)); - *oppVoxel = this; -} - -void xVoxl_Delete(xVoxelRef *ioppVoxel) -{ - xVoxelRef this = NULL; - - if (NULL == ioppVoxel) { - return; - } - - this = *ioppVoxel; - - free(this); - *ioppVoxel = NULL; -} - -void xVoxl_Copy(xVoxelRef ipVoxDest, xVoxelRef ipVoxSrc) -{ - xVoxl_SetFloat(ipVoxDest, xVoxl_GetFloatX(ipVoxSrc), xVoxl_GetFloatY(ipVoxSrc), xVoxl_GetFloatZ(ipVoxSrc)); -} - -char xVoxl_IsEqualInt(xVoxelRef ipVox1, xVoxelRef ipVox2) -{ - if (xVoxl_GetX(ipVox1) == xVoxl_GetX(ipVox2) && xVoxl_GetY(ipVox1) == xVoxl_GetY(ipVox2) && - xVoxl_GetZ(ipVox1) == xVoxl_GetZ(ipVox2)) { - return TRUE; - } - else { - return FALSE; - } -} - -char xVoxl_IsEqualFloat(xVoxelRef ipVox1, xVoxelRef ipVox2) -{ - if (fabs(xVoxl_GetFloatX(ipVox1) - xVoxl_GetFloatX(ipVox2)) < 0.0001 && - fabs(xVoxl_GetFloatY(ipVox1) - xVoxl_GetFloatY(ipVox2)) < 0.0001 && - fabs(xVoxl_GetFloatZ(ipVox1) - xVoxl_GetFloatZ(ipVox2)) < 0.0001) { - return TRUE; - } - else { - return FALSE; - } -} - -/* declare non-macro versions of this stuff. */ -#ifndef XVOXL_USE_MACROS - -void xVoxl_Set(xVoxelRef this, int x, int y, int z) -{ - this->mfX = x; - this->mfY = y; - this->mfZ = z; -} - -int xVoxl_GetX(xVoxelRef this) { return (int)(floor(this->mfX + 0.5)); } - -int xVoxl_GetY(xVoxelRef this) { return (int)(floor(this->mfY + 0.5)); } - -int xVoxl_GetZ(xVoxelRef this) { return (int)(floor(this->mfZ + 0.5)); } - -int xVoxl_GetRoundX(xVoxelRef this) { return rint(this->mfX); } - -int xVoxl_GetRoundY(xVoxelRef this) { return rint(this->mfY); } - -int xVoxl_GetRoundZ(xVoxelRef this) { return rint(this->mfZ); } - -void xVoxl_SetFloat(xVoxelRef this, float x, float y, float z) -{ - this->mfX = x; - this->mfY = y; - this->mfZ = z; -} - -void xVoxl_SetX(xVoxelRef this, int x) { this->mfX = (float)x; } - -void xVoxl_SetY(xVoxelRef this, int y) { this->mfY = (float)y; } - -void xVoxl_SetZ(xVoxelRef this, int z) { this->mfZ = (float)z; } - -void xVoxl_SetFloatX(xVoxelRef this, float x) { this->mfX = x; } - -void xVoxl_SetFloatY(xVoxelRef this, float y) { this->mfY = y; } - -void xVoxl_SetFloatZ(xVoxelRef this, float z) { this->mfZ = z; } - -float xVoxl_GetFloatX(xVoxelRef this) { return this->mfX; } - -float xVoxl_GetFloatY(xVoxelRef this) { return this->mfY; } - -float xVoxl_GetFloatZ(xVoxelRef this) { return this->mfZ; } - -#endif /* XVOXL_USE_MACROS */ - -tBoolean xVoxl_IncrementWithMinUntilLimit(xVoxelRef this, float inMin, float inLimit) -{ - if (this->mfX < inLimit) { - this->mfX += 1.0; - return TRUE; - } - else if (this->mfY < inLimit) { - this->mfX = inMin; - this->mfY += 1.0; - return TRUE; - } - else if (this->mfZ < inLimit) { - this->mfX = inMin; - this->mfY = inMin; - this->mfZ += 1.0; - return TRUE; - } - else { - return FALSE; - } -} - -tBoolean xVoxl_IncrementUntilLimit(xVoxelRef this, float inLimit) -{ - return xVoxl_IncrementWithMinUntilLimit(this, 0, inLimit); -} - -tBoolean xVoxl_IncrementUntilLimits(xVoxelRef this, float inXLimit, float inYLimit, float inZLimit) -{ - if (this->mfX < inXLimit) { - this->mfX += 1.0; - return TRUE; - } - else if (this->mfY < inYLimit) { - this->mfX = 0; - this->mfY += 1.0; - return TRUE; - } - else if (this->mfZ < inZLimit) { - this->mfX = 0; - this->mfY = 0; - this->mfZ += 1.0; - return TRUE; - } - else { - return FALSE; - } -} - -tBoolean xVoxl_IncrementWithMinsUntilLimits( - xVoxelRef this, float inXMin, float inYMin, float inXLimit, float inYLimit, float inZLimit) -{ - if (this->mfX < inXLimit) { - this->mfX += 1.0; - return TRUE; - } - else if (this->mfY < inYLimit) { - this->mfX = inXMin; - this->mfY += 1.0; - return TRUE; - } - else if (this->mfZ < inZLimit) { - this->mfX = inXMin; - this->mfY = inYMin; - this->mfZ += 1.0; - return TRUE; - } - else { - return FALSE; - } -} - -int xVoxl_ExpandToIndex(xVoxelRef this, int inDimensionX, int inDimensionY) -{ - return (this->mfZ * inDimensionX * inDimensionY) + (this->mfY * inDimensionX) + this->mfX; -} - -void xVoxl_PrintDebug(xVoxelRef this) -{ - DebugPrint(("Voxel: %d, %d, %d\n", xVoxl_GetX(this), xVoxl_GetY(this), xVoxl_GetZ(this))); -} diff --git a/utils/xVoxel.cpp b/utils/xVoxel.cpp new file mode 100644 index 00000000000..85e9e6dcc49 --- /dev/null +++ b/utils/xVoxel.cpp @@ -0,0 +1,206 @@ +/** + * @file xVoxel.c + * @brief general-purpose utils + */ +/* + * Original Author: Kevin Teich + * CVS Revision Info: + * $Author: nicks $ + * $Date: 2011/03/02 00:04:55 $ + * $Revision: 1.15 $ + * + * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" + * + * Terms and conditions for use, reproduction, distribution and contribution + * are found in the 'FreeSurfer Software License Agreement' contained + * in the file 'LICENSE' found in the FreeSurfer distribution, and here: + * + * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense + * + * Reporting: freesurfer@nmr.mgh.harvard.edu + * + */ + +#include "xVoxel.h" +#include +#include +#include "xDebug.h" + +void xVoxl_New(xVoxelRef *oppVoxel) +{ + xVoxelRef ref = (xVoxelRef)calloc(1, sizeof(xVoxel)); + *oppVoxel = ref; +} + +void xVoxl_Delete(xVoxelRef *ioppVoxel) +{ + xVoxelRef ref = NULL; + + if (NULL == ioppVoxel) { + return; + } + + ref = *ioppVoxel; + + free(ref); + *ioppVoxel = NULL; +} + +void xVoxl_Copy(xVoxelRef ipVoxDest, xVoxelRef ipVoxSrc) +{ + xVoxl_SetFloat(ipVoxDest, xVoxl_GetFloatX(ipVoxSrc), xVoxl_GetFloatY(ipVoxSrc), xVoxl_GetFloatZ(ipVoxSrc)); +} + +char xVoxl_IsEqualInt(xVoxelRef ipVox1, xVoxelRef ipVox2) +{ + if (xVoxl_GetX(ipVox1) == xVoxl_GetX(ipVox2) && xVoxl_GetY(ipVox1) == xVoxl_GetY(ipVox2) && + xVoxl_GetZ(ipVox1) == xVoxl_GetZ(ipVox2)) { + return TRUE; + } + else { + return FALSE; + } +} + +char xVoxl_IsEqualFloat(xVoxelRef ipVox1, xVoxelRef ipVox2) +{ + if (fabs(xVoxl_GetFloatX(ipVox1) - xVoxl_GetFloatX(ipVox2)) < 0.0001 && + fabs(xVoxl_GetFloatY(ipVox1) - xVoxl_GetFloatY(ipVox2)) < 0.0001 && + fabs(xVoxl_GetFloatZ(ipVox1) - xVoxl_GetFloatZ(ipVox2)) < 0.0001) { + return TRUE; + } + else { + return FALSE; + } +} + +/* declare non-macro versions of ref stuff. */ +#ifndef XVOXL_USE_MACROS + +void xVoxl_Set(xVoxelRef ref, int x, int y, int z) +{ + ref->mfX = x; + ref->mfY = y; + ref->mfZ = z; +} + +int xVoxl_GetX(xVoxelRef ref) { return (int)(floor(ref->mfX + 0.5)); } + +int xVoxl_GetY(xVoxelRef ref) { return (int)(floor(ref->mfY + 0.5)); } + +int xVoxl_GetZ(xVoxelRef ref) { return (int)(floor(ref->mfZ + 0.5)); } + +int xVoxl_GetRoundX(xVoxelRef ref) { return rint(ref->mfX); } + +int xVoxl_GetRoundY(xVoxelRef ref) { return rint(ref->mfY); } + +int xVoxl_GetRoundZ(xVoxelRef ref) { return rint(ref->mfZ); } + +void xVoxl_SetFloat(xVoxelRef ref, float x, float y, float z) +{ + ref->mfX = x; + ref->mfY = y; + ref->mfZ = z; +} + +void xVoxl_SetX(xVoxelRef ref, int x) { ref->mfX = (float)x; } + +void xVoxl_SetY(xVoxelRef ref, int y) { ref->mfY = (float)y; } + +void xVoxl_SetZ(xVoxelRef ref, int z) { ref->mfZ = (float)z; } + +void xVoxl_SetFloatX(xVoxelRef ref, float x) { ref->mfX = x; } + +void xVoxl_SetFloatY(xVoxelRef ref, float y) { ref->mfY = y; } + +void xVoxl_SetFloatZ(xVoxelRef ref, float z) { ref->mfZ = z; } + +float xVoxl_GetFloatX(xVoxelRef ref) { return ref->mfX; } + +float xVoxl_GetFloatY(xVoxelRef ref) { return ref->mfY; } + +float xVoxl_GetFloatZ(xVoxelRef ref) { return ref->mfZ; } + +#endif /* XVOXL_USE_MACROS */ + +tBoolean xVoxl_IncrementWithMinUntilLimit(xVoxelRef ref, float inMin, float inLimit) +{ + if (ref->mfX < inLimit) { + ref->mfX += 1.0; + return TRUE; + } + else if (ref->mfY < inLimit) { + ref->mfX = inMin; + ref->mfY += 1.0; + return TRUE; + } + else if (ref->mfZ < inLimit) { + ref->mfX = inMin; + ref->mfY = inMin; + ref->mfZ += 1.0; + return TRUE; + } + else { + return FALSE; + } +} + +tBoolean xVoxl_IncrementUntilLimit(xVoxelRef ref, float inLimit) +{ + return xVoxl_IncrementWithMinUntilLimit(ref, 0, inLimit); +} + +tBoolean xVoxl_IncrementUntilLimits(xVoxelRef ref, float inXLimit, float inYLimit, float inZLimit) +{ + if (ref->mfX < inXLimit) { + ref->mfX += 1.0; + return TRUE; + } + else if (ref->mfY < inYLimit) { + ref->mfX = 0; + ref->mfY += 1.0; + return TRUE; + } + else if (ref->mfZ < inZLimit) { + ref->mfX = 0; + ref->mfY = 0; + ref->mfZ += 1.0; + return TRUE; + } + else { + return FALSE; + } +} + +tBoolean xVoxl_IncrementWithMinsUntilLimits( + xVoxelRef ref, float inXMin, float inYMin, float inXLimit, float inYLimit, float inZLimit) +{ + if (ref->mfX < inXLimit) { + ref->mfX += 1.0; + return TRUE; + } + else if (ref->mfY < inYLimit) { + ref->mfX = inXMin; + ref->mfY += 1.0; + return TRUE; + } + else if (ref->mfZ < inZLimit) { + ref->mfX = inXMin; + ref->mfY = inYMin; + ref->mfZ += 1.0; + return TRUE; + } + else { + return FALSE; + } +} + +int xVoxl_ExpandToIndex(xVoxelRef ref, int inDimensionX, int inDimensionY) +{ + return (ref->mfZ * inDimensionX * inDimensionY) + (ref->mfY * inDimensionX) + ref->mfX; +} + +void xVoxl_PrintDebug(xVoxelRef ref) +{ + DebugPrint(("Voxel: %d, %d, %d\n", xVoxl_GetX(ref), xVoxl_GetY(ref), xVoxl_GetZ(ref))); +} diff --git a/utils/xmlToHtml.c b/utils/xmlToHtml.cpp similarity index 100% rename from utils/xmlToHtml.c rename to utils/xmlToHtml.cpp diff --git a/utilscpp/CMakeLists.txt b/utilscpp/CMakeLists.txt deleted file mode 100644 index 5b3b3eedc1e..00000000000 --- a/utilscpp/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -project(utilscpp) - -include_directories(${FS_INCLUDE_DIRS}) - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") - -set(SOURCES - argparse.cpp - log.cpp - lut.cpp - pointset.cpp - mris_fastmarching.cpp - globals.cpp - face.cpp - vertex.cpp - loop.cpp - fastloop.cpp - surface.cpp - patchdisk.cpp - mris_topology.cpp - segment.cpp - patchdisk.cpp -) - -add_library(utilscpp STATIC ${SOURCES}) -target_link_libraries(utilscpp utils) diff --git a/utilscpp/log.cpp b/utilscpp/log.cpp deleted file mode 100644 index 87089e060d3..00000000000 --- a/utilscpp/log.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include -#include -#include - -#include "log.hpp" - - -namespace fs -{ - Logger::Logger(MessageStatus status) : msg_status(status), exitout(false) {} - Logger::Logger(MessageStatus status, int exitcode) : msg_status(status), retcode(exitcode), exitout(true) {} - - // destructor calls the print routine - Logger::~Logger() - { - print(ss.str()); - if (exitout) exit(retcode); - } - - /// prints the actual prefaced message - void Logger::print(std::string content) - { - switch(msg_status) { - case Warning : fprintf(stderr, "%swarning:%s %s\n", term::yellow(), term::reset(), content.c_str()); break; - case Error : fprintf(stderr, "%serror:%s %s\n", term::red(), term::reset(), content.c_str()); break; - default : fprintf(stdout, "%s\n", content.c_str()); break; - } - } - - /// checks to make sure the output is a tty that accepts colors - static bool termAllowsColor() - { - if (!isatty(fileno(stderr))) return false; - if (const char* term = getenv("TERM")) { - return 0 == strcmp(term, "cygwin") - || 0 == strcmp(term, "linux") - || 0 == strcmp(term, "rxvt-unicode-256color") - || 0 == strcmp(term, "screen") - || 0 == strcmp(term, "screen-256color") - || 0 == strcmp(term, "tmux-256color") - || 0 == strcmp(term, "xterm") - || 0 == strcmp(term, "xterm-256color") - || 0 == strcmp(term, "xterm-termite") - || 0 == strcmp(term, "xterm-color"); - } - else return false; - } - - namespace term - { - // colors - const char* black() { return termAllowsColor() ? "\e[30m" : ""; } - const char* red() { return termAllowsColor() ? "\e[31m" : ""; } - const char* green() { return termAllowsColor() ? "\e[32m" : ""; } - const char* yellow() { return termAllowsColor() ? "\e[33m" : ""; } - const char* blue() { return termAllowsColor() ? "\e[34m" : ""; } - const char* purple() { return termAllowsColor() ? "\e[35m" : ""; } - const char* cyan() { return termAllowsColor() ? "\e[36m" : ""; } - const char* light_gray() { return termAllowsColor() ? "\e[37m" : ""; } - const char* white() { return termAllowsColor() ? "\e[37m" : ""; } - const char* light_red() { return termAllowsColor() ? "\e[91m" : ""; } - const char* dim() { return termAllowsColor() ? "\e[2m" : ""; } - - // formating - const char* bold() { return termAllowsColor() ? "\e[1m" : ""; } - const char* underline() { return termAllowsColor() ? "\e[4m" : ""; } - - // reset - const char* reset() { return termAllowsColor() ? "\e[0m" : ""; } - } -} \ No newline at end of file diff --git a/utilscpp/test/ctest.c b/utilscpp/test/ctest.c deleted file mode 100644 index b3f30555aea..00000000000 --- a/utilscpp/test/ctest.c +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @file ctest.c - * @brief REPLACE_WITH_ONE_LINE_SHORT_DESCRIPTION - * - * REPLACE_WITH_LONG_DESCRIPTION_OR_REFERENCE - */ -/* - * Original Author: REPLACE_WITH_FULL_NAME_OF_CREATING_AUTHOR - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -// -// ctest.c -// -// purpose: usability of cpp library exported C function -// -#include -#include -#include "mri.h" -#include "fastmarching.h" - -const char *Progname = "ctest"; - -int main(int argc, char *argv[]) { - MRI *src; - MRI *dst; - int label=2; - float max_distance=10.; - int mode=1; - - if (argc < 1) { - fprintf(stderr, "Usage: ctest \n"); - return -1; - } - src = MRIread(argv[1]); - dst = MRIextractDistanceMap(src, NULL, label, max_distance, mode,NULL); - return 0; -} - diff --git a/vtkfsio/CMakeLists.txt b/vtkfsio/CMakeLists.txt deleted file mode 100644 index 1df3442960d..00000000000 --- a/vtkfsio/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -project(vtkfsio) - -if(VTK_FOUND) - - include_directories(${FS_INCLUDE_DIRS} ${VTK_INCLUDE_DIRS}) - - set(SOURCES - vtkFSSurfaceLabelSource.cxx - vtkFSSurfaceWriter.cxx - vtkFSSurfaceScalarsReader.cxx - vtkFSSurfaceSource.cxx - vtkFSVolumeSource.cxx - ) - - if(SUPPRESS_WARNINGS) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated") - endif() - - add_library(vtkfsio STATIC ${SOURCES}) - -endif() diff --git a/vtkfsio/lh.vtkFSSurfaceWriterTestFile b/vtkfsio/lh.vtkFSSurfaceWriterTestFile deleted file mode 100644 index 0244c74d6e7087f77092a14a72a5baf60feb01d6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13626 zcmZvj2bf(|xrYCB=%M!x8$m%J$z%e=L@`@KZ_*W%G9(i+kV#@DV8FKRT~M&MqoSbF zdv#U-1pxs80jVQRK|w)5K_K`2zjM|)D?E2Sv-ke~_y4|iCbRy1F84mqUApu&YgN|T zVtQj1$IR+zT1k&KJ?^cf@(j$J+4;OXjU zJ)QmZe96=9?$6WDG+K{me*Czq~(5J$?rP))#k=Ze((Eo?mGGPEckSK?upL)YImNQ*Fctd-P-{19U)6=owdH)K?lD{ha=vZ+1n@%6Bzn|}|{nNAH$se6{xj!?n zDOfs(y0=e0$A%tU{%+q`&ipg|N;+CkC%;&iyUx6(VCi$}-ae`eE+e-FT2r~O^W?v=j>sPp$gS7(3vpO0Oh_pbn~$hD*@_D4tSargUPwL@0Y{!BU+ ze0t*T&K~lhGp8S|n?+|{7aW~A-pHkWcqZ=8#9b$jC3Dw_k2XE-I`N3duhh@HE;u^# zrr_wz+XY8w9t)1ne5~N;#MAkXHl1_NynBw~=*%nA5=Z+p=}0H(>2P0l)I&Gd-uLC2 zA1&9}-|jHKr|-9C{Qc%--DOGV z-yaaWy_#qG{nOK1u9M$&g!yvq*Z;SY-+QqzB!Ag=ooat3zw7B-zM}4(o9pCv?U%2} zmHjnEcct$=FVpv4(%IiQ>8$j<=auW|g5^5<+fF(weeZeYI=W!F&i?46vtlfMe>6W@ z&a;24!~CAU_mYk-Sk9B*=RYmiqfMtu?}b;cv!8b%t@PhNUb~LnhU@IFx{${bblx8w zt+SR?9lvMN_iEDaPdZvpI}@*ftfWVqo{k0geodYBPul%SN9*bAuYjzYYf07l{gaN? zR9mXZ-6ZMo9_NKH9A_4XFok(^4EnQ9SffPAT9U%O23cm$d!2V zd*7FH*U9hCXgxli+C9#EC7t{c=2zm`Ujtd3mjtzY@>; zSEeP7&VF>Hleqj1bsNa?`Eo6PS4Zpd?5CGGI`i7Jv=2J(gN}3(&wiLMah}*RMGt;fA~Pg+SQzw^kIc=CHcao34EOWdEC*9Avs-V_|2dAs1~%wxgPnU575 zow&~iHvRs2PMXg5SmxdDTmLsMsZ1;B(WaY)M>>gX|28$3FMsBF=;~PT>~DZ9`J3*! zw5ie2dOZ7UAWQzb@S|hFvmfS5ex9REPsf5MzdwDs-*xi4j@IK|yCId%2sT+&C4%6-DlrpW-E1|*x$mbqkl-3>AqcLi5x zZN^^(&HVtyfdto43qf#Ql?a0GQHh!0`ey4X$o)XYfdn^D3qf#0l?Z|dsl-fhW3!DE z=YFu_K!Tg7g&?@8N(8|}RAMH$x!Golb3asZAi*uvLJ-_iC4%5#Dlrq>%B)hH`{9ZM z3BE}!1i`IUA_%@$C1!$eHrqyV?(b6^NboIcAqZ}(5<&0?m6!>>)oeS(xgV)Gkl^-e zAqeiE5<&3&DlrorZ?>c2+&`c=kl+Nh5CkWxL=ZemC1!$?%=#4Pezf91g8gbC2u@as zAb5;Q%mjBf+evZm$0`maxQki{f>Tr?2o9*kOmM2%+Z5-1oZ>)&)6_x`e7i~n!I>&C z6WrD89g1_Gr8tn_JJmuEoURf*B znVqcGzJjOdEdw54cB)$Yn*l$nHweg!_A#}1p@5&z+W|b-?2~F8B={LkK9CpWvug1o z0KcHA1|DwqMYRqS{E{XX$Y6h2Ee05Pnx+wWq}l0e9U*vzCJo3yo~agt2mF?%2za#F zx79jI@OzpNAcORMwHO%Sk97LL4G8{JCktc%&Qfcp8SreK8j!<1N3B7@U+I{D z9O5t3LU3xoREgja@lc+iQ<$$)JJAfWK&QsRAvhY2kCWxFM%2ZCSfnln1ZRg00|)mZ zbul0otBV1_kzvEYA%0k042X}Yivhv$VZ*?Ieq3D)h(=uu2+kK91`hXA>S92AT3rkX zjujgQ4*GNIVnBReT?`1$9UF#o&CXL7%>Y~|f*E+eoR|?8C_)NxktP8%gK@DU3-H(Whx2T5NKr**BCTi1?0Q88!@Onf**%42Ykr zive-AY#7ebfYIfL!DGPa@`GUBu<-}K-0TYdh0*-MuNL7C4!lx-?eitB(qEfDIN}=p zg)#F7zg7|c;J{J+xq$qUuTu-bU+>o{5gZC0NKJ^;GfLySNwhpYkAxu!3Wer z5PVSOeI5*Jt0Y2@<7N`j4_R2p;|>XO^t2EJIeN+mJs8$iNo35zdLE$*4C`wWn4-rl zY~U>h0~j{c(K9U!#$U{y(s(>&VI#LWWGeou7UD^>r&T`b!LYGPA_V_t_Kf1sSlGnl z4hjBUEd;@5RX**(u&GKS1pi_7oZ`<}*v#V&3I0L8N+JaRWA>8bFIlKO?vUVr)j|+_S>=l!3|pxrLhyfPuPFYC zg*SQJA;DMGLJ)jS<;xxnTdO2OaH-kriob4Q8;?7D)q<(T4zF1VDiK>-*w#yrEVb}v zkGL=kZ&8WBjE9mJb~_7i)mw??h22qvmlU|Y-b!9f#148Zc`*?a^_F4gW$aUgmku~t zZxE0dZ6~#Op@38Lb^v*a-li5W3-Illd>}8#JJjMu08ZCb0~!8WEruL8LlX;Ruy<37 z0S4}=i3Kvid#S|$1NYU$0vX`_)M9{v@6j{@8QKHYVmN_^XwrZT&{5 zLmW~I!Ks~~60xlXJe1q%6vpe+I5@-vo!a&i9L)|ga9ESn#enEn7bk*a!iIr^+gV)< zh+WjhfZ)imVc-y_s*3?JO>0tpe_c)aq40~FgDmQ%(5`3E(XMGbul2AD{L6%S{POr&44Ws!3>-yCuYQaMMxn= zG+LO4EPPNA#0eG_szfk&cqrL?k%g1A8=B1*i?BKHWbMr6h!1IJHb;C|am;LfiXsSh zJ5?ou&GAsO`MDO(({5-szfgqDf#+*yHb-2bo!K05iQ<^q{31mV>~^tA1e@cb{D_5* zTKI&8M*30w+n?-q#&QOUU_ohL_$`$Pf_JFIOz=AvzO6X-I~4~K{H|IEg5Oh#AovHBmGQTy6pJxZa2>B>tia$9%PgzbbN-1>oN_(!gshj9U1$4BY=N8}M2SQ7y!E7M7?) z5d4Qq%mi<+aJ}N(|EV~T;Eie_2>wPTg5bYYVkUT#-WN1)&A$}~61-V01VLU6N(90G zsKk7Wh5sr-7x+KD1wdYwSJk>zaH%F7c)PVsEe3w6wU*QL@^;*5t>x9a!(nSBO(v6n zm$g>*7J~|Gt*WVGs_(JZYTjZ9fvq()QB3T;)>_M33>dJruBL@)yx&^ud5hrzwl>rx zFli51Ya?$l7{J!1ngpikA!}{sEd~SF+EPc)v^;FB&AsIl@`$yz@X{ybQTI^#U_4>r zNlgM1f_O@k@R$V0{kRMaz|-ntKs=)^P6Wq_4Fd!4thyKw+6!SP|kz(GH+E(XL4 z>S91}OxQ4Rpf9S60r8T$7!Vv8HVho%%j#l4yrM1!1ZRp30|)w=x)>0ztBV1_`C@z3 zPp}o#<^Q=OSgWP(>n{APIdKde^a|=?K&+@P1_VdU>0{u~S5X%OVw}1d5F9r)3=F{P z>S92wp)LjlM~@8y!?3ox7!d2IivhtHV8g&*tgkKx#0KhOKrj;6Ffb$=tBV1#iMkjN zj0ZLh3=FeDmmdVPL6;u{v%&u=XUlW>O3(F99+*2ctJ<}iR8?D7C(oaI((qt4G;j9& zN{w-|hvp8>8-VRvO`J1-cyQv0iw1{g&Y8GqaAeUjvj!FoOdOauuxS49(9D6k6Xy&a z)4%h~la3plHDUPpQ^$38+qLT7x$^^AJUDk`=v3cs(u6+NvX60#7Y>Y672WaOc3;QU zd5k+HwU@!kJnqytw3pdq+{`z0m)V2=8-p#Uzl?>gh8GSU!#{9jaPHiJMT6C{|Ey|K z|CDO(oC$M=ssk6!KYroB@Zp0CM~3Fln^tXe0Dq}zRkclZ=+N-sA&Ulv7fh@A`}(F# z?AvMLq$%SkO`SG*%C!C|g%7@H|wg14(IYaaK^w~orbA|@11Nqfw&tEt^ zt=eyB-bssdoqyT>3A;>~I)11A34IeLPuP9Gk>Lf^jQPV0IPZm>f5x6OW@M66llyk+ H>$Cp@wP^?x diff --git a/vtkfsio/vtkFSSurfaceLabelSource.cxx b/vtkfsio/vtkFSSurfaceLabelSource.cxx deleted file mode 100644 index 5899cf44af2..00000000000 --- a/vtkfsio/vtkFSSurfaceLabelSource.cxx +++ /dev/null @@ -1,370 +0,0 @@ -/** - * @file vtkFSSurfaceLabelSource.h - * @brief Reads a label, maps it to a surface, and outputs PolyData - * - * A FreeSurfer label file consists of a list of vertices that may - * also have associated vertex indices. This will read in a label, map - * it to a surface, fill in any holes, and output PolyData, which will - * appear to be a subset of the surface PolyData. - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.14 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include -#include -#include "vtkFSSurfaceLabelSource.h" -#include "vtkFSSurfaceSource.h" -#include "vtkObjectFactory.h" -#include "vtkCellArray.h" -#include "vtkPointData.h" -#include "vtkPoints.h" -#include "vtkPolyData.h" - -using namespace std; - -vtkStandardNewMacro( vtkFSSurfaceLabelSource ); -//vtkCxxRevisionMacro( vtkFSSurfaceLabelSource, "$Revision: 1.14 $" ); - -vtkFSSurfaceLabelSource::vtkFSSurfaceLabelSource() : - LabelFileName( NULL ), Mris( NULL ), Label( NULL ) { - - this->vtkPolyDataAlgorithm::SetNthOutput(0, vtkPolyData::New()); - - // Releasing data for pipeline parallism. Filters will know it is - // empty. - this->Outputs[0]->ReleaseData(); - this->Outputs[0]->Delete(); -} - -vtkFSSurfaceLabelSource::~vtkFSSurfaceLabelSource () { - -} - -vtkPolyData* -vtkFSSurfaceLabelSource::GetOutput () { - - if ( this->NumberOfOutputs < 1 ) { - return NULL; - } - - return (vtkPolyData *)(this->Outputs[0]); -} - -vtkPolyData* -vtkFSSurfaceLabelSource::GetOutput ( int inOutput ) { - - return (vtkPolyData *)this->vtkPolyDataAlgorithm::GetOutput( inOutput ); -} - -void -vtkFSSurfaceLabelSource::SetOutput ( vtkPolyData* iOutput ) { - - this->vtkPolyDataAlgorithm::SetNthOutput( 0, iOutput ); -} - -void -vtkFSSurfaceLabelSource::InitializeEmptyLabel () { - - // Delete existing label if present, and create a new one with 0 - // vertices. - if( NULL != Label ) { - LabelFree( &Label ); - } - - Label = LabelAlloc( 0, (char*)"", (char*)"" ); - - this->Modified(); -} - -void -vtkFSSurfaceLabelSource::AddVerticesToLabel ( int icVertices, - int* iaVertices ) { - assert( icVertices > 0 ); - assert( iaVertices ); - assert( Mris ); - assert( Label ); - - // Reallocate the label with enough points. - LabelRealloc( Label, Label->n_points + icVertices ); - - // For each vertex to add... - int nPoint = Label->n_points; - for( int nVertex = 0; nVertex < icVertices; nVertex++ ) { - - // Check the vertex number. - if( iaVertices[nVertex] < 0 || - iaVertices[nVertex] >= Mris->nvertices ) - throw runtime_error( "Invalid vertex number" ); - - // Make a new point. - Label->lv[nPoint].vno = iaVertices[nVertex]; - Label->lv[nPoint].x = Mris->vertices[iaVertices[nVertex]].x; - Label->lv[nPoint].y = Mris->vertices[iaVertices[nVertex]].y; - Label->lv[nPoint].z = Mris->vertices[iaVertices[nVertex]].z; - Label->lv[nPoint].deleted = 0; - - Label->n_points++; - nPoint++; - } - - this->Modified(); -} - -void -vtkFSSurfaceLabelSource::RemoveVerticesFromLabel ( int icVertices, - int* iaVertices ) { - - assert( Label ); - assert( iaVertices ); - - // For each vertex to remove... - for( int nVertex = 0; nVertex < icVertices; nVertex++ ) { - - // Check the vertex. - if( iaVertices[nVertex] < 0 || - iaVertices[nVertex] >= Mris->nvertices ) - throw runtime_error( "Invalid vertex number" ); - - // Search for this vertex in the label and if found, set its - // deleted flag to true. - for( int nPoint = 0; nPoint < Label->n_points; nPoint++ ) { - - if( Label->lv[nPoint].vno == iaVertices[nVertex] ) - Label->lv[nPoint].deleted = 1; - - } - } - - this->Modified(); -} - -void -vtkFSSurfaceLabelSource::Execute () { - - if( NULL == Mris ) - vtkErrorMacro( << "vtkFSSurfaceLabelSource cannot exectue without a surface" ); - - if( NULL == Label ) { - this->ReadLabelFile(); - if( NULL == Label ) - vtkErrorMacro( << "vtkFSSurfaceLabelSource cannot exectue without a label" ); - } - - // We use marks to figure out where the label is on the surface. - MRISclearMarks( Mris ); - - LabelMarkUndeleted( Label, Mris ); - - // Now we have a marked surface. What we want to do is create a - // new poly data object without only marked faces in it. To do - // that, we need a list of points in the faces, and make faces - // that index those points. However we need to map the surface - // based indices to a new range of indices that only have the - // selected points. So we'll save a list of points and faces that - // are selected using the old indices, and then create a mapping. - - // For each face in the surface, if all its vertices are marked, - // put those points and the face in our list of ones that will go - // into the new poly data. - map > aPoints; - map > aPolys; - int nPoly = 0; - for( int nFace = 0; nFace < Mris->nfaces; nFace++ ) { - if( Mris->vertices[Mris->faces[nFace].v[0]].marked && - Mris->vertices[Mris->faces[nFace].v[1]].marked && - Mris->vertices[Mris->faces[nFace].v[2]].marked ) { - - // We're going to make an entry for a poly with a 0-based face - // index, but using the same vertex index as the original - // surface. - for( int nFaceVertex = 0; - nFaceVertex < VERTICES_PER_FACE; nFaceVertex++ ) { - - int nVertex = Mris->faces[nFace].v[nFaceVertex]; - - // Save the poly using the 0 based index. - aPolys[nPoly][nFaceVertex] = nVertex; - - // Save the point with the original index. This can be - // redundant, we don't care. - aPoints[nVertex][0] = Mris->vertices[nVertex].x; - aPoints[nVertex][1] = Mris->vertices[nVertex].y; - aPoints[nVertex][2] = Mris->vertices[nVertex].z; - } - - nPoly++; - } - } - - // Now lets make point and poly lists out of the maps we just - // made. - vtkPoints* labelPoints = vtkPoints::New(); - labelPoints->SetNumberOfPoints( aPoints.size() ); - - vtkCellArray* labelPolys = vtkCellArray::New(); - labelPolys->Allocate( aPolys.size() ); - - vtkIdType nNextNewID = 0; - map aOldIDToNewID; - - // For each point we saved, we need to map its surface based index - // to a new 0 based index. - map >::iterator tPoint; - for( tPoint = aPoints.begin(); tPoint != aPoints.end(); ++tPoint ) { - - // Get the old ID. - vtkIdType oldID = tPoint->first; - - // Build a point. - double point[3]; - for( int n = 0; n < 3; n++ ) - point[n] = tPoint->second[n]; - - // Map the old ID to a new ID and save it. - aOldIDToNewID[oldID] = nNextNewID++; - - // Insert the point with the new ID. - labelPoints->SetPoint( aOldIDToNewID[oldID], point ); - } - - // Now for each poly, add it to the polys array using the new 0 - // based point indices. - map >::iterator tPoly; - for( tPoly = aPolys.begin(); tPoly != aPolys.end(); ++tPoly ) { - - // Make a poly using the new IDs. - vtkIdType poly[3]; - for( int n = 0; n < 3; n++ ) - poly[n] = aOldIDToNewID[tPoly->second[n]]; - - // Insert the poly. - labelPolys->InsertNextCell( 3, poly ); - } - - // Set the points and polys in our output - this->GetOutput()->SetPoints( labelPoints ); - labelPoints->Delete(); - - this->GetOutput()->SetPolys( labelPolys ); - labelPolys->Delete(); - -} - -void -vtkFSSurfaceLabelSource::ReadLabelFile () { - - if( NULL == LabelFileName ) - vtkErrorMacro( << "vtkFSSurfaceLabelSource cannot exectue without a label file name" ); - - - // Load the white vertex positions in the surface. - int eMRIS = MRISreadWhiteCoordinates( Mris, (char*)"white" ); - if( eMRIS != 0 ) - throw runtime_error( "Couldn't read the white surface file, so unable to load a label." ); - - // Load the label file. - char* fnLabel = strdup( LabelFileName ); - Label = LabelRead( NULL, fnLabel ); - free( fnLabel ); - if( NULL == Label ) - throw runtime_error( "Couldn't read label" ); - - // Map it to the surface using the white coordinates. - LabelToWhite( Label, Mris ); - - // See if it's completely unassigned. If so, there are likely to - // be lots of holes in the label after we sample it to the - // vertices, so we'll fill it in afterwards. - int unassigned; - LabelIsCompletelyUnassigned( Label, &unassigned ); - - // Assign the mris vertex numbers to unnumbered vertices in the - // label. - LabelFillUnassignedVertices( Mris, Label, WHITE_VERTICES ); - - // If we were unassigned before, fill the holes now. - if( unassigned ) { - LABEL* filledLabel = LabelFillHoles( Label, Mris, WHITE_VERTICES ); - LabelFree( &Label ); - Label = filledLabel; - } - -} - -void -vtkFSSurfaceLabelSource::WriteLabelFile () { - - assert( Label ); - if( NULL == LabelFileName ) - vtkErrorMacro( << "vtkFSSurfaceLabelSource cannot write without a label file name" ); - - // Write the file. - char* fn = strdup( LabelFileName ); - int rLabel = LabelWrite( Label, fn ); - free( fn ); - - if( rLabel != 0 ) { - stringstream ssError; - ssError << "Couldn't write the label to " << LabelFileName; - throw runtime_error( ssError.str().c_str() ); - } -} - -void -vtkFSSurfaceLabelSource::GetLabeledPoints ( vtkPoints& ioPoints ) { - - assert( Label ); - - // Reset the point list and set the type to point. - ioPoints.Reset(); - ioPoints.SetDataTypeToFloat(); - - // Go through our Label, and for each not-deleted point, add it to - // our points. - for( int nPoint = 0; nPoint < Label->n_points; nPoint++ ) { - - if( !Label->lv[nPoint].deleted ) { - - float x = Label->lv[nPoint].x; - float y = Label->lv[nPoint].y; - float z = Label->lv[nPoint].z; - - ioPoints.InsertNextPoint( x, y, z ); - } - } -} - -void -vtkFSSurfaceLabelSource::GetLabeledVertices ( vector& iolVertices ) { - - assert( Label ); - - // Reset the list. - iolVertices.clear(); - - // Go through our Label, and for each not-deleted point, add the - // vertex number to the list. - for( int nPoint = 0; nPoint < Label->n_points; nPoint++ ) - if( !Label->lv[nPoint].deleted ) - iolVertices.push_back( Label->lv[nPoint].vno ); - -} diff --git a/vtkfsio/vtkFSSurfaceLabelSource.h b/vtkfsio/vtkFSSurfaceLabelSource.h deleted file mode 100644 index a46a31ee037..00000000000 --- a/vtkfsio/vtkFSSurfaceLabelSource.h +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file vtkFSSurfaceLabelSource.h - * @brief Reads a label, maps it to a surface, and outputs PolyData - * - * A FreeSurfer label file consists of a list of vertices that may - * also have associated vertex indices. This will read in a label, map - * it to a surface, fill in any holes, and output PolyData, which will - * appear to be a subset of the surface PolyData. - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.6 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef __vtkFSSurfaceLabelSource_h -#define __vtkFSSurfaceLabelSource_h - -#include - -class vtkPoints; -class vtkPolyData; -class vtkFSSurfaceSource; - -#include "vtkPolyDataAlgorithm.h" -extern "C" { -#include "mrisurf.h" -} - -class vtkFSSurfaceLabelSource : public vtkPolyDataAlgorithm { -public: - - static vtkFSSurfaceLabelSource *New(); - vtkTypeMacro(vtkFSSurfaceLabelSource,vtkPolyDataAlgorithm); - - // Description: - // vtkFSSurfaceLabelSource needs an MRIS object on which to map the - // label. The white coordinates should also be available for this - // surface. - vtkSetMacro(Mris,MRIS*); - vtkGetMacro(Mris,MRIS*); - - // Description: - // Initialize the label to be empty. - void InitializeEmptyLabel (); - - // Description: - // The file name of the label to read. - vtkSetStringMacro(LabelFileName); - vtkGetStringMacro(LabelFileName); - - // Description: - // Get the output of this source. - vtkPolyData* GetOutput (); - vtkPolyData* GetOutput ( int inOutput ); - void SetOutput ( vtkPolyData* iOutput ); - - // Description: - // Modify the label in memory. - void AddVerticesToLabel ( int icVertices, int* iaVertices ); - void RemoveVerticesFromLabel ( int icVertices, int* iaVertices ); - - // Description: - // Use LabelWrite to write the label with the current LabelFileName. - void WriteLabelFile (); - - // Description: - // Fill out the input vtkPoints with the labeled points, using the - // surface coordinates. GetLabeledVertices does the same thing but - // with vertex numbers. - void GetLabeledPoints ( vtkPoints& ioPoints ); - void GetLabeledVertices ( std::vector& iolVertices ); - -protected: - - vtkFSSurfaceLabelSource(); - ~vtkFSSurfaceLabelSource(); - - void Execute(); - - void ReadLabelFile (); - - char* LabelFileName; - MRIS* Mris; - LABEL* Label; - -private: - vtkFSSurfaceLabelSource(const vtkFSSurfaceLabelSource&); // Not implemented. - void operator=(const vtkFSSurfaceLabelSource&); // Not implemented. -}; - -#endif diff --git a/vtkfsio/vtkFSSurfaceScalarsReader.cxx b/vtkfsio/vtkFSSurfaceScalarsReader.cxx deleted file mode 100644 index 7a1b0345d1e..00000000000 --- a/vtkfsio/vtkFSSurfaceScalarsReader.cxx +++ /dev/null @@ -1,98 +0,0 @@ -#include -#include - -extern "C" { -#include "error.h" -#include "mrisurf.h" -} - -#include "vtkFSSurfaceScalarsReader.h" -#include "vtkDataObject.h" -#include "vtkFloatArray.h" -#include "vtkInformationVector.h" -#include "vtkObjectFactory.h" -#include "vtkPointData.h" -#include "vtkPolyData.h" -#include "vtkSmartPointer.h" -#include "vtkStreamingDemandDrivenPipeline.h" - -using namespace std; - -vtkCxxRevisionMacro(vtkFSSurfaceScalarsReader, "$Revision: 1.3 $"); -vtkStandardNewMacro(vtkFSSurfaceScalarsReader); - -vtkFSSurfaceScalarsReader::vtkFSSurfaceScalarsReader () : - FileName( "" ), - NumberOfValues( 0 ) { - - this->SetNumberOfInputPorts( 0 ); -} - -vtkFSSurfaceScalarsReader::~vtkFSSurfaceScalarsReader () { - -} - -void -vtkFSSurfaceScalarsReader::SetFileName ( const char* ifn ) { - - FileName = ifn; -} - -const char* -vtkFSSurfaceScalarsReader::GetFileName () const { - - return FileName.c_str(); -} - -int -vtkFSSurfaceScalarsReader::RequestData ( vtkInformation*, - vtkInformationVector**, - vtkInformationVector* iOutputVector ){ - - - // Init a float array. - vtkSmartPointer scalars = vtkFloatArray::New(); - - // Try to read the scalars. - float* values = NULL; - int eRead = MRISreadValuesIntoArray( this->FileName.c_str(), - this->NumberOfValues, - &values ); - if( ERROR_NONE != eRead ) { - if( values ) free( values ); - vtkErrorMacro(<< "Could not read scalar file " << this->FileName.c_str() ); - return 0; // 0 is failure - } - - // Allocate our scalars. - scalars->Allocate( this->NumberOfValues ); - scalars->SetNumberOfComponents( 1 ); - - // Copy our array into the scalars. - for( int nValue = 0; nValue < this->NumberOfValues; nValue ++ ) - scalars->InsertNextValue( values[nValue] ); - - // MRISreadValuesIntoArray allocated the array, so we free it. - free( values ); - -#if 0 - // Set the scalars in the output. - vtkPolyData* output = vtkPolyData::GetData( iOutputVector ); - if( !output ) { - vtkErrorMacro(<< "No output for vtkFSSurfaceScalarsReader" ); - return 0; // 0 is failure - } - output->GetPointData()->SetScalars( scalars ); -#endif - - return 1; // 1 is success -} - - -void -vtkFSSurfaceScalarsReader::PrintSelf ( ostream& iStream, vtkIndent iIndent ) { - - vtkPolyDataAlgorithm::PrintSelf( iStream, iIndent ); -} - - diff --git a/vtkfsio/vtkFSSurfaceScalarsReader.h b/vtkfsio/vtkFSSurfaceScalarsReader.h deleted file mode 100644 index d95bbe8850b..00000000000 --- a/vtkfsio/vtkFSSurfaceScalarsReader.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file vtkFSSurfaceScalarsReader.h - * @brief Reads a scalar file and outputs a float array - * - * This is the equivalent of calling MRISreadValues() except that it - * doesn't actually require an MRIS. It attemps to read a few - * different scalar file types, and outputs a vtkFloatArray if - * successful. - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.3 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#ifndef vtkFSSurfaceScalarsReader_h -#define vtkFSSurfaceScalarsReader_h - -#include -#include "vtkPolyDataAlgorithm.h" - -class vtkFloatArray; - -class vtkFSSurfaceScalarsReader : public vtkPolyDataAlgorithm { - - public: - - static vtkFSSurfaceScalarsReader* New (); - vtkTypeRevisionMacro( vtkFSSurfaceScalarsReader, vtkPolyDataAlgorithm ); - void PrintSelf ( ostream& os, vtkIndent indent ); - - void SetFileName ( const char* ifn ); - const char* GetFileName () const; - - vtkSetMacro(NumberOfValues,int); - vtkGetMacro(NumberOfValues,int); - - protected: - - vtkFSSurfaceScalarsReader (); - virtual ~vtkFSSurfaceScalarsReader (); - - // Description: - // Read the file, create the array of floats, and set our output. - virtual int RequestData ( vtkInformation*, - vtkInformationVector**, - vtkInformationVector* iOutputVector ); - - - static const int NEW_SCALAR_MAGIC_NUMBER = 16777215; - - std::string FileName; - int NumberOfValues; - - private: - vtkFSSurfaceScalarsReader ( const vtkFSSurfaceScalarsReader& ); - void operator= ( const vtkFSSurfaceScalarsReader& ); -}; - -#endif diff --git a/vtkfsio/vtkFSSurfaceSource.cxx b/vtkfsio/vtkFSSurfaceSource.cxx deleted file mode 100644 index 3550e73a9e0..00000000000 --- a/vtkfsio/vtkFSSurfaceSource.cxx +++ /dev/null @@ -1,622 +0,0 @@ -/** - * @file vtkFSSurfaceSource.cxx - * @brief import a freesurfer surface file into vtk - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.14 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include -#include -#include -#include -#include "vtkFSSurfaceSource.h" -#include "vtkObjectFactory.h" -#include "vtkFloatArray.h" -#include "vtkCellArray.h" -#include "vtkPointData.h" -#include "vtkPolyData.h" -#include "vtkTransform.h" - -using namespace std; - -vtkStandardNewMacro( vtkFSSurfaceSource ); -vtkCxxRevisionMacro( vtkFSSurfaceSource, "$Revision: 1.14 $" ); - -vtkFSSurfaceSource::vtkFSSurfaceSource() : - mMRIS( NULL ), - mbBoundsCacheDirty( true ), - mHashTable( NULL ) { - - this->vtkSource::SetNthOutput(0, vtkPolyData::New()); - - // Releasing data for pipeline parallism. - // Filters will know it is empty. - this->Outputs[0]->ReleaseData(); - this->Outputs[0]->Delete(); -} - -vtkFSSurfaceSource::~vtkFSSurfaceSource () { - - if( NULL != mHashTable ) MHTfree( &mHashTable ); - if( NULL != mMRIS ) MRISfree( &mMRIS ); -} - -void -vtkFSSurfaceSource::MRISRead( char const* ifn ) { - - char* fn = strdup( ifn ); - MRIS* mris = ::MRISread( fn ); - free( fn ); - if ( mris == NULL ) { - throw runtime_error( "MRISread failed" ); - } - - // Out with the old and in with the new. - if( NULL != mMRIS ) { - MRISfree( &mMRIS ); - } - mMRIS = mris; - - // Get some info from the MRIS. This can either come from the volume - // geometry data embedded in the surface; this is done for newer - // surfaces. Or it can come from the source information in the - // transform. We use it to get the RAS center offset for the - // surface->RAS transform. - if ( mMRIS->vg.valid ) { - - mSurfaceToRASMatrix[0] = 1; - mSurfaceToRASMatrix[1] = 0; - mSurfaceToRASMatrix[2] = 0; - mSurfaceToRASMatrix[3] = mMRIS->vg.c_r; - mSurfaceToRASMatrix[4] = 0; - mSurfaceToRASMatrix[5] = 1; - mSurfaceToRASMatrix[6] = 0; - mSurfaceToRASMatrix[7] = mMRIS->vg.c_a; - mSurfaceToRASMatrix[8] = 0; - mSurfaceToRASMatrix[9] = 0; - mSurfaceToRASMatrix[10] = 1; - mSurfaceToRASMatrix[11] = mMRIS->vg.c_s; - mSurfaceToRASMatrix[12] = 0; - mSurfaceToRASMatrix[13] = 0; - mSurfaceToRASMatrix[14] = 0; - mSurfaceToRASMatrix[15] = 1; - - } else if ( mMRIS->lta ) { - - mSurfaceToRASMatrix[0] = 1; - mSurfaceToRASMatrix[1] = 0; - mSurfaceToRASMatrix[2] = 0; - mSurfaceToRASMatrix[3] = -mMRIS->lta->xforms[0].src.c_r; - mSurfaceToRASMatrix[4] = 0; - mSurfaceToRASMatrix[5] = 1; - mSurfaceToRASMatrix[6] = 0; - mSurfaceToRASMatrix[7] = -mMRIS->lta->xforms[0].src.c_a; - mSurfaceToRASMatrix[8] = 0; - mSurfaceToRASMatrix[9] = 0; - mSurfaceToRASMatrix[10] = 1; - mSurfaceToRASMatrix[11] = -mMRIS->lta->xforms[0].src.c_s; - mSurfaceToRASMatrix[12] = 0; - mSurfaceToRASMatrix[13] = 0; - mSurfaceToRASMatrix[14] = 0; - mSurfaceToRASMatrix[15] = 1; - - } - - // Make our transform object and set the matrix. - mSurfaceToRASTransform = vtkSmartPointer::New(); - mSurfaceToRASTransform->SetMatrix( mSurfaceToRASMatrix ); - - // Make the hash table. This makes it with v->x,y,z. - if ( NULL != mHashTable ) - MHTfree( &mHashTable ); - mHashTable = MHTcreateVertexTable_Resolution( mMRIS, CURRENT_VERTICES, 2.0 ); -} - -vtkPolyData* -vtkFSSurfaceSource::GetOutput () { - - if ( this->NumberOfOutputs < 1 ) { - return NULL; - } - - return (vtkPolyData *)(this->Outputs[0]); -} - -vtkPolyData* -vtkFSSurfaceSource::GetOutput ( int inOutput ) { - - return (vtkPolyData *)this->vtkSource::GetOutput( inOutput ); -} - -void -vtkFSSurfaceSource::SetOutput ( vtkPolyData* iOutput ) { - - this->vtkSource::SetNthOutput( 0, iOutput ); -} - -void -vtkFSSurfaceSource::ConvertSurfaceToRAS ( float iX, float iY, float iZ, - float& oX, float& oY, float& oZ ) const { - - float surface[3]; - float ras[3]; - - surface[0] = iX; - surface[1] = iY; - surface[2] = iZ; - - this->ConvertSurfaceToRAS( surface, ras ); - - oX = ras[0]; - oY = ras[1]; - oZ = ras[2]; -} - -void -vtkFSSurfaceSource::ConvertSurfaceToRAS ( double iX, double iY, double iZ, - double& oX, double& oY, double& oZ ) const { - - double surface[3]; - double ras[3]; - - surface[0] = iX; - surface[1] = iY; - surface[2] = iZ; - - this->ConvertSurfaceToRAS( surface, ras ); - - oX = ras[0]; - oY = ras[1]; - oZ = ras[2]; -} - -void -vtkFSSurfaceSource::ConvertRASToSurface ( float iX, float iY, float iZ, - float& oX, float& oY, float& oZ ) const { - - float ras[3]; - float surface[3]; - - ras[0] = iX; - ras[1] = iY; - ras[2] = iZ; - - this->ConvertRASToSurface( ras, surface ); - - oX = surface[0]; - oY = surface[1]; - oZ = surface[2]; -} - -void -vtkFSSurfaceSource::ConvertRASToSurface ( double iX, double iY, double iZ, - double& oX, double& oY, double& oZ ) const { - - double ras[3]; - double surface[3]; - - ras[0] = iX; - ras[1] = iY; - ras[2] = iZ; - - this->ConvertRASToSurface( ras, surface ); - - oX = surface[0]; - oY = surface[1]; - oZ = surface[2]; -} - -void -vtkFSSurfaceSource::ConvertSurfaceToRAS ( float const iSurf[3], float oRAS[3] ) const { - - mSurfaceToRASTransform->TransformPoint( iSurf, oRAS ); -} - -void -vtkFSSurfaceSource::ConvertSurfaceToRAS ( double const iSurf[3], double oRAS[3] ) const { - - mSurfaceToRASTransform->TransformPoint( iSurf, oRAS ); -} - -void -vtkFSSurfaceSource::ConvertRASToSurface ( float const iRAS[3], float oSurf[3] ) const { - - mSurfaceToRASTransform->GetInverse()->TransformPoint( iRAS, oSurf ); -} - -void -vtkFSSurfaceSource::ConvertRASToSurface ( double const iRAS[3], double oSurf[3] ) const { - - mSurfaceToRASTransform->GetInverse()->TransformPoint( iRAS, oSurf ); -} - -void -vtkFSSurfaceSource::GetRASBounds ( float oRASBounds[6] ) { - - if ( NULL == mMRIS ) { - - oRASBounds[0] = oRASBounds[1] = oRASBounds[2] = - oRASBounds[3] = oRASBounds[4] = oRASBounds[5] = 0; - - return; - } - - if ( mbBoundsCacheDirty ) { - - mRASBounds[0] = mRASBounds[2] = mRASBounds[4] = 999999; - mRASBounds[1] = mRASBounds[3] = mRASBounds[5] = -999999; - - // Find the bounds. - for ( int vno = 0; vno < mMRIS->nvertices; vno++ ) { - - // Translate to actual RAS coords. - float rasX, rasY, rasZ; - this->ConvertSurfaceToRAS( mMRIS->vertices[vno].x, - mMRIS->vertices[vno].y, - mMRIS->vertices[vno].z, - rasX, rasY, rasZ ); - - if ( rasX < mRASBounds[0] ) mRASBounds[0] = rasX; - if ( rasX > mRASBounds[1] ) mRASBounds[1] = rasX; - if ( rasY < mRASBounds[2] ) mRASBounds[2] = rasY; - if ( rasY > mRASBounds[3] ) mRASBounds[3] = rasY; - if ( rasZ < mRASBounds[4] ) mRASBounds[4] = rasZ; - if ( rasZ > mRASBounds[5] ) mRASBounds[5] = rasZ; - - } - - mbBoundsCacheDirty = false; - } - - oRASBounds[0] = mRASBounds[0]; - oRASBounds[1] = mRASBounds[1]; - oRASBounds[2] = mRASBounds[2]; - oRASBounds[3] = mRASBounds[3]; - oRASBounds[4] = mRASBounds[4]; - oRASBounds[5] = mRASBounds[5]; -} - -vtkTransform const* -vtkFSSurfaceSource::GetSurfaceToRASTransform () const { - - return mSurfaceToRASTransform; -} - -int -vtkFSSurfaceSource::GetNumberOfVertices () const { - - if( mMRIS ) - return mMRIS->nvertices; - else - return 0; -} - -int -vtkFSSurfaceSource::FindVertexAtRAS ( float const iRAS[3], float* oDistance ) { - - float surf[3]; - this->ConvertRASToSurface( iRAS, surf ); - - return this->FindVertexAtSurfaceRAS( surf, oDistance ); -} - -int -vtkFSSurfaceSource::FindVertexAtRAS ( double const iRAS[3], double* oDistance ) { - - double surf[3]; - this->ConvertRASToSurface( iRAS, surf ); - - return this->FindVertexAtSurfaceRAS( surf, oDistance ); -} - -int -vtkFSSurfaceSource::FindVertexAtSurfaceRAS ( float const iSurfaceRAS[3], - float* oDistance ) { - - VERTEX v; - v.x = iSurfaceRAS[0]; - v.y = iSurfaceRAS[1]; - v.z = iSurfaceRAS[2]; - float distance; - int nClosestVertex = - MHTfindClosestVertexNo( mHashTable, mMRIS, &v, &distance ); - - if ( -1 == nClosestVertex ) { - throw runtime_error( "No vertices found."); - } - - if ( NULL != oDistance ) { - *oDistance = distance; - } - - return nClosestVertex; -} - -int -vtkFSSurfaceSource::FindVertexAtSurfaceRAS ( double const iSurfaceRAS[3], - double* oDistance ) { - - VERTEX v; - v.x = static_cast(iSurfaceRAS[0]); - v.y = static_cast(iSurfaceRAS[1]); - v.z = static_cast(iSurfaceRAS[2]); - float distance; - int nClosestVertex = - MHTfindClosestVertexNo( mHashTable, mMRIS, &v, &distance ); - - if ( -1 == nClosestVertex ) { - throw runtime_error( "No vertices found."); - } - - if ( NULL != oDistance ) { - *oDistance = static_cast(distance); - } - - return nClosestVertex; -} - -void -vtkFSSurfaceSource::GetRASAtVertex ( int inVertex, float ioRAS[3] ) { - - float surfaceRAS[3]; - this->GetSurfaceRASAtVertex( inVertex, surfaceRAS ); - - this->ConvertSurfaceToRAS( surfaceRAS, ioRAS ); -} - -void -vtkFSSurfaceSource::GetRASAtVertex ( int inVertex, double ioRAS[3] ) { - - double surfaceRAS[3]; - this->GetSurfaceRASAtVertex( inVertex, surfaceRAS ); - - this->ConvertSurfaceToRAS( surfaceRAS, ioRAS ); -} - -void -vtkFSSurfaceSource::GetSurfaceRASAtVertex ( int inVertex, float ioRAS[3] ) { - - if( mMRIS == NULL ) - throw runtime_error( "GetRASAtVertex: mMRIS was NULL" ); - - if( inVertex < 0 || inVertex >= mMRIS->nvertices ) - throw runtime_error( "GetRASAtVertex: inVertex was invalid" ); - - ioRAS[0] = mMRIS->vertices[inVertex].x; - ioRAS[1] = mMRIS->vertices[inVertex].y; - ioRAS[2] = mMRIS->vertices[inVertex].z; -} - -void -vtkFSSurfaceSource::GetSurfaceRASAtVertex ( int inVertex, double ioRAS[3] ) { - - if( mMRIS == NULL ) - throw runtime_error( "GetRASAtVertex: mMRIS was NULL" ); - - if( inVertex < 0 || inVertex >= mMRIS->nvertices ) - throw runtime_error( "GetRASAtVertex: inVertex was invalid" ); - - ioRAS[0] = static_cast(mMRIS->vertices[inVertex].x); - ioRAS[1] = static_cast(mMRIS->vertices[inVertex].y); - ioRAS[2] = static_cast(mMRIS->vertices[inVertex].z); -} - -void -vtkFSSurfaceSource::Execute () { - - if ( mMRIS == NULL) { - return; - } - - vtkPolyData *output = this->GetOutput(); - - // Allocate all our arrays. - int cVertices = mMRIS->nvertices; - int cFaces = mMRIS->nfaces; - - vtkSmartPointer newPoints = - vtkSmartPointer::New(); - newPoints->Allocate( cVertices ); - - vtkSmartPointer newPolys = - vtkSmartPointer::New(); - newPolys->Allocate( newPolys->EstimateSize(cFaces,VERTICES_PER_FACE) ); - - vtkSmartPointer newNormals = - vtkSmartPointer::New(); - newNormals->Allocate( cVertices ); - newNormals->SetNumberOfComponents( 3 ); - newNormals->SetName( "Normals" ); - - // Go through the surface and copy the vertex and normal for each - // vertex. We have to transform them from surface RAS into normal - // RAS. - float point[3], normal[3], surfaceRAS[3]; - for ( int vno = 0; vno < cVertices; vno++ ) { - - surfaceRAS[0] = mMRIS->vertices[vno].x; - surfaceRAS[1] = mMRIS->vertices[vno].y; - surfaceRAS[2] = mMRIS->vertices[vno].z; - this->ConvertSurfaceToRAS( surfaceRAS, point ); - newPoints->InsertNextPoint( point ); - - normal[0] = mMRIS->vertices[vno].nx; - normal[1] = mMRIS->vertices[vno].ny; - normal[2] = mMRIS->vertices[vno].nz; - newNormals->InsertNextTuple( normal ); - } - - // Go through and add the face indices. - vtkIdType face[VERTICES_PER_FACE]; - for ( int fno = 0; fno < cFaces; fno++ ) { - - face[0] = mMRIS->faces[fno].v[0]; - face[1] = mMRIS->faces[fno].v[1]; - face[2] = mMRIS->faces[fno].v[2]; - newPolys->InsertNextCell( 3, face ); - } - - output->SetPoints( newPoints ); - output->GetPointData()->SetNormals( newNormals ); - newPolys->Squeeze(); // since we've estimated size; reclaim some space - output->SetPolys( newPolys ); -} - -void -vtkFSSurfaceSource::FindPath ( int inStartVertex, int inEndVertex, - vector& iolPath ) { - - if( NULL == mMRIS ) - throw runtime_error( "Must have read in a surface before attempting to find a path" ); - - const int cVerticies = mMRIS->nvertices; - - if( inStartVertex < 0 || inStartVertex >= cVerticies ) - throw runtime_error( "Start VNO is invalid" ); - if( inEndVertex < 0 || inEndVertex >= cVerticies ) - throw runtime_error( "End VNO is invalid" ); - - // We use these arrays to hold the state of the search. The distance - // is the distance from the start to that vertex to that vertex in - // the current shortest path we've gound. The predecessor for a - // vertex is the vertex number right before that vertex in the - // shortest path. The check vector is a list of vertices to check - // (our 'cloud'). - vector aDistance( cVerticies, numeric_limits::max() ); - vector aPredecessor( cVerticies, -1 ); - vector aCheck; - - // Start at the start vertex. - aDistance[inStartVertex] = 0; - aPredecessor[inStartVertex] = inStartVertex; - aCheck.push_back( inStartVertex ); - - // While we're not done and have things to check... - bool bDone = false; - vector::iterator tCheck; - float closestDistance = numeric_limits::max(); - vector::iterator tClosestVertex; - int nClosestVertex; - while( !bDone && !aCheck.empty() ) { - - // Find the closest vertex that needs checking. - closestDistance = numeric_limits::max(); - nClosestVertex = -1; - for ( tCheck = aCheck.begin(); tCheck != aCheck.end(); ++tCheck ) { - if( aDistance[*tCheck] < closestDistance ) { - closestDistance = aDistance[*tCheck]; - tClosestVertex = tCheck; - } - } - - // Take out the closest vertex. - nClosestVertex = *tClosestVertex; - aCheck.erase( tClosestVertex ); - - // If this is it, we're done! - if( inEndVertex == nClosestVertex ) { - - bDone = true; - - } else { - - // Otherwise, look at all our neighbors. We'll call this vertex v. - VERTEX *v = &(mMRIS->vertices[nClosestVertex]); - VERTEX_TOPOLOGY* vt = &(mMRIS->vertices_topology[nClosestVertex]); - for( int nNeighbor = 0; nNeighbor < vt->vnum; nNeighbor++ ) { - - // Get a neighbor. We'll call it u. - int nNeighborVertex = vt->v[nNeighbor]; - VERTEX* u = &(mMRIS->vertices[nNeighborVertex]); - - // Calc the vector from u to v. - float vuX = u->x - v->x; - float vuY = u->y - v->y; - float vuZ = u->z - v->z; - - // Calc the distance here. - float distance = sqrt( vuX*vuX + vuY*vuY + vuZ*vuZ ); - - // If this is a new shortest path to this vertex, update the - // predecessor and the distance here, and add it to the list - // of vertices to check next. - if( distance + aDistance[nClosestVertex] < - aDistance[nNeighborVertex] ) { - aPredecessor[nNeighborVertex] = nClosestVertex; - aDistance[nNeighborVertex] = distance + aDistance[nClosestVertex]; - aCheck.push_back( nNeighborVertex ); - } - } - } - } - - // Add the predecessors from the dest to the src in the output path. - iolPath.clear(); - int nPathVertex = inEndVertex; - iolPath.push_back( inEndVertex ); - while( aPredecessor[nPathVertex] != inStartVertex ) { - - iolPath.push_back( aPredecessor[nPathVertex] ); - nPathVertex = aPredecessor[nPathVertex]; - } - iolPath.push_back( inStartVertex ); - -} - -void -vtkFSSurfaceSource::SmoothValuesOnSurface ( vtkFloatArray& iValues, - int icSteps ) { - - assert( mMRIS ); - - if( iValues.GetNumberOfTuples() != mMRIS->nvertices ) - throw runtime_error( "Number of tuples in values must be equal to the number of vertices in the surface." ); - - if( icSteps <= 0 ) - throw runtime_error( "Number of steps must be > 0." ); - - float* aTmpValues = new float[iValues.GetNumberOfTuples()]; - - // This could probably done in a cleaner way with a VTK object, but - // I want to use this code because it's exactly the same as the old - // tksurfer method. - for( int nStep = 0; nStep < icSteps; nStep++ ) { - - // Copy the current values into our temp array. - for( int nValue = 0; nValue < iValues.GetNumberOfTuples(); nValue++ ) - aTmpValues[nValue] = iValues.GetTuple1( nValue ); - - // For each vertex... - for( int nVertex = 0; nVertex < mMRIS->nvertices; nVertex++ ) { - - // Sum up the values of this vertex and its neighbors. - VERTEX_TOPOLOGY* vt = &mMRIS->vertices_topology[nVertex]; - float sum = aTmpValues[nVertex]; - - for( int nNeighbor = 0; nNeighbor < vt->vnum; nNeighbor++ ) - sum += aTmpValues[vt->v[nNeighbor]]; - - // Set the average in the values array. - iValues.SetTuple1( nVertex, sum / (float)(1 + vt->vnum) ); - } - } - - delete [] aTmpValues; -} diff --git a/vtkfsio/vtkFSSurfaceSource.h b/vtkfsio/vtkFSSurfaceSource.h deleted file mode 100644 index e4504fe1838..00000000000 --- a/vtkfsio/vtkFSSurfaceSource.h +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file vtkFSSurfaceSource.h - * @brief import a freesurfer surface file into vtk - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.11 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - - -#ifndef __vtkFSSurfaceSource_h -#define __vtkFSSurfaceSource_h - -#include - -#include "vtkPolyDataAlgorithm.h" -#include "vtkSmartPointer.h" -extern "C" { -#include "mrisurf.h" -} - -class vtkFloatArray; -class vtkPolyData; -class vtkTransform; - -class vtkFSSurfaceSource : public vtkPolyDataAlgorithm { -public: - - static vtkFSSurfaceSource *New(); - vtkTypeMacro(vtkFSSurfaceSource,vtkPolyDataAlgorithm); - - // Description: - // This will call the MRISread function from the FS library. - void MRISRead ( char const* ifnSurface ); - - // Description: - // Get the output of this source. - vtkPolyData* GetOutput (); - vtkPolyData* GetOutput ( int inOutput ); - void SetOutput ( vtkPolyData* iOutput ); - - // Description: - // Coordinate conversion. RAS space is defined by various header - // metadata and used by the Layer to display things in the right - // space. - void ConvertSurfaceToRAS ( float iSurfX, float iSurfY, float iSurfZ, - float& oRASX, float& oRASY, float& oRASZ ) const; - void ConvertSurfaceToRAS ( double iSurfX, double iSurfY, double iSurfZ, - double& oRASX, double& oRASY, double& oRASZ ) const; - void ConvertRASToSurface ( float iRASX, float iRASY, float iRASZ, - float& oSurfX, float& oSurfY, float& oSurfZ) const; - void ConvertRASToSurface ( double iRASX, double iRASY, double iRASZ, - double& oSurfX, double& oSurfY, double& oSurfZ) const; - void ConvertSurfaceToRAS ( float const iSurf[3], float oRAS[3] ) const; - void ConvertSurfaceToRAS ( double const iSurf[3], double oRAS[3] ) const; - void ConvertRASToSurface ( float const iRAS[3], float oSurf[3] ) const; - void ConvertRASToSurface ( double const iRAS[3], double oSurf[3] ) const; - - void GetRASBounds ( float ioBounds[6] ); - - vtkTransform const* GetSurfaceToRASTransform () const; - - // Description: - // Returns the number of vertices in the surface. - int GetNumberOfVertices () const; - - // Description: - // Get the vertex number from a RAS or surface RAS point. This uses - // the hash table and finds only the closest vertex point. If - // oDistance is not NULL, the distance to the found point will be - // returned there. - int FindVertexAtRAS ( float const iRAS[3], float* oDistance ); - int FindVertexAtRAS ( double const iRAS[3], double* oDistance ); - int FindVertexAtSurfaceRAS ( float const iSurfaceRAS[3],float* oDistance ); - int FindVertexAtSurfaceRAS ( double const iSurfaceRAS[3],double* oDistance ); - - // Description: - // Get the RAS or surface RAS coords at a vertex index. - void GetRASAtVertex ( int inVertex, float ioRAS[3] ); - void GetRASAtVertex ( int inVertex, double ioRAS[3] ); - void GetSurfaceRASAtVertex ( int inVertex, float ioRAS[3] ); - void GetSurfaceRASAtVertex ( int inVertex, double ioRAS[3] ); - - // Description: - // Return a list a of vertex indices that form the shortest path - // from inStartVertex to inEndVertex. - void FindPath ( int inStartVertex, int inEndVertex, - std::vector& iolPath ); - - // Description: - // Given a float array, this will load the values onto the surface, - // smooth the values using surface topology using the number of - // given steps, and write the values back to the float array, - // replacing the original contents (but having the same number of - // elements). - void SmoothValuesOnSurface ( vtkFloatArray& iValues, int icSteps ); - - - MRIS* GetMRIS() { return mMRIS; } - -protected: - - vtkFSSurfaceSource(); - ~vtkFSSurfaceSource(); - - void Execute(); - - // The surface. - MRIS* mMRIS; - - // [ 0 1 2 3 ] - // [ 4 5 6 7 ] - // [ 8 9 10 11 ] - // [ 12 13 14 15 ] - double mSurfaceToRASMatrix[16]; - vtkSmartPointer mSurfaceToRASTransform; - - // RAS bounds. - bool mbBoundsCacheDirty; - float mRASBounds[6]; - - // The center in RAS space. - float mRASCenter[3]; - - // Hash table so we can look up vertices. Uses v->x,y,z. - MRIS_HASH_TABLE* mHashTable; - -private: - vtkFSSurfaceSource(const vtkFSSurfaceSource&); // Not implemented. - void operator=(const vtkFSSurfaceSource&); // Not implemented. -}; - -#endif diff --git a/vtkfsio/vtkFSSurfaceWriter.cxx b/vtkfsio/vtkFSSurfaceWriter.cxx deleted file mode 100644 index c0e2bc64ba7..00000000000 --- a/vtkfsio/vtkFSSurfaceWriter.cxx +++ /dev/null @@ -1,147 +0,0 @@ -/** - * @file vtkFSSurfaceWriter.h - * @brief Writes a vtkPolyData to an MRIS file. - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.4 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#include - -#include "vtkFSSurfaceWriter.h" - -#include "vtkInformation.h" -#include "vtkObjectFactory.h" -#include "vtkPolyData.h" -#include "vtkCellArray.h" - -extern "C" { -#include "mrisurf.h" -} - -vtkCxxRevisionMacro(vtkFSSurfaceWriter, "$Revision: 1.4 $"); -vtkStandardNewMacro(vtkFSSurfaceWriter); - -vtkFSSurfaceWriter::vtkFSSurfaceWriter() : - mMRIS( NULL ), - FileName( NULL ) { -} - -vtkFSSurfaceWriter::~vtkFSSurfaceWriter() { - - if( NULL != mMRIS ) - MRISfree( &mMRIS ); -} - -MRIS* -vtkFSSurfaceWriter::GetMRIS () { - - return mMRIS; -} - -void -vtkFSSurfaceWriter::WriteData () { - - vtkPolyData* input = this->GetInput(); - if( NULL == input ) - return; - - // Try to allocate a surface. - MRIS* mris = - MRISalloc( input->GetNumberOfPoints(), input->GetNumberOfPolys() ); - if( NULL == mris ) { - vtkErrorMacro("Could not allocate MRIS with " - << input->GetNumberOfPoints() << " points and " - << input->GetNumberOfPolys() << " faces." ); - return; - } - - // Make sure we write the proper kind of surface. - mris->type = MRIS_TRIANGULAR_SURFACE; - - // Copy in the vertices. - vtkPoints* points = input->GetPoints(); - assert( points ); - int cPoints = input->GetNumberOfPoints(); - for( int nPoint = 0; nPoint < cPoints; nPoint++ ) { - - double* point = points->GetPoint( nPoint ); - mris->vertices[nPoint].x = point[0]; - mris->vertices[nPoint].y = point[1]; - mris->vertices[nPoint].z = point[2]; - } - - // Copy in the faces. - vtkIdType nFace = 0; - vtkIdType cPointIDs = 0; - vtkIdType* pPointIDs = NULL; - vtkCellArray* polys = input->GetPolys(); - assert( polys ); - - setFaceAttachmentDeferred(mris, true); - - for( polys->InitTraversal(); - polys->GetNextCell( cPointIDs, pPointIDs ); nFace++ ) { - - if( cPointIDs != 3 ) { - vtkErrorMacro("Face with invalid number of points: face " << nFace << " with " << cPointIDs << " points."); - MRISfree( &mris ); - return; - } - - mrisAttachFaceToVertices(mris, nFace, pPointIDs[0], pPointIDs[1], pPointIDs[2]); - } - - setFaceAttachmentDeferred(mris, false); - - // Delete the last MRIS and save this one. - if( NULL != mMRIS ) - MRISfree( &mMRIS ); - mMRIS = mris; - - // Write the data. - char* fnMRIS = strdup( this->FileName ); - MRISwrite( mMRIS, fnMRIS ); - free( fnMRIS ); -} - -int -vtkFSSurfaceWriter::FillInputPortInformation ( int, vtkInformation* ioInfo ) { - - ioInfo->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData" ); - return 1; -} - -vtkPolyData* -vtkFSSurfaceWriter::GetInput () { - - return vtkPolyData::SafeDownCast( this->Superclass::GetInput() ); -} - -vtkPolyData* -vtkFSSurfaceWriter::GetInput ( int iPort ) { - - return vtkPolyData::SafeDownCast( this->Superclass::GetInput( iPort ) ); -} - -void -vtkFSSurfaceWriter::PrintSelf ( ostream& iStream, vtkIndent iIndent ) { - - this->Superclass::PrintSelf( iStream, iIndent ); -} diff --git a/vtkfsio/vtkFSSurfaceWriter.h b/vtkfsio/vtkFSSurfaceWriter.h deleted file mode 100644 index a29b3910693..00000000000 --- a/vtkfsio/vtkFSSurfaceWriter.h +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file vtkFSSurfaceWriter.h - * @brief Writes vtkPolyData to a MRIS file - * - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.2 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#ifndef vtkFSSurfaceWriter_h -#define vtkFSSurfaceWriter_h - -#include "vtkWriter.h" -extern "C" { -#include "mrisurf.h" -} - -class vtkPolyData; - -class vtkFSSurfaceWriter : public vtkWriter { - - public: - - static vtkFSSurfaceWriter *New(); - vtkTypeRevisionMacro(vtkFSSurfaceWriter,vtkWriter); - void PrintSelf(ostream& os, vtkIndent indent); - - // Description: - // Get the input to this writer. - vtkPolyData* GetInput(); - vtkPolyData* GetInput(int port); - - // Description: - // Specify file name of the MRIS data file to write. - vtkSetStringMacro(FileName); - vtkGetStringMacro(FileName); - - MRIS* GetMRIS (); - - protected: - vtkFSSurfaceWriter(); - ~vtkFSSurfaceWriter(); - - void WriteData(); - - virtual int FillInputPortInformation(int port, vtkInformation *info); - - MRIS* mMRIS; - - char* FileName; - - private: - vtkFSSurfaceWriter(const vtkFSSurfaceWriter&); // Not implemented. - void operator=(const vtkFSSurfaceWriter&); // Not implemented. -}; - -#endif - - diff --git a/vtkfsio/vtkFSSurfaceWriterTester.cxx b/vtkfsio/vtkFSSurfaceWriterTester.cxx deleted file mode 100644 index 807c5f0bc3e..00000000000 --- a/vtkfsio/vtkFSSurfaceWriterTester.cxx +++ /dev/null @@ -1,77 +0,0 @@ -#include -#include "vtkFSSurfaceSource.h" -#include "vtkFSSurfaceWriter.h" - -const char* kfnInput = "lh.vtkFSSurfaceWriterTestFile"; -const char* kfnOutput = "lh.vtkFSSurfaceWriterTestFileOut"; - -const char* Progname = "vtkFSSurfaceWriterTester"; - -int -main ( int argc, char** argv ) { - - - // Make a source. - vtkSmartPointer source = - vtkSmartPointer::New(); - source->MRISRead( kfnInput ); - source->Update(); - - // Make a dest. - vtkSmartPointer writer = - vtkSmartPointer::New(); - writer->SetFileName( kfnOutput ); - writer->SetInputConnection( source->GetOutputPort() ); - writer->Update(); - - MRIS* surf1 = source->GetMRIS(); - assert( surf1 ); - MRIS* surf2 = writer->GetMRIS(); - assert( surf2 ); - - // Check the number of verts and faces. - assert( surf1->nvertices == surf2->nvertices ); - assert( surf1->nfaces == surf2->nfaces ); - - // Check vertices. - for( int nVertex = 0; nVertex < surf1->nvertices; nVertex++ ) { - - if( surf1->vertices[nVertex].x != surf2->vertices[nVertex].x ) { - cerr << "Mismatch x on vertex " << nVertex - << ": in " << surf1->vertices[nVertex].x - << ", out " << surf2->vertices[nVertex].x << endl; - exit( 1 ); - } - if( surf1->vertices[nVertex].y != surf2->vertices[nVertex].y ) { - cerr << "Mismatch x on vertex " << nVertex - << ": in " << surf1->vertices[nVertex].y - << ", out " << surf2->vertices[nVertex].y << endl; - exit( 1 ); - } - if( surf1->vertices[nVertex].z != surf2->vertices[nVertex].z ) { - cerr << "Mismatch x on vertex " << nVertex - << ": in " << surf1->vertices[nVertex].z - << ", out " << surf2->vertices[nVertex].z << endl; - exit( 1 ); - } - - } - - // Check faces. - for( int nFace = 0; nFace < surf1->nfaces; nFace++ ) { - - for( int nVertex = 0; nVertex < VERTICES_PER_FACE; nVertex++ ) { - - if( surf1->faces[nFace].v[nVertex] != surf2->faces[nFace].v[nVertex] ) { - cerr << "Mismatch face index on face " << nFace - << ", vertex " << nVertex - << ": in " << surf1->faces[nFace].v[nVertex] - << ", out " << surf2->faces[nFace].v[nVertex] << endl; - exit( 1 ); - } - - } - } - - return 0; -} diff --git a/vtkfsio/vtkFSVolumeSource.cxx b/vtkfsio/vtkFSVolumeSource.cxx deleted file mode 100644 index 85a51496539..00000000000 --- a/vtkfsio/vtkFSVolumeSource.cxx +++ /dev/null @@ -1,884 +0,0 @@ -/** - * @file vtkFSVolumeSource.cxx - * @brief Source for FreeSurfer MRI volumes - * - * This will read any FS MRI volume with the MRIRead command, and - * provide a VTK StructuredPointsSource output port. The output is in - * 'index' space, with the corner at 0,0,0. There are also functions - * for getting the 'RAS' space transforms, which should be used to - * display the output properly in RAS space. - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.12 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -// -// Why use a source and not a reader? -// -// Unlike most VTK pipelines, this object is designed to hold an -// easily editable volume. We keep the actual MRI object in memory and -// allow operations on it, basically a wrapper for the C object and -// functions defined in mri*.c. Then, when it changes, we copy the new -// volume into the output. This doesn't quite fit well into the VTK -// way of things, but it's better than changing a file and re-reading -// it every time. -// - -#include -#include "vtkFSVolumeSource.h" -#include "vtkObjectFactory.h" -#include "vtkShortArray.h" -#include "vtkLongArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkFloatArray.h" -#include "vtkPointData.h" -#include "vtkCellData.h" -#include "vtkIntArray.h" - -using namespace std; - -vtkStandardNewMacro( vtkFSVolumeSource ); -vtkCxxRevisionMacro( vtkFSVolumeSource, "$Revision: 1.12 $" ); - -vtkFSVolumeSource::vtkFSVolumeSource () : - mMRI( NULL ), - mbUseActualPixelSpacing( false ), - mbBoundsCacheDirty( true ) { - mImageData = vtkImageData::New(); -} - -void -vtkFSVolumeSource::MRIRead ( char const* ifn ) { - - char* fn = strdup( ifn ); - mMRI = ::MRIread( fn ); - free( fn ); - - if ( mMRI == NULL ) { - throw runtime_error( "MRIread failed" ); - } - - this->CopyMRIToImage(); - this->CopyMatricesFromMRI(); -} - -void -vtkFSVolumeSource::MRIWrite ( char const* ifn ) { - - char* fn = strdup( ifn ); - int err = ::MRIwrite( mMRI, fn ); - free( fn ); - - if ( err != 0 ) { - throw runtime_error( "MRIwrite failed" ); - } -} - -void -vtkFSVolumeSource::MRIWrite () { - - int err = ::MRIwrite( mMRI, mMRI->fname ); - if ( err != 0 ) { - throw runtime_error( "MRIwrite failed" ); - } -} - -void -vtkFSVolumeSource::ActualSpacingOn () { - - if( !mbUseActualPixelSpacing ) { - mbUseActualPixelSpacing = true; - this->Modified(); - } -} - -void -vtkFSVolumeSource::ActualSpacingOff () { - - if( mbUseActualPixelSpacing ) { - mbUseActualPixelSpacing = false; - this->Modified(); - } -} - -float -vtkFSVolumeSource::GetRASCenterX () { - - if ( mMRI ) - return mMRI->c_r; - else - return -1; -} - -float -vtkFSVolumeSource::GetRASCenterY () { - - if ( mMRI ) - return mMRI->c_a; - else - return -1; -} - -float -vtkFSVolumeSource::GetRASCenterZ () { - - if ( mMRI ) - return mMRI->c_s; - else - return -1; -} - -void -vtkFSVolumeSource::SetVoxelToRASMatrix ( vtkMatrix4x4& iMatrix ) { - - MATRIX* m = MatrixIdentity( 4, NULL ); - for ( int r = 0; r < 4; r++ ) - for ( int c = 0; c < 4; c++ ) - *MATRIX_RELT((m),r+1,c+1) = (float) iMatrix[r][c]; - - MRIsetVoxelToRasXform( mMRI, m ); - - MatrixFree( &m ); - - this->CopyMatricesFromMRI(); -} - - -int -vtkFSVolumeSource::ConvertIndexToRAS ( float iIdxX, float iIdxY, float iIdxZ, - float& oRASX, float& oRASY, float& oRASZ ) { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - double ix, iy, iz, wx, wy, wz; - int r; - - ix = iIdxX; - iy = iIdxY; - iz = iIdxZ; - r = ::MRIvoxelToWorld( mMRI, ix, iy, iz, &wx, &wy, &wz ); - oRASX = wx; - oRASY = wy; - oRASZ = wz; - - return r; -} - -int -vtkFSVolumeSource::ConvertRASToIndex( float iRASX, float iRASY, float iRASZ, - float& oIdxX, float& oIdxY, float& oIdxZ ) { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - double ix, iy, iz, wx, wy, wz; - int r; - - wx = iRASX; - wy = iRASY; - wz = iRASZ; - r = ::MRIworldToVoxel( mMRI, wx, wy, wz, &ix, &iy, &iz ); - oIdxX = ix; - oIdxY = iy; - oIdxZ = iz; - - return r; -} - -int -vtkFSVolumeSource::ConvertRASToIndex( float iRASX, float iRASY, float iRASZ, - int& oIdxX, int& oIdxY, int& oIdxZ ) { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - double wx, wy, wz; - int ix, iy, iz; - int r; - - wx = iRASX; - wy = iRASY; - wz = iRASZ; - r = ::MRIworldToVoxelIndex( mMRI, wx, wy, wz, &ix, &iy, &iz ); - oIdxX = ix; - oIdxY = iy; - oIdxZ = iz; - - return r; -} - -void -vtkFSVolumeSource::Execute () { - - vtkStructuredPoints* output = this->GetOutput(); - if ( output == NULL ) { - return; - } - - // Set relevant information from the ImageData in the output. - if( mbUseActualPixelSpacing ) - mImageData->SetSpacing( mMRI->xsize, mMRI->ysize, mMRI->zsize ); - else - mImageData->SetSpacing( 1, 1, 1 ); - output->SetSpacing( mImageData->GetSpacing() ); - output->SetOrigin( mImageData->GetOrigin() ); - output->SetDimensions( mImageData->GetDimensions() ); - - // Just pass the output a pointer to our scalars. - output->GetPointData()->SetScalars - ( mImageData->GetPointData()->GetScalars() ); -} - - - -void -vtkFSVolumeSource::ExecuteInformation () { - - vtkStructuredPoints* output = this->GetOutput(); - if ( output == NULL ) { - return; - } - - // Set relevant information from the ImageData in the output. - output->SetWholeExtent( mImageData->GetWholeExtent() ); - output->SetScalarType( mImageData->GetScalarType() ); - output->SetNumberOfScalarComponents - ( mImageData->GetNumberOfScalarComponents() ); - if( mbUseActualPixelSpacing ) - mImageData->SetSpacing( mMRI->xsize, mMRI->ysize, mMRI->zsize ); - else - mImageData->SetSpacing( 1, 1, 1 ); - output->SetSpacing( mImageData->GetSpacing() ); - output->SetOrigin( mImageData->GetOrigin() ); -} - - -float -vtkFSVolumeSource::GetValueAtIndex (float iIdxX, float iIdxY, float iIdxZ, float iIdxFrame ) { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - int aDimensions[3]; - mImageData->GetDimensions( aDimensions ); - if ( iIdxX < 0 || iIdxX >= aDimensions[0] || - iIdxY < 0 || iIdxY >= aDimensions[1] || - iIdxZ < 0 || iIdxZ >= aDimensions[2] ) { - return -1; - } - - float oValue = -1; - switch ( mMRI->type ) { - case MRI_UCHAR: - oValue = MRIseq_vox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ, (int)iIdxFrame ); - break; - case MRI_INT: - oValue = MRIIseq_vox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ, (int)iIdxFrame ); - break; - case MRI_LONG: - oValue = MRILseq_vox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ, (int)iIdxFrame ); - break; - case MRI_FLOAT: - oValue = MRIFseq_vox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ, (int)iIdxFrame ); - break; - case MRI_SHORT: - oValue = MRISseq_vox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ, (int)iIdxFrame ); - break; - default: - oValue = 0; - break ; - } - - return oValue; - -} - -float -vtkFSVolumeSource::GetValueAtIndex (float iIdxX, float iIdxY, float iIdxZ ) { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - int aDimensions[3]; - mImageData->GetDimensions( aDimensions ); - if ( iIdxX < 0 || iIdxX >= aDimensions[0] || - iIdxY < 0 || iIdxY >= aDimensions[1] || - iIdxZ < 0 || iIdxZ >= aDimensions[2] ) { - return -1; - } - - float oValue; - switch ( mMRI->type ) { - case MRI_UCHAR: - oValue = MRIvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ); - break; - case MRI_INT: - oValue = MRIIvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ); - break; - case MRI_LONG: - oValue = MRILvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ); - break; - case MRI_FLOAT: - oValue = MRIFvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ); - break; - case MRI_SHORT: - oValue = MRISvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ); - break; - default: - oValue = 0; - break ; - } - - return oValue; -} - -void -vtkFSVolumeSource::SetValueAtIndex ( float iIdxX, float iIdxY, float iIdxZ, - float iValue ) { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return; - } - - // Make sure the index is in our bounds. - int aDimensions[3]; - mImageData->GetDimensions( aDimensions ); - if ( iIdxX < 0 || iIdxX >= aDimensions[0] || - iIdxY < 0 || iIdxY >= aDimensions[1] || - iIdxZ < 0 || iIdxZ >= aDimensions[2] ) { - return; - } - - // Get our scalars. - vtkDataArray *scalars = mImageData->GetPointData()->GetScalars(); - if ( !scalars ) { - vtkErrorMacro( << "Couldn't get scalars" ); - } - - // Calculate a flat index from our coordinates. - int index = (int)iIdxX + - ((int)iIdxY * aDimensions[0]) + - ((int)iIdxZ * aDimensions[0] * aDimensions[1]); - - // Set the value in the scalars array. - scalars->SetComponent( index, 0, iValue ); - - // We are now modified. - this->Modified(); - - // Set the value in the MRI. - switch ( mMRI->type ) { - case MRI_UCHAR: - MRIvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ) = (unsigned char)iValue; - break; - case MRI_INT: - MRIIvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ) = (int)iValue; - break; - case MRI_LONG: - MRILvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ) = (long)iValue; - break; - case MRI_FLOAT: - MRIFvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ) = iValue; - break; - case MRI_SHORT: - MRISvox( mMRI, (int)iIdxX, (int)iIdxY, (int)iIdxZ ) = (short)iValue; - break; - default: - break ; - } -} - -float -vtkFSVolumeSource::GetMinValue () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - float min, max; - MRIvalRange( mMRI, &min, &max ); - return min; -} - -float -vtkFSVolumeSource::GetMaxValue () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - float min, max; - MRIvalRange( mMRI, &min, &max ); - return max; -} - -float -vtkFSVolumeSource::GetPixelSizeX () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - return mMRI->xsize; -} - -float -vtkFSVolumeSource::GetPixelSizeY () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - return mMRI->ysize; -} - -float -vtkFSVolumeSource::GetPixelSizeZ () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - return mMRI->zsize; -} - -float -vtkFSVolumeSource::GetPixelSize ( const int iDimension ) { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - float size = -1; - - const int x = 0; - const int y = 1; - const int z = 2; - - if( iDimension == x ) { - size = this->GetPixelSizeX(); - } else if( iDimension == y ) { - size = this->GetPixelSizeY(); - } else if( iDimension == z ) { - size = this->GetPixelSizeZ(); - } - - return size; - -} - -float -vtkFSVolumeSource::GetXDimension () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - return mMRI->width; -} - -float -vtkFSVolumeSource::GetYDimension () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - return mMRI->height; -} - -float -vtkFSVolumeSource::GetZDimension () { - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return -1; - } - - return mMRI->depth; -} - -int* -vtkFSVolumeSource::GetDimensions () { - - if ( NULL != mImageData ) - return mImageData->GetDimensions(); - else - return NULL; -} - -void -vtkFSVolumeSource::CopyMRIToImage () { - - vtkDataArray *scalars = NULL; - vtkUnsignedCharArray *ucharScalars = NULL; - vtkIntArray *intScalars = NULL; - vtkShortArray *shortScalars = NULL; - vtkLongArray *longScalars = NULL; - vtkFloatArray *floatScalars = NULL; - int cValues; - int nZ, nY; - - if ( mMRI == NULL ) { - vtkErrorMacro( << "No MRI is present." ); - return; - } - - int zX = mMRI->width; - int zY = mMRI->height; - int zZ = mMRI->depth; - int zFrames = mMRI->nframes; - - // This object's output space is in voxel coordinates. - mImageData->SetDimensions( zX, zY, zZ ); - - // TODO: this is where the pixel spacing should go, but it messes up this - // visualization in scuba2 right now -- fix later - if( mbUseActualPixelSpacing ) - mImageData->SetSpacing( mMRI->xsize, mMRI->ysize, mMRI->zsize ); - else - mImageData->SetSpacing( 1, 1, 1 ); - - mImageData->SetOrigin( -zX/2, -zY/2, -zZ/2 ); - mImageData->SetWholeExtent( 0, zX-1, 0, zY-1, 0, zZ-1 ); - mImageData->SetNumberOfScalarComponents( zFrames ); - - // create the scalars for all of the images. set the element size - // for the data we will read. - vtkDebugMacro (<< "Creating vtkUnsignedCharArray"); - switch ( mMRI->type ) { - case MRI_UCHAR: - mImageData->SetScalarTypeToUnsignedChar(); - ucharScalars = vtkUnsignedCharArray::New(); - scalars = (vtkDataArray*) ucharScalars; - break; - case MRI_INT: - mImageData->SetScalarTypeToInt(); - intScalars = vtkIntArray::New(); - scalars = (vtkDataArray*) intScalars; - break; - case MRI_LONG: - mImageData->SetScalarTypeToLong(); - longScalars = vtkLongArray::New(); - scalars = (vtkDataArray*) longScalars; - break; - case MRI_FLOAT: - mImageData->SetScalarTypeToFloat(); - floatScalars = vtkFloatArray::New(); - scalars = (vtkDataArray*) floatScalars; - break; - case MRI_SHORT: - mImageData->SetScalarTypeToShort(); - shortScalars = vtkShortArray::New(); - scalars = (vtkDataArray*) shortScalars; - break; - default: - break ; - } - - if ( NULL == scalars ) { - vtkErrorMacro(<< "Couldn't allocate scalars array."); - return; - } - - // change the number of components to store tuples - if( zFrames > 1 ) { - scalars->SetNumberOfComponents( zFrames ); - } - - cValues = zX * zY * zZ; - scalars->Allocate( cValues ); - - // Copy the slice data into the scalars. - vtkDebugMacro (<< "Copying " << cValues << " values into the scalars array"); - float* tuple = (float*) malloc( sizeof(float) * zFrames ); - int nTuple = 0; - for ( nZ = 0; nZ < zZ; nZ++ ) { - for ( nY = 0; nY < zY; nY++ ) { -#if 1 - for ( int nX = 0; nX < zX; nX++ ) { - for ( int nFrame = 0; nFrame < zFrames; nFrame++ ) { - - switch ( mMRI->type ) { - case MRI_UCHAR: - scalars->InsertComponent( nTuple, nFrame, - MRIseq_vox( mMRI, nX, nY, nZ, nFrame ) ); - break; - case MRI_INT: - scalars->InsertComponent( nTuple, nFrame, - MRIIseq_vox( mMRI, nX, nY, nZ, nFrame ) ); - break; - case MRI_LONG: - scalars->InsertComponent( nTuple, nFrame, - MRILseq_vox( mMRI, nX, nY, nZ, nFrame ) ); - break; - case MRI_FLOAT: - scalars->InsertComponent( nTuple, nFrame, - MRIFseq_vox( mMRI, nX, nY, nZ, nFrame ) ); - break; - case MRI_SHORT: - scalars->InsertComponent( nTuple, nFrame, - MRISseq_vox( mMRI, nX, nY, nZ, nFrame ) ); - break; - default: - break; - } - - } - nTuple++; - - } - -#else - // Not sure how this will work when reading in frames. - vtkDebugMacro (<< "Getting a write pointer for " << - cValues << " values"); - switch ( mMRI->type ) { - case MRI_UCHAR: - pixels = (void*) ucharScalars->WritePointer( cRead, zX * zElement ); - break; - case MRI_INT: - pixels = (void*) intScalars->WritePointer( cRead, zX * zElement ); - break; - case MRI_LONG: - pixels = (void*) longScalars->WritePointer( cRead, zX * zElement ); - break; - case MRI_FLOAT: - pixels = (void*) floatScalars->WritePointer( cRead, zX * zElement ); - break; - case MRI_SHORT: - pixels = (void*) shortScalars->WritePointer( cRead, zX * zElement ); - break; - default: - break ; - } - if ( NULL == pixels ) { - vtkErrorMacro (<< "Couldn't get a write pointer"); - return; - } - memcpy( pixels, mMRI->slices[nZ][nY], zX* zElement ); - cRead += zX; -#endif - } - } - free( tuple ); - - // Assign the scalars array to the image. - mImageData->GetPointData()->SetScalars( scalars ); - - scalars->Delete(); - - this->Modified(); - - // Need to recalc our bounds at some point. - mbBoundsCacheDirty = true; -} - -void -vtkFSVolumeSource::GetRASBounds ( float oRASBounds[6] ) { - - if ( NULL == mMRI ) { - - oRASBounds[0] = oRASBounds[1] = oRASBounds[2] = - oRASBounds[3] = oRASBounds[4] = oRASBounds[5] = 0; - - return; - } - - // If we need to rebuild the cache... - if ( mbBoundsCacheDirty ) { - - mRASBounds[0] = mRASBounds[2] = mRASBounds[4] = 999999; - mRASBounds[1] = mRASBounds[3] = mRASBounds[5] = -999999; - - // For each corner, convert to RAS, and get the bounds. - float cornerFactor[3]; - float RAS[3]; - for ( cornerFactor[2] = 0; cornerFactor[2] <= 1; cornerFactor[2]++ ) { - for ( cornerFactor[1] = 0; cornerFactor[1] <= 1; cornerFactor[1]++ ) { - for ( cornerFactor[0] = 0; cornerFactor[0] <= 1; cornerFactor[0]++ ) { - - this->ConvertIndexToRAS( cornerFactor[0]*mMRI->width, - cornerFactor[1]*mMRI->height, - cornerFactor[2]*mMRI->depth, - RAS[0], RAS[1], RAS[2] ); - - if ( RAS[0] < mRASBounds[0] ) mRASBounds[0] = RAS[0]; - if ( RAS[0] > mRASBounds[1] ) mRASBounds[1] = RAS[0]; - if ( RAS[1] < mRASBounds[2] ) mRASBounds[2] = RAS[1]; - if ( RAS[1] > mRASBounds[3] ) mRASBounds[3] = RAS[1]; - if ( RAS[2] < mRASBounds[4] ) mRASBounds[4] = RAS[2]; - if ( RAS[2] > mRASBounds[5] ) mRASBounds[5] = RAS[2]; - } - } - } - - mbBoundsCacheDirty = false; - } - - oRASBounds[0] = mRASBounds[0]; - oRASBounds[1] = mRASBounds[1]; - oRASBounds[2] = mRASBounds[2]; - oRASBounds[3] = mRASBounds[3]; - oRASBounds[4] = mRASBounds[4]; - oRASBounds[5] = mRASBounds[5]; -} - -void -vtkFSVolumeSource::GetUnscaledRASBounds ( float oUnscaledRASBounds[6] ) { - - // get the scaled bounds - this->GetRASBounds( oUnscaledRASBounds ); - - // divide out the scale factor - for( int n=0; n<3; n++ ) { - - const int nLow = n * 2; - const int nHigh = n * 2 + 1; - - oUnscaledRASBounds[ nLow ] /= this->GetPixelSize( n ); - oUnscaledRASBounds[ nHigh ] /= this->GetPixelSize( n ); - - } - -} - -void -vtkFSVolumeSource::GetUnscaledVoxelToRASMatrix ( double oMatrix[16] ) { - - // copy all the components - for( int n=0; n<16; n++ ) { - oMatrix[ n ] = mVoxelToRASMatrix[ n ]; - } - - // divide out the scale factor - oMatrix[ 0 ] *= this->GetPixelSizeX(); - oMatrix[ 5 ] *= this->GetPixelSizeY(); - oMatrix[ 10 ] *= this->GetPixelSizeZ(); - -} - -void -vtkFSVolumeSource::GetUnscaledRASToVoxelMatrix ( double* oMatrix ) { - - // copy all the components - for( int n=0; n<16; n++ ) { - oMatrix[ n ] = mRASToVoxelMatrix[ n ]; - } - - // divide out the scale factor - oMatrix[ 0 ] *= this->GetPixelSizeX(); - oMatrix[ 5 ] *= this->GetPixelSizeY(); - oMatrix[ 10 ] *= this->GetPixelSizeZ(); - -} - -void -vtkFSVolumeSource::CopyMatricesFromMRI () { - - if ( NULL == mMRI ) - return; - - MATRIX* m = extract_i_to_r( mMRI ); - for ( int i = 0; i < 16; i++ ) { - mVoxelToRASMatrix[i] = (double) *MATRIX_RELT((m),(i/4)+1,(i%4)+1); - } - MatrixFree( &m ); - - m = extract_r_to_i( mMRI ); - for ( int i = 0; i < 16; i++ ) { - mRASToVoxelMatrix[i] = (double) *MATRIX_RELT((m),(i/4)+1,(i%4)+1); - } - MatrixFree( &m ); - - mbBoundsCacheDirty = true; -} - -float -vtkFSVolumeSource::GetPreferredValueIncrement () { - - if ( !mMRI ) - return 1; - - // First look at the range. If it's an int or char type, increment - // is 1. - switch ( mMRI->type ) { - - case MRI_UCHAR: - case MRI_INT: - case MRI_LONG: - case MRI_SHORT: - return 1; - - default: - - // Look at the range. If it's > 100, inc is 1, 10-100, inc is .1, - // 1-10, inc is .01, etc. - float range = this->GetMaxValue() - this->GetMinValue(); - float inc = 1; - if ( range >= 1000000 ) { - inc = 1000; - } else if ( range >= 100000 ) { - inc = 100; - } else if ( range >= 10000 ) { - inc = 10; - } else if ( range >= 1000 ) { - inc = 1; - } else if ( range >= 10 ) { - inc = 0.1; - } else if ( range >= 1 ) { - inc = 0.01; - } else if ( range >= 0.1 ) { - inc = 0.001; - } else if ( range >= 0.01 ) { - inc = 0.0001; - } else if ( range >= 0.001 ) { - inc = 0.00001; - } else if ( range >= 0.0001 ) { - inc = 0.000001; - } else if ( range >= 0.00001 ) { - inc = 0.0000001; - } else if ( range >= 0.000001 ) { - inc = 0.00000001; - } else { - inc = 0.000000001; - } - - return inc; - } -} diff --git a/vtkfsio/vtkFSVolumeSource.h b/vtkfsio/vtkFSVolumeSource.h deleted file mode 100644 index 4fedf51b847..00000000000 --- a/vtkfsio/vtkFSVolumeSource.h +++ /dev/null @@ -1,184 +0,0 @@ -/** - * @file vtkFSVolumeSource.h - * @brief Source for FreeSurfer MRI volumes - * - * This will read any FS MRI volume with the MRIRead command, and - * provide a VTK StructuredPointsSource output port. The output is in - * 'index' space, with the corner at 0,0,0. There are also functions - * for getting the 'RAS' space transforms, which should be used to - * display the output properly in RAS space. - */ -/* - * Original Author: Kevin Teich - * CVS Revision Info: - * $Author: nicks $ - * $Date: 2011/03/02 00:04:56 $ - * $Revision: 1.8 $ - * - * Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH" - * - * Terms and conditions for use, reproduction, distribution and contribution - * are found in the 'FreeSurfer Software License Agreement' contained - * in the file 'LICENSE' found in the FreeSurfer distribution, and here: - * - * https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense - * - * Reporting: freesurfer@nmr.mgh.harvard.edu - * - */ - -#ifndef __vtkFSVolumeSource_h -#define __vtkFSVolumeSource_h - -#include "vtkStructuredPoints.h" -#include "vtkStructuredPointsSource.h" -#include "vtkImageData.h" -#include "vtkMatrix4x4.h" -extern "C" { -#include "mri.h" -} - -// These are defined in the mri headers somewhere. You will probably -// have to do this in files that include this file. -#ifdef X -#undef X -#endif -#ifdef Y -#undef Y -#endif - - -class vtkFSVolumeSource : public vtkStructuredPointsSource { -public: - - static vtkFSVolumeSource *New(); - vtkTypeRevisionMacro( vtkFSVolumeSource, vtkStructuredPointsSource ); - - // Description: - // This will call the MRIread function from the FS library. - void MRIRead ( char const* ifnVolume ); - - // Description: - // This writes the volume. The volume type is determined by the - // filename extension or format. If no filename is given, it will - // use the orignal filename, overwriting the original volume. - void MRIWrite ( char const* ifnVolume ); - void MRIWrite (); - - // Description: - // If set to true, the output image will have the proper spacing - // from the MRI {x,y,z}size values. If false, spacing will just be - // 1,1,1. - void ActualSpacingOn (); - void ActualSpacingOff (); - - // Description: - // Coordinate conversion. RAS space is defined by various header - // metadata and used by the Layer to display things in the right - // space. - int ConvertIndexToRAS ( float iIdxX, float iIdxY, float iIdxZ, - float& oRASX, float& oRASY, float& oRASZ ); - int ConvertRASToIndex ( float iRASX, float iRASY, float iRASZ, - float& oIdxX, float& oIdxY, float& oIdxZ ); - int ConvertRASToIndex ( float iRASX, float iRASY, float iRASZ, - int& oIdxX, int& oIdxY, int& oIdxZ ); - - void GetRASBounds ( float oRASBounds[6] ); - - void GetUnscaledRASBounds ( float oUnscaledRASBounds[6] ); - - double* GetVoxelToRASMatrix () { - return mVoxelToRASMatrix; - } - - // Description: - // Returns the RAS matrix, but without pixel scaling - void GetUnscaledVoxelToRASMatrix ( double oMatrix[16] ); - - double* GetRASToVoxelMatrix () { - return mRASToVoxelMatrix; - } - - // Description: - // Returns the RAS matrix, but without pixel scaling - void GetUnscaledRASToVoxelMatrix ( double* oMatrix ); - - void SetVoxelToRASMatrix ( vtkMatrix4x4& iMatrix ); - - float GetRASCenterX (); - float GetRASCenterY (); - float GetRASCenterZ (); - - // Description: - // Get and set the value at the given index. - float GetValueAtIndex ( float iIdxX, float iIdxY, float iIdxZ ); - void SetValueAtIndex ( float iIdxX, float iIdxY, float iIdxZ, - float iValue ); - float GetValueAtIndex (float iIdxX, float iIdxY, float iIdxZ, float iIdxFrame ); - - - // Description: - // Get the min and max value in the volume. - float GetMinValue (); - float GetMaxValue (); - - // Description: - // Get the pixel size in RAS space from the metadata. - float GetPixelSizeX (); - float GetPixelSizeY (); - float GetPixelSizeZ (); - float GetPixelSize ( const int iDimension ); - - // Description: - // Returns the number of elements in a dimension. This is in index - // space. - float GetXDimension (); - float GetYDimension (); - float GetZDimension (); - int* GetDimensions (); - - // Description: - // Returns a best guess value increment for a GUI. - float GetPreferredValueIncrement (); - -protected: - - vtkFSVolumeSource (); - ~vtkFSVolumeSource () {}; - - // Overriding to output the volume data. - void Execute (); - void ExecuteInformation (); - - // If we have a new MRI, we copy the data to our local storage. - void CopyMRIToImage (); - void CopyMatricesFromMRI (); - - // Pointer to the MRI. - MRI* mMRI; - - // Whether or not to use actual pixel spacing in the output image. - bool mbUseActualPixelSpacing; - - // The local copy of the SP data. - vtkImageData* mImageData; - - // [ 0 1 2 3 ] - // [ 4 5 6 7 ] - // [ 8 9 10 11 ] - // [ 12 13 14 15 ] - double mVoxelToRASMatrix[16]; - double mRASToVoxelMatrix[16]; - - // RAS bounds. - bool mbBoundsCacheDirty; - float mRASBounds[6]; - -private: - vtkFSVolumeSource(const vtkFSVolumeSource&); // Not implemented. - void operator=(const vtkFSVolumeSource&); // Not implemented. -}; - -#endif - - diff --git a/vtkutils/vtkFreesurferLookupTable.h b/vtkutils/vtkFreesurferLookupTable.h index 42d55411bdb..f9ab1083c16 100644 --- a/vtkutils/vtkFreesurferLookupTable.h +++ b/vtkutils/vtkFreesurferLookupTable.h @@ -31,9 +31,7 @@ //#include "vtkRenderingCoreModule.h" // For export macro #include "vtkLookupTable.h" -extern "C" { #include "colortab.h" -} class vtkFreesurferLookupTable : public vtkLookupTable { diff --git a/vtkutils/vtkKWRGBATransferFunctionEditorTester.cxx b/vtkutils/vtkKWRGBATransferFunctionEditorTester.cxx index 37f7a954c2e..60604fc29ae 100644 --- a/vtkutils/vtkKWRGBATransferFunctionEditorTester.cxx +++ b/vtkutils/vtkKWRGBATransferFunctionEditorTester.cxx @@ -1,8 +1,6 @@ #include "vtkKWRGBATransferFunctionEditorTester.h" -extern "C" { - #include "mrisurf.h" -} +#include "mrisurf.h" #include "vtkObjectFactory.h" #include "vtkKWWindowBase.h" @@ -12,9 +10,7 @@ extern "C" { #include "vtkFloatArray.h" #include "vtkKWHistogram.h" -extern "C" { - extern int Rgbatransferfunctioneditortesterlib_SafeInit ( Tcl_Interp* ); -} +extern int Rgbatransferfunctioneditortesterlib_SafeInit ( Tcl_Interp* ); const char* Progname = "vtkKWRGBATransferFunctionEditorTester";