├── iocbio ├── analysis │ ├── __init__.py │ ├── src │ │ ├── imageinterp.h │ │ ├── iocbio_fperiod.h │ │ ├── iocbio_detrend.h │ │ ├── fperiod.h │ │ ├── dp.pyf │ │ └── fperiod.pyf │ ├── setup.py │ ├── script_options.py │ ├── scripts │ │ └── sarcomere_length.py │ └── tests │ │ ├── test_sarcomere.py │ │ └── test_dp.py ├── chaco │ ├── __init__.py │ ├── setup.py │ ├── scripts │ │ └── analyze.py │ ├── array_data_source.py │ ├── markers.py │ ├── point.py │ ├── cursor_tool.py │ ├── base_viewer_task.py │ ├── timeit.py │ ├── base_data_source.py │ ├── fft_viewer_task.py │ ├── points_task.py │ ├── scale_space_task.py │ ├── tiff_file_info.py │ ├── image_timeseries_viewer.py │ ├── line_selector_task.py │ ├── main.py │ └── slice_selector_task.py ├── kinetics │ ├── setup.py │ ├── __init__.py │ ├── demo_model.py │ └── DemoModel_mass.c ├── strathkelvin │ ├── scripts │ │ └── strathkelvin929.py │ ├── setup.py │ ├── __init__.py │ ├── script_options.py │ └── reader.py ├── scanner │ ├── __init__.py │ ├── setup.py │ ├── cache.py │ ├── sample_clock.py │ └── configuration.py ├── __init__.py ├── microscope │ ├── setup.py │ ├── __init__.py │ ├── examples │ │ └── test_deconvolve_1d.py │ ├── snr.py │ ├── tutorial │ │ └── mk_figures.sh │ ├── dv.py │ └── scripts │ │ ├── estimate_psf.py │ │ ├── deconvolve_with_sphere.py │ │ └── deconvolve.py ├── io │ ├── setup.py │ ├── __init__.py │ └── scripts │ │ ├── ome.py │ │ └── rowfile_plot.py ├── ops │ ├── examples │ │ ├── regress.py │ │ ├── apply_window.py │ │ ├── convolve.py │ │ ├── acf.py │ │ └── acf_dominant_frequency.py │ ├── __init__.py │ ├── src │ │ ├── discrete_gauss.h │ │ ├── acf.h │ │ ├── discrete_gauss_ext.c │ │ ├── minpack │ │ │ ├── enorm.f │ │ │ ├── fdjac2.f │ │ │ └── lmdif1.f │ │ └── discrete_gauss.c │ ├── filters.py │ ├── setup.py │ ├── convolution.py │ ├── scripts │ │ ├── convolve.py │ │ ├── apply_noise.py │ │ ├── apply_window.py │ │ └── estimate_snr.py │ └── window.py ├── README.txt ├── fperiod │ ├── src │ │ ├── iocbio_detrend.h │ │ ├── iocbio_fperiod.h │ │ ├── imageinterp.h │ │ ├── iocbio_ipwf_manual.c │ │ ├── demo.c │ │ ├── libfperiod.h │ │ └── fperiod.pyf │ ├── setup.py │ └── tests │ │ └── test_fperiod.py ├── version.py ├── script_options.py ├── setup.py └── chaco_examples │ └── tiff_viewer.py ├── doc ├── source │ ├── _static │ │ ├── convolve_1d.png │ │ ├── regress_1d.png │ │ ├── apply_window_1d.png │ │ ├── regress_kernels.png │ │ ├── acf_dominant_frequency.png │ │ └── deconvolve_poisson_1d.png │ ├── _templates │ │ └── autosummary │ │ │ └── class.rst │ └── index.rst ├── Makefile └── BuildWindowsInstallersOnLinux.txt ├── README.txt ├── installer ├── wineit2.sh ├── wineit.sh ├── iocbio_installer.py ├── make_iocbio_installer.bat ├── README.txt └── make_iocbio_installer.sh ├── mk_apidocs.sh ├── mk_wininstaller.sh ├── MANIFEST.in ├── mk_installer.sh ├── README.md ├── LICENSE.txt ├── setup.py └── mingw └── matplotlib-1.0.0.patch /iocbio/analysis/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /doc/source/_static/convolve_1d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearu/iocbio/HEAD/doc/source/_static/convolve_1d.png -------------------------------------------------------------------------------- /doc/source/_static/regress_1d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearu/iocbio/HEAD/doc/source/_static/regress_1d.png -------------------------------------------------------------------------------- /doc/source/_static/apply_window_1d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearu/iocbio/HEAD/doc/source/_static/apply_window_1d.png -------------------------------------------------------------------------------- /doc/source/_static/regress_kernels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearu/iocbio/HEAD/doc/source/_static/regress_kernels.png -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | 2 | Please refer to 3 | 4 | http://code.google.com/p/iocbio/ 5 | 6 | for information and installation instructions. 7 | -------------------------------------------------------------------------------- /doc/source/_static/acf_dominant_frequency.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearu/iocbio/HEAD/doc/source/_static/acf_dominant_frequency.png -------------------------------------------------------------------------------- /doc/source/_static/deconvolve_poisson_1d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearu/iocbio/HEAD/doc/source/_static/deconvolve_poisson_1d.png -------------------------------------------------------------------------------- /installer/wineit2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | export WINEPREFIX=$HOME/local/.wine2 3 | export WINEDEBUG=fixme-all,warn-all 4 | wine cmd /c $1 5 | -------------------------------------------------------------------------------- /mk_apidocs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | PYTHONPATH=`pwd`:$PYTHONPATH 4 | 5 | cd doc && make clean && make html || exit 1 6 | cd - 7 | exit 0 8 | 9 | -------------------------------------------------------------------------------- /iocbio/chaco/__init__.py: -------------------------------------------------------------------------------- 1 | """Enthought Chaco extensions. 2 | 3 | .. currentmodule:: iocbio.chaco 4 | 5 | Package content 6 | --------------- 7 | """ 8 | -------------------------------------------------------------------------------- /mk_wininstaller.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | PYTHONPATH= wine python setup.py build --compiler=mingw32 install_lib bdist_wininst --install-script=iocbio_nt_post_install.py 4 | -------------------------------------------------------------------------------- /iocbio/kinetics/setup.py: -------------------------------------------------------------------------------- 1 | 2 | def configuration(parent_package='',top_path=None): 3 | from numpy.distutils.misc_util import Configuration 4 | return Configuration('kinetics', parent_package,top_path) 5 | 6 | -------------------------------------------------------------------------------- /iocbio/chaco/setup.py: -------------------------------------------------------------------------------- 1 | 2 | from os.path import join 3 | 4 | def configuration(parent_package='',top_path=None): 5 | from numpy.distutils.misc_util import Configuration 6 | config = Configuration('chaco',parent_package,top_path) 7 | return config 8 | -------------------------------------------------------------------------------- /iocbio/strathkelvin/scripts/strathkelvin929.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Runs IOCBio.StrathKelvin GUI application. 4 | """ 5 | 6 | ### START UPDATE SYS.PATH ### 7 | ### END UPDATE SYS.PATH ### 8 | 9 | from iocbio.strathkelvin.main import main 10 | main() 11 | -------------------------------------------------------------------------------- /iocbio/scanner/__init__.py: -------------------------------------------------------------------------------- 1 | """ Scanner of confocal microscope. 2 | 3 | .. currentmodule:: iocbio.scanner 4 | 5 | The :mod:`iocbio.scanner` provides the following modules: 6 | 7 | .. autosummary:: 8 | 9 | curve 10 | 11 | """ 12 | 13 | __autodoc__ = ['curve'] 14 | -------------------------------------------------------------------------------- /iocbio/strathkelvin/setup.py: -------------------------------------------------------------------------------- 1 | 2 | from os.path import join 3 | 4 | def configuration(parent_package='',top_path=None): 5 | from numpy.distutils.misc_util import Configuration 6 | config = Configuration('strathkelvin',parent_package,top_path) 7 | return config 8 | 9 | -------------------------------------------------------------------------------- /iocbio/__init__.py: -------------------------------------------------------------------------------- 1 | # To make iocbio directory a Python package. Keep this file empty!! 2 | """IOCBio 3 | 4 | """ 5 | 6 | __autodoc__ = ['io', 'utils', 'ops', 'microscope', 'optparse_gui', 'utils', 'scanner', 7 | 'strathkelvin', 'timeunit', 'fperiod'] 8 | 9 | 10 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | # Use .add_data_files and .add_data_dir methods in a appropriate 2 | # setup.py files to include non-python files such as documentation, 3 | # data, etc files to distribution. Avoid using MANIFEST.in for that. 4 | # 5 | include MANIFEST.in 6 | include *.txt 7 | include setup.py 8 | include iocbio/*/scripts/*.py -------------------------------------------------------------------------------- /iocbio/kinetics/__init__.py: -------------------------------------------------------------------------------- 1 | """ Kinetic equation generator and solver. 2 | 3 | .. currentmodule:: iocbio.kinetics 4 | 5 | The :mod:`iocbio.kinetics` provides the following modules: 6 | 7 | .. autosummary:: 8 | 9 | oxygen_isotope_model 10 | 11 | """ 12 | 13 | __autodoc__ = ['oxygen_isotope_model'] 14 | -------------------------------------------------------------------------------- /iocbio/microscope/setup.py: -------------------------------------------------------------------------------- 1 | 2 | from os.path import join 3 | 4 | def configuration(parent_package='',top_path=None): 5 | from numpy.distutils.misc_util import Configuration 6 | config = Configuration('microscope',parent_package,top_path) 7 | config.add_extension('ops_ext', join('src','ops_ext.c')) 8 | return config 9 | -------------------------------------------------------------------------------- /iocbio/scanner/setup.py: -------------------------------------------------------------------------------- 1 | 2 | from os.path import join 3 | 4 | def configuration(parent_package='',top_path=None): 5 | from numpy.distutils.misc_util import Configuration 6 | config = Configuration('scanner',parent_package,top_path) 7 | #config.add_extension('regress_ext', join('src','regress_ext.c')) 8 | return config 9 | -------------------------------------------------------------------------------- /installer/wineit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | export WINEPREFIX=$HOME/local/.wine 3 | test -d $WINEPREFIX || mkdir -p $WINEPREFIX 4 | export WINEDEBUG=fixme-all,warn-all 5 | test -f mingw-get-inst-20110316.exe || wget http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/mingw-get-inst-20110316/mingw-get-inst-20110316.exe 6 | wine cmd /c $1 2.6 7 | -------------------------------------------------------------------------------- /iocbio/io/setup.py: -------------------------------------------------------------------------------- 1 | 2 | from os.path import join 3 | 4 | def configuration(parent_package='',top_path=None): 5 | from numpy.distutils.misc_util import Configuration 6 | config = Configuration('io',parent_package,top_path) 7 | config.add_extension('_tifffile', join('src','tifffile.c')) 8 | config.add_data_files('ome.xsd') 9 | return config 10 | -------------------------------------------------------------------------------- /iocbio/strathkelvin/__init__.py: -------------------------------------------------------------------------------- 1 | """ Starthkelvin 929 Oxygen System software wrapper. 2 | 3 | .. currentmodule:: iocbio.strathkelvin 4 | 5 | Use `iocbio.strathkelvin929` script to run GUI of this module. 6 | 7 | .. autosummary:: 8 | 9 | main 10 | mailslot 11 | fakemailslot 12 | menu_tools_wx 13 | """ 14 | 15 | __autodoc__ = ['main', 'mailslot', 'fakemailslot', 'menu_tools_wx'] 16 | -------------------------------------------------------------------------------- /iocbio/microscope/__init__.py: -------------------------------------------------------------------------------- 1 | """ Microscope image manipulation tools. 2 | 3 | .. currentmodule:: iocbio.microscope 4 | 5 | The :mod:`iocbio.microscope` provides the following modules: 6 | 7 | .. autosummary:: 8 | 9 | psf 10 | deconvolution 11 | 12 | """ 13 | 14 | __autodoc__ = ['cluster_tools', 'psf', 'deconvolution', 15 | 'spots_to_psf', 'snr'] 16 | 17 | from .psf import spots_to_psf 18 | -------------------------------------------------------------------------------- /iocbio/chaco/scripts/analyze.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | # Author: Pearu Peterson 4 | # Created: December 2010 5 | 6 | from __future__ import division 7 | import sys 8 | 9 | ### START UPDATE SYS.PATH ### 10 | ### END UPDATE SYS.PATH ### 11 | 12 | from iocbio.chaco.main import analyze 13 | 14 | if len(sys.argv)>1: 15 | file_name = sys.argv[1] 16 | else: 17 | file_name = '' 18 | analyze(file_name=file_name) 19 | -------------------------------------------------------------------------------- /iocbio/chaco/array_data_source.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['ArrayDataSource'] 3 | 4 | from enthought.traits.api import Instance 5 | from enthought.traits.ui.api import View, Group, Item 6 | from .base_data_source import BaseDataSource 7 | 8 | class ArrayDataSource(BaseDataSource): 9 | 10 | original_source = Instance(BaseDataSource) 11 | 12 | traits_view = View(Group(Item("original_source", style='readonly'))) 13 | 14 | def get_pixel_sizes (self): 15 | return self.original_source.get_pixel_sizes() 16 | -------------------------------------------------------------------------------- /iocbio/ops/examples/regress.py: -------------------------------------------------------------------------------- 1 | from numpy import * 2 | from scipy.stats import poisson 3 | from iocbio.ops.regress import regress 4 | x = arange(0,2*pi,0.1) 5 | data = 50+7*sin(x)+5*sin(2*x) 6 | data_with_noise = poisson.rvs (data) 7 | data_estimate, data_estimate_grad = regress(data_with_noise, (0.1, ), 8 | kernel='tricube', 9 | boundary='periodic', 10 | method='average') 11 | 12 | -------------------------------------------------------------------------------- /iocbio/analysis/src/imageinterp.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for imageinterp.c. 3 | 4 | Author: Pearu Peterson 5 | Created: May 2011 6 | */ 7 | 8 | #ifndef IMAGEINTERP_H 9 | #define IMAGEINTERP_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | 15 | extern void imageinterp_get_roi(int image_width, int image_height, double *image, 16 | int i0, int j0, int i1, int j1, double width, 17 | int roi_width, int roi_height, double *roi 18 | ); 19 | #ifdef __cplusplus 20 | } 21 | #endif 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /mk_installer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | SVNVERSION=`svnversion` 4 | 5 | 6 | PYVER=26 7 | 8 | PACKAGENAME=iocbio 9 | SUMMARY="IOCBio software installer (revision $SVNVERSION)" 10 | PROJECT=iocbio 11 | LABELS="Type-Source,OpSys-Windows,Featured" 12 | 13 | #cd installer 14 | #./wineit.sh make_iocbio_installer.bat 15 | #cd - 16 | 17 | INSTALLER=installer/iocbio_installer_py$PYVER.exe 18 | echo INSTALLER=$INSTALLER 19 | test -f $INSTALLER || exit 1 20 | python installer/googlecode_upload.py --summary="$SUMMARY" --project="$PROJECT" --labels="$LABELS" $INSTALLER 21 | -------------------------------------------------------------------------------- /doc/source/_templates/autosummary/class.rst: -------------------------------------------------------------------------------- 1 | {% extends "!autosummary/class.rst" %} 2 | 3 | {% block methods %} 4 | {% if methods %} 5 | .. HACK 6 | .. autosummary:: 7 | :toctree: 8 | {% for item in methods %} 9 | {{ name }}.{{ item }} 10 | {%- endfor %} 11 | {% endif %} 12 | {% endblock %} 13 | 14 | {% block attributes %} 15 | {% if attributes %} 16 | .. HACK 17 | .. autosummary:: 18 | :toctree: 19 | {% for item in attributes %} 20 | {{ name }}.{{ item }} 21 | {%- endfor %} 22 | {% endif %} 23 | {% endblock %} 24 | -------------------------------------------------------------------------------- /iocbio/chaco/markers.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['LowerLeftMarker', 'UpperRightMarker'] 3 | 4 | import numpy 5 | from enthought.enable.api import CircleMarker 6 | from enthought.kiva.constants import NO_MARKER 7 | 8 | class LowerLeftMarker(CircleMarker): 9 | 10 | kiva_marker = NO_MARKER 11 | circle_points = CircleMarker.circle_points.copy ()[4:] 12 | circle_points[0] = (0,0) 13 | 14 | class UpperRightMarker(CircleMarker): 15 | 16 | kiva_marker = NO_MARKER 17 | circle_points = numpy.dot(CircleMarker.circle_points, numpy.array([[0,-1],[-1,0]]))[4:] 18 | circle_points[0] = (0,0) 19 | -------------------------------------------------------------------------------- /iocbio/ops/examples/apply_window.py: -------------------------------------------------------------------------------- 1 | 2 | from numpy import * 3 | from iocbio.ops import apply_window 4 | 5 | data = ones (50) 6 | window0 = apply_window(data, (1/20., ), smoothness=0, background=0.2) 7 | window1 = apply_window(data, (1/20., ), smoothness=1, background=0) 8 | 9 | from matplotlib import pyplot as plt 10 | 11 | plt.plot (data,label='data') 12 | plt.plot (window0,'o',label='smoothness=0, bg=0.2') 13 | plt.plot (window1,'o',label='smoothness=1, bg=0') 14 | plt.legend () 15 | plt.xlabel ('x') 16 | plt.ylabel ('data') 17 | plt.title ('Applying window to constant data=1') 18 | 19 | plt.savefig('apply_window_1d.png') 20 | 21 | plt.show () 22 | -------------------------------------------------------------------------------- /iocbio/chaco/point.py: -------------------------------------------------------------------------------- 1 | 2 | from enthought.traits.api import HasStrictTraits, Int, Tuple, Bool, Any, Property, cached_property 3 | 4 | class Point(HasStrictTraits): 5 | 6 | coordinates = Tuple (Int, Int, Int) 7 | x = Property(depends_on='coordinates') 8 | y = Property(depends_on='coordinates') 9 | z = Property(depends_on='coordinates') 10 | 11 | selected = Bool(False) 12 | value = Any 13 | 14 | @cached_property 15 | def _get_z (self): return self.coordinates[0] 16 | @cached_property 17 | def _get_y (self): return self.coordinates[1] 18 | @cached_property 19 | def _get_x (self): return self.coordinates[2] 20 | -------------------------------------------------------------------------------- /iocbio/analysis/src/iocbio_fperiod.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for iocbio_fperiod.c. See the C source file for documentation. 3 | 4 | Author: Pearu Peterson 5 | Created: October 2011 6 | */ 7 | 8 | #ifndef IOCBIO_FPERIOD_H 9 | #define IOCBIO_FPERIOD_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | 15 | extern void iocbio_objective(double *y, int k, double *f, int n, int m, int order, int method, double *r); 16 | extern double iocbio_fperiod(double *f, int n, int m, double initial_period, int detrend, int method); 17 | extern double iocbio_fperiod_cached(double *f, int n, int m, double initial_period, int detrend, int method, double *cache); 18 | 19 | #ifdef __cplusplus 20 | } 21 | #endif 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /iocbio/scanner/cache.py: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | import cPickle as pickle 4 | 5 | class Cache: 6 | 7 | def __init__ (self, filename): 8 | self.filename = filename 9 | self.data = {} 10 | 11 | def load(self): 12 | if os.path.isfile (self.filename): 13 | 14 | try: 15 | f = open (self.filename, 'rb') 16 | self.data = pickle.load(f) 17 | f.close() 18 | except EOFError, msg: 19 | print 'Loading %r failed with EOFError: %s' % (self.filename, msg) 20 | self.data = {} 21 | 22 | return self 23 | 24 | def dump (self): 25 | f = open (self.filename, 'wb') 26 | pickle.dump (self.data, f) 27 | f.close() 28 | -------------------------------------------------------------------------------- /iocbio/ops/examples/convolve.py: -------------------------------------------------------------------------------- 1 | 2 | from numpy import * 3 | from scipy.stats import poisson 4 | from iocbio.ops import convolve 5 | kernel = array([0,1,2,2,2,1,0]) 6 | x = arange(0,2*pi,0.1) 7 | data = 50+7*sin(x)+5*sin(2*x) 8 | data_with_noise = poisson.rvs(data) 9 | data_convolved = convolve(kernel, data_with_noise) 10 | 11 | 12 | from matplotlib import pyplot as plt 13 | 14 | plt.plot (x,data,label='data') 15 | plt.plot (x,data_with_noise,'o',label='data with poisson noise') 16 | plt.plot (x,data_convolved,label='convolved noisy data') 17 | plt.legend () 18 | plt.xlabel ('x') 19 | plt.ylabel ('data') 20 | plt.title ('Convolution with %s for recovering data=50+7*sin(x)+5*sin(2*x)' % (kernel)) 21 | 22 | plt.savefig('convolve_1d.png') 23 | 24 | plt.show () 25 | -------------------------------------------------------------------------------- /iocbio/chaco/cursor_tool.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['CursorTool'] 3 | 4 | from enthought.traits.api import Instance 5 | from enthought.chaco.tools.cursor_tool import CursorTool2D 6 | from enthought.chaco.tools.cursor_tool import CursorTool as _CursorTool 7 | from enthought.enable.markers import CircleMarker 8 | from enthought.chaco.base_2d_plot import Base2DPlot 9 | 10 | class IocbioCursorTool2D(CursorTool2D): 11 | 12 | # Allow using subclasses of CircleMarker: 13 | marker = Instance(CircleMarker, ()) 14 | invisible_layout = None 15 | 16 | def CursorTool(component, *args, **kwds): 17 | if isinstance(component, Base2DPlot): 18 | return IocbioCursorTool2D(component, *args, **kwds) 19 | return _CursorTool(component, *args, **kwds) 20 | CursorTool.__doc__ = _CursorTool.__doc__ 21 | -------------------------------------------------------------------------------- /iocbio/README.txt: -------------------------------------------------------------------------------- 1 | 2 | How to add new subpackages to iocbio? 3 | ===================================== 4 | 5 | To add a subpackage, say ``foo``, to ``iocbio`` package, 6 | insert the following line:: 7 | 8 | config.add_subpackage('foo') 9 | 10 | to ``iocbio/setup.py`` file and copy the directory of the ``foo`` 11 | package to ``iocbio/`` directory. 12 | 13 | After installing ``iocbio``, the subpackage ``foo`` will be 14 | accessible as follows:: 15 | 16 | >>> import iocbio.foo 17 | 18 | For generating documentation from package sources, add subpackage 19 | information to the following files:: 20 | 21 | iocbio/__init__.py 22 | 23 | Subpackage Python scripts must be in ``foo/scripts/`` directory and 24 | optparse argument definitions should be in ``foo/script_options.py``. 25 | Installation of scripts will add ``iocbio.`` prefix to scripts names. 26 | -------------------------------------------------------------------------------- /iocbio/analysis/src/iocbio_detrend.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for dp.c. See dp.c for documentation. 3 | 4 | Author: Pearu Peterson 5 | Created: October 2011 6 | */ 7 | 8 | #ifndef IOCBIO_DETREND_H 9 | #define IOCBIO_DETREND_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | 15 | extern void iocbio_detrend(double *f, int n, int m, double period, double *r); 16 | extern void iocbio_trend(double *f, int n, int m, double period, double *r); 17 | extern void iocbio_detrend1(double *f, int n, int fstride, double period, double *r, int rstride); 18 | extern void iocbio_compute_trend_spline_data(double *f, int n, double period, 19 | int* nof_extremes, double* extreme_positions, double* extreme_values, 20 | int* nof_averages, double* average_positions, double* average_values); 21 | 22 | #ifdef __cplusplus 23 | } 24 | #endif 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /iocbio/fperiod/src/iocbio_detrend.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for dp.c. See dp.c for documentation. 3 | 4 | Author: Pearu Peterson 5 | Created: October 2011 6 | */ 7 | 8 | #ifndef IOCBIO_DETREND_H 9 | #define IOCBIO_DETREND_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | 15 | extern void iocbio_detrend(double *f, int n, int m, double period, double *r); 16 | extern void iocbio_trend(double *f, int n, int m, double period, double *r); 17 | extern void iocbio_detrend1(double *f, int n, int fstride, double period, double *r, int rstride); 18 | extern void iocbio_compute_trend_spline_data(double *f, int n, double period, 19 | int* nof_extremes, double* extreme_positions, double* extreme_values, 20 | int* nof_averages, double* average_positions, double* average_values); 21 | 22 | #ifdef __cplusplus 23 | } 24 | #endif 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /iocbio/fperiod/src/iocbio_fperiod.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for iocbio_fperiod.c. See the C source file for documentation. 3 | 4 | Author: Pearu Peterson 5 | Created: October 2011 6 | */ 7 | 8 | #ifndef IOCBIO_FPERIOD_H 9 | #define IOCBIO_FPERIOD_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | 15 | extern void iocbio_objective(double *y, int k, double *f, int n, int m, int order, int method, double *r); 16 | extern double iocbio_fperiod(double *f, int n, int m, double initial_period, int detrend, int method); 17 | extern double iocbio_fperiod_cached(double *f, int n, int m, double initial_period, int detrend, int method, double *cache); 18 | extern double iocbio_fperiod2_cached(double *f, int n, int m, double min_period, double max_period, int detrend, int method, double *cache); 19 | 20 | #ifdef __cplusplus 21 | } 22 | #endif 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /iocbio/chaco/base_viewer_task.py: -------------------------------------------------------------------------------- 1 | 2 | from enthought.traits.api import HasStrictTraits, Instance, Str, DelegatesTo, Bool 3 | from .base_data_viewer import BaseDataViewer 4 | 5 | class BaseViewerTask(HasStrictTraits): 6 | 7 | viewer = Instance (BaseDataViewer) 8 | is_complex = DelegatesTo('viewer') 9 | is_real = Bool(True) 10 | name = Str 11 | 12 | def _is_complex_changed(self): 13 | self.is_real = not self.is_complex 14 | 15 | def __init__(self, viewer = None): 16 | HasStrictTraits.__init__ (self, viewer=viewer) 17 | self.startup() 18 | 19 | def startup (self): 20 | raise NotImplementedError ('%s must implement startup() method.' % (self.__class__.__name__)) 21 | 22 | def _name_default (self): 23 | n = self.__class__.__name__ 24 | if n.endswith ('Task'): 25 | n = n[:-4] 26 | return n 27 | -------------------------------------------------------------------------------- /iocbio/io/__init__.py: -------------------------------------------------------------------------------- 1 | """Microscope data I/O tools 2 | 3 | Overview 4 | ======== 5 | 6 | .. currentmodule:: iocbio.io 7 | 8 | The :mod:`iocbio.io` provides the following I/O related tools to 9 | read, write, and hold microscope data: 10 | 11 | .. autosummary:: 12 | 13 | io.load_image_stack 14 | io.save_image_stack 15 | image_stack.ImageStack 16 | io.RowFile 17 | cacher.Cacher 18 | 19 | The front-end class for I/O tasks is 20 | `iocbio.io.image_stack.ImageStack`, see `iocbio.io.image_stack` for 21 | more information. 22 | """ 23 | 24 | __autodoc__ = ['image_stack', 'pathinfo', 'io', 25 | 'RowFile', 'ImageStack', 'load_image_stack','save_image_stack', 26 | 'cacher', 'Cacher'] 27 | 28 | from .image_stack import ImageStack 29 | from .io import RowFile, load_image_stack, save_image_stack 30 | from .cacher import Cacher 31 | import pathinfo 32 | 33 | -------------------------------------------------------------------------------- /iocbio/ops/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Operations on microscope images. 3 | 4 | .. currentmodule:: iocbio.ops 5 | 6 | The :mod:`iocbio.ops` provides the following modules for for 7 | manipulating microscope images. 8 | 9 | .. autosummary:: 10 | 11 | regression 12 | convolution 13 | window 14 | fft_tasks 15 | autocorrelation 16 | filters 17 | 18 | """ 19 | 20 | __autodoc__ = ['regression', 'convolution', 'window', 'regress', 'convolve','apply_window', 21 | 'fft_tasks', 'FFTTasks', 22 | 'autocorrelation', 'acf', 'acf_argmax', 'acf_sinefit', 23 | 'filters', 'convolve_discrete_gauss'] 24 | 25 | from .regression import regress 26 | from .convolution import convolve 27 | from .window import apply_window 28 | from .fft_tasks import FFTTasks 29 | from .autocorrelation import acf, acf_argmax, acf_sinefit 30 | from .filters import convolve_discrete_gauss 31 | -------------------------------------------------------------------------------- /doc/source/index.rst: -------------------------------------------------------------------------------- 1 | IOCBio 2 | ====== 3 | 4 | :Release: |version| 5 | :Date: |today| 6 | 7 | The `IOCBio`__ project provides open-source software that is developed 8 | in `Laboratory of Systems Biology`__ at `Institute of 9 | Cybernetics`__. The project is created to publish the software, this 10 | includes distributing the source codes, continuing software 11 | development, supporting users as well as attracting users to 12 | contribute to the software. 13 | 14 | __ http://code.google.com/p/iocbio/ 15 | __ http://sysbio.ioc.ee/ 16 | __ http://www.ioc.ee/ 17 | 18 | Please report any issues to `IOCBio Issue Tracker`__. 19 | 20 | __ http://code.google.com/p/iocbio/issues/list 21 | 22 | Reference 23 | ========= 24 | 25 | .. toctree:: 26 | :maxdepth: 3 27 | 28 | reference/iocbio 29 | reference/libtiff 30 | reference/nidaqmx 31 | 32 | .. .. include:: generated/scripts.rst 33 | 34 | 35 | See also 36 | -------- 37 | `List of documentations with examples `_ 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /iocbio/fperiod/src/imageinterp.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for imageinterp.c. See the source for documentation. 3 | 4 | Author: Pearu Peterson 5 | Created: May 2011 6 | */ 7 | 8 | #ifndef IMAGEINTERP_H 9 | #define IMAGEINTERP_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | 15 | extern void imageinterp_get_roi8(int image_width, int image_height, unsigned char *image, 16 | double di_size, double dj_size, 17 | double i0, double j0, double i1, double j1, 18 | int roi_width, int roi_height, double *roi, 19 | double* roi_di_size, double* roi_dj_size, 20 | int interpolation 21 | ); 22 | 23 | extern void imageinterp_get_roi(int image_width, int image_height, double *image, 24 | double di_size, double dj_size, 25 | double i0, double j0, double i1, double j1, 26 | int roi_width, int roi_height, double *roi, 27 | double *roi_di_size, double *roi_dj_size, 28 | int interpolation 29 | ); 30 | 31 | #ifdef __cplusplus 32 | } 33 | #endif 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /iocbio/microscope/examples/test_deconvolve_1d.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy 3 | from iocbio.ops import convolve 4 | from iocbio.microscope.deconvolution import deconvolve 5 | from iocbio.io import ImageStack 6 | import scipy.stats 7 | 8 | from matplotlib import pyplot as plt 9 | 10 | kernel = numpy.array([0,1,3,1,0]) 11 | test_data = numpy.array([0, 0,0,0,2, 0,0,0,0, 0,1,0,1, 0,0,0])*50 12 | data =convolve(kernel, test_data) 13 | degraded_data = scipy.stats.poisson.rvs(numpy.where(data<=0, 1e-16, data)).astype(data.dtype) 14 | 15 | psf = ImageStack(kernel, voxel_sizes = (1,)) 16 | stack = ImageStack(degraded_data, voxel_sizes = (1,)) 17 | 18 | deconvolved_data = deconvolve(psf, stack).images 19 | 20 | plt.plot(test_data, label='test') 21 | plt.plot (data, label='convolved') 22 | plt.plot (degraded_data, label='degraded') 23 | plt.plot (deconvolved_data, label='deconvolved') 24 | plt.legend() 25 | plt.ylabel('data') 26 | plt.xlabel('index') 27 | plt.title('Deconvolving degraded test data.') 28 | plt.savefig('deconvolve_poisson_1d.png') 29 | plt.show () 30 | -------------------------------------------------------------------------------- /iocbio/analysis/setup.py: -------------------------------------------------------------------------------- 1 | 2 | from os.path import join 3 | def configuration(parent_package='',top_path=None): 4 | from numpy.distutils.misc_util import Configuration 5 | config = Configuration('analysis',parent_package,top_path) 6 | config.add_extension('lineinterp', sources = [join('src','lineinterp.c')]) 7 | config.add_extension('imageinterp', sources = [join('src','imageinterp.c')], 8 | define_macros = [('PYTHON_EXTENSION', None)]) 9 | 10 | config.add_extension('fperiod', sources = [ 11 | join('src','fperiod.pyf'), 12 | join('src','fperiod.c')]) 13 | 14 | config.add_extension('dp', sources = [ 15 | join('src','dp.pyf'), 16 | join('src','iocbio_detrend.c'), 17 | join('src','iocbio_fperiod.c'), 18 | join('src','iocbio_ipwf.c'), 19 | ]) 20 | 21 | config.add_extension('ipwf', sources = [ 22 | join('src','ipwf.pyf'), 23 | join('src','iocbio_ipwf.c'), 24 | ]) 25 | return config 26 | -------------------------------------------------------------------------------- /iocbio/chaco/timeit.py: -------------------------------------------------------------------------------- 1 | import time 2 | from iocbio.utils import time2str, bytes2str 3 | from numpy.testing import memusage 4 | 5 | class TimeIt(object): 6 | 7 | def __init__ (self, viewer, title): 8 | self.title = title 9 | self.viewer = viewer 10 | viewer.status = '%s..' % (title) 11 | self.start_memusage = memusage() 12 | self.start_time = time.time() 13 | 14 | def stop(self, message = None): 15 | if self.viewer is not None: 16 | elapsed = time.time() - self.start_time 17 | memdiff = memusage() - self.start_memusage 18 | if message: 19 | status = '%s %s' % (self.title, message) 20 | else: 21 | status = '%s took %s and %s' % (self.title, time2str(elapsed), bytes2str(memdiff)) 22 | self.viewer.status = status 23 | self.viewer = None 24 | 25 | __del__ = stop 26 | 27 | def update (self, message): 28 | if self.viewer is not None: 29 | self.viewer.status = '%s..%s' % (self.title, message) 30 | -------------------------------------------------------------------------------- /iocbio/ops/examples/acf.py: -------------------------------------------------------------------------------- 1 | 2 | from numpy import * 3 | from iocbio.ops.autocorrelation import acf, acf_argmax, acf_sinefit 4 | # Define a signal: 5 | dx = 0.05 6 | x = arange(0,2*pi,dx) 7 | N = len(x) 8 | f = 7*sin(5*x)+6*sin(9*x) 9 | # f is shown in the upper right plot below 10 | # Calculate autocorrelation function: 11 | y = arange(0,N,0.1) 12 | af = acf (f, y, method='linear') 13 | # af is shown in the lower right plot below 14 | # Find the first maximum of the autocorrelation function: 15 | y_max1 = acf_argmax(f, method='linear') 16 | # The first maximum gives period estimate for f 17 | print 'period=',dx*y_max1 18 | print 'frequency=',2*pi/(y_max1*dx) 19 | # Find the second maximum of the autocorrelation function: 20 | y_max2 = acf_argmax(f, start_j=y_max1+1, method='linear') 21 | print y_max1, y_max2 22 | # Find sine-fit of the autocorrelation function: 23 | omega = acf_sinefit(f, method='linear') 24 | # The parameter omega in A*cos (omega*y)*(N-y)/N gives 25 | # another period estimate for f: 26 | print 'period=',2*pi/(omega/dx) 27 | print 'frequency=', omega/dx 28 | 29 | -------------------------------------------------------------------------------- /iocbio/fperiod/setup.py: -------------------------------------------------------------------------------- 1 | 2 | from os.path import join 3 | def configuration(parent_package='',top_path=None): 4 | from numpy.distutils.misc_util import Configuration 5 | config = Configuration('fperiod',parent_package,top_path) 6 | 7 | config.add_extension('imageinterp', sources = [join('src','imageinterp.c')], 8 | define_macros = [('PYTHON_EXTENSION', None)]) 9 | 10 | config.add_extension('fperiod_ext', sources = [ 11 | join('src','fperiod.pyf'), 12 | join('src','iocbio_detrend.c'), 13 | join('src','iocbio_fperiod.c'), 14 | join('src','iocbio_ipwf.c'), 15 | ], 16 | #define_macros = [('F2PY_REPORT_ATEXIT','1')] 17 | depends = [join('src','iocbio_ipwf_manual.c')] 18 | ) 19 | 20 | config.add_extension('ipwf', sources = [ 21 | join('src','ipwf.pyf'), 22 | join('src','iocbio_ipwf.c'), 23 | ], 24 | depends = [join('src','iocbio_ipwf_manual.c')] 25 | ) 26 | return config 27 | -------------------------------------------------------------------------------- /iocbio/version.py: -------------------------------------------------------------------------------- 1 | 2 | # THIS FILE IS GENERATED FROM iocbio/setup.py 3 | short_version='1.3.0' 4 | version='1.3.0' 5 | release=False 6 | 7 | if not release: 8 | version += '.dev' 9 | import os 10 | svn_version_file = os.path.join(os.path.dirname(__file__), 11 | '__svn_version__.py') 12 | svn_entries_file = os.path.join(os.path.dirname(__file__),'.svn', 13 | 'entries') 14 | if os.path.isfile(svn_version_file): 15 | import imp 16 | svn = imp.load_module('iocbio.__svn_version__', 17 | open(svn_version_file), 18 | svn_version_file, 19 | ('.py','U',1)) 20 | version += svn.version 21 | elif os.path.isfile(svn_entries_file): 22 | import subprocess 23 | try: 24 | svn_version = subprocess.Popen(["svnversion", os.path.dirname (__file__)], stdout=subprocess.PIPE).communicate()[0] 25 | except: 26 | pass 27 | else: 28 | version += svn_version.strip() 29 | 30 | print version 31 | -------------------------------------------------------------------------------- /installer/iocbio_installer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | 6 | if 0 and 'admin' not in sys.argv and len (sys.argv)==1: 7 | import subprocess 8 | print subprocess.call(['runas', '/user:Administrator', '"\"%s\" admin"' % sys.argv[0]]) 9 | raw_input('Press ENTER to close this program...') 10 | sys.exit() 11 | 12 | try: 13 | from gui import Model 14 | import gui_resources 15 | import gui_python 16 | 17 | working_dir = r'c:\iocbio\_install' 18 | 19 | installer_log_tmpl = os.path.join(working_dir, 'iocbio_installer_%d.log') 20 | i = 0 21 | installer_log = installer_log_tmpl % i 22 | while os.path.isfile(installer_log): 23 | i += 1 24 | installer_log = installer_log_tmpl % i 25 | 26 | resources = [ 27 | 'iocbio' 28 | ] 29 | 30 | Model(logfile=installer_log, 31 | working_dir = working_dir 32 | ).run (resources) 33 | 34 | print __file__,'normal exit' 35 | except: 36 | import traceback 37 | traceback.print_exc () 38 | print __file__,'abnormal exit' 39 | 40 | raw_input('Press ENTER to close this program...') 41 | sys.exit(0) 42 | -------------------------------------------------------------------------------- /iocbio/strathkelvin/script_options.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['set_strathkelvin929_options', 3 | 'set_strathkelvin929_rate_options'] 4 | 5 | from iocbio.script_options import set_formatter 6 | 7 | def set_strathkelvin929_options (parser): 8 | set_formatter(parser) 9 | parser.set_usage('%prog') 10 | parser.set_description('Wrapper of Strathkelvin 929 System software, the GUI program.') 11 | 12 | def set_strathkelvin929_rate_options(parser): 13 | set_formatter(parser) 14 | parser.set_usage('%prog [options] ') 15 | parser.set_description('Re-calculates oxygen respiration rates. Rewrites the channel files unless --tryrun is used.') 16 | 17 | parser.add_option('--nof-regression-points', '-n', 18 | type = 'int', default=10, 19 | help = 'Specify the number of regression points. When 0 then use the number from channel files.') 20 | parser.add_option('--tryrun', action = 'store_true', 21 | help = 'Re-calculate rates but do not save rates to file.') 22 | parser.add_option('--no-tryrun', action = 'store_false', dest='tryrun', 23 | help = 'See --tryrun.') 24 | -------------------------------------------------------------------------------- /iocbio/ops/src/discrete_gauss.h: -------------------------------------------------------------------------------- 1 | #ifndef DISCRETE_GAUSS_H_INCLUDE 2 | #define DISCRETE_GAUSS_H_INCLUDE 3 | #include "fftw3.h" 4 | 5 | #ifdef __cplusplus 6 | extern "C" { 7 | #endif 8 | 9 | typedef struct 10 | { 11 | int rank; 12 | int dims[3]; 13 | int howmany; 14 | int sz; /* prod(dims) */ 15 | double *rdata; 16 | double *hcdata; /* fft of rdata */ 17 | double *kernel_real; /* filter kernel: real part */ 18 | double *kernel_imag; /* filter kernel: imaginary part */ 19 | fftw_plan r2hc_plan; 20 | fftw_plan hc2r_plan; 21 | } DGR2HCConfig; 22 | 23 | 24 | // user interface: 25 | extern int dg_convolve(double *seq, int n, double t); 26 | extern int dg_high_pass_filter(double *seq, int n, int rows, double t); 27 | 28 | // user interface with fftw plan caching: 29 | extern int dg_high_pass_filter_init(DGR2HCConfig *config, int rank, int dims[3], int howmany, double scale_parameter); 30 | extern int dg_high_pass_filter_clean(DGR2HCConfig *config); 31 | extern int dg_high_pass_filter_apply(DGR2HCConfig *config, double *seq); 32 | extern int dg_DGR2HCConfig_apply_real_filter(DGR2HCConfig *config); 33 | 34 | #ifdef __cplusplus 35 | } 36 | #endif 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /iocbio/ops/filters.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['convolve_discrete_gauss'] 3 | 4 | import numpy 5 | 6 | def convolve_discrete_gauss(seq, t): 7 | """ Return convolved sequence with discrete Gaussian kernel. 8 | 9 | Parameters 10 | ---------- 11 | seq : numpy.ndarray 12 | t : float 13 | Scale parameter. 14 | 15 | Notes 16 | ----- 17 | 18 | The discrete Gaussian kernel ``T(n,t)`` is defined as 19 | ``exp(-t)*I_n(t)`` where ``I_n(t)`` is the modified Bessel 20 | functions of integer order. The Fourier transform of ``T(n,t)`` is 21 | ``exp((cos(2*pi*k/N)-1)*t)`` where ``k=0..N-1``. 22 | 23 | The half-height-width of the discrete Gaussian kernel ``T(n,t)`` 24 | is approximately ``2.36*sqrt(t)``. So, to smooth out details 25 | over W points, use ``t = (W/2.36)**2``. 26 | 27 | References 28 | ---------- 29 | http://www.nada.kth.se/~tony/abstracts/Lin90-PAMI.html 30 | http://en.wikipedia.org/wiki/Scale-space_implementation 31 | """ 32 | n = len(seq) 33 | fseq = numpy.fft.fft (seq) 34 | theta = 2*numpy.pi*numpy.fft.fftfreq(n) 35 | fker = numpy.exp((numpy.cos(theta)-1)*t) 36 | fres = fseq * fker 37 | res = numpy.fft.ifft (fres) 38 | res = res.real 39 | return res 40 | -------------------------------------------------------------------------------- /installer/make_iocbio_installer.bat: -------------------------------------------------------------------------------- 1 | @rem Author: Pearu Peterson 2 | @rem Created: Apr 2011 3 | @ECHO OFF 4 | echo "ARGS:" %0 %1 5 | 6 | set MINGW_INSTALLER=mingw-get-inst-20110316.exe 7 | set MINGW_ROOT=C:\MinGW 8 | set GET_EXE=%MINGW_ROOT%\bin\mingw-get.exe 9 | set BASH_EXE=%MINGW_ROOT%\msys\1.0\bin\bash.exe 10 | set PATH=%MINGW_ROOT%\bin;%MINGW_ROOT%\msys\1.0\bin;%PATH% 11 | 12 | if exist "%MINGW_INSTALLER%" GOTO MINGWINSTALL 13 | @echo Download the following MinGW installer: 14 | @echo 15 | @echo http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/mingw-get-inst-20110316/mingw-get-inst-20110316.exe 16 | @echo 17 | @echo and rerun this batch file "%0" 18 | GOTO END 19 | :MINGWINSTALL 20 | @echo "%MINGW_INSTALLER%" exists 21 | 22 | if exist "%MINGW_ROOT%" GOTO HAS_MINGW 23 | mingw-get-inst-20110316.exe 24 | :HAS_MINGW 25 | @echo "%MINGW_ROOT%" exists 26 | 27 | if exist "%BASH_EXE%" GOTO HAS_BASH 28 | %GET_EXE% install msys-bash msys-core msys-coreutils msys-wget msys-unzip 29 | GOTO SKIP 30 | %GET_EXE% install msys-bash msys-core msys-coreutils msys-wget msys-unzip gfortran g++ binutils msys-patch msys-tar msys-make 31 | :SKIP 32 | :HAS_BASH 33 | @echo "%BASH_EXE%" exists 34 | %BASH_EXE% make_iocbio_installer.sh %1 35 | :END 36 | @echo EOF %0 -------------------------------------------------------------------------------- /iocbio/analysis/script_options.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['set_sarcomere_length_options'] 3 | 4 | import os 5 | from optparse import OptionGroup, NO_DEFAULT 6 | from iocbio.script_options import set_formatter 7 | 8 | def set_sarcomere_length_options (parser): 9 | from ..io.script_options import get_microscope_options_group, get_io_options_group 10 | set_formatter (parser) 11 | parser.set_usage('%prog [options] [ -i INPUT_PATH ]') 12 | parser.set_description('Estimate the length of sarcomere.') 13 | parser.add_option ('--input-path','-i', 14 | type = 'file', metavar='PATH', 15 | help = 'Specify input PATH of 3D images.' 16 | ) 17 | parser.add_option ('--roi-center-line', 18 | help = 'Specify the coordinates of ROI center line in pixels: x0,y0,x1,y1') 19 | parser.add_option ('--roi-width', 20 | type = 'int', 21 | help = 'Specify the width of ROI in pixels') 22 | parser.add_option ('--nof-points', 23 | type = 'int', default = 512, 24 | help = 'Specify the number of interpolation points.') 25 | parser.add_option_group(get_io_options_group(parser)) 26 | parser.add_option_group(get_microscope_options_group(parser)) 27 | 28 | -------------------------------------------------------------------------------- /iocbio/chaco/base_data_source.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['BaseDataSource'] 3 | 4 | from enthought.traits.api import HasStrictTraits, Bool, Any, Enum, Str, Tuple, Float, Dict 5 | 6 | data_source_kinds = Enum('image_stack', 'image_timeseries', 'image_stack_timeseries', None) 7 | 8 | _data = [None] 9 | 10 | class BaseDataSource(HasStrictTraits): 11 | 12 | has_data = Bool(False) # set True when data is loaded 13 | 14 | description = Str 15 | kind = data_source_kinds 16 | voxel_sizes = Tuple(Float(1.0), Float(1.0), Float(1.0)) 17 | pixel_sizes = Tuple(Float(1.0), Float(1.0)) 18 | 19 | tables = Dict 20 | 21 | is_image_stack = Bool(True) 22 | is_image_timeseries = Bool(False) 23 | is_image_stack_timeseries = Bool(False) 24 | 25 | @property 26 | def data(self): 27 | return _data[0] 28 | 29 | @data.setter 30 | def data(self, data): 31 | _data[0] = data 32 | self.has_data = data is not None 33 | if data is None: 34 | print '%s.data.setter: removing data' % (self.__class__.__name__) 35 | else: 36 | print '%s.data.setter: setting data' % (self.__class__.__name__) 37 | 38 | def _kind_changed (self): 39 | self.is_image_stack = self.kind=='image_stack' 40 | self.is_image_timeseries = self.kind=='image_timeseries' 41 | self.is_image_stack_timeseries = self.kind=='image_stack_timeseries' 42 | -------------------------------------------------------------------------------- /iocbio/io/scripts/ome.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | """ 4 | Converts image files to ome-tiff files. 5 | """ 6 | # Author: Pearu Peterson 7 | # Created: October 2010 8 | 9 | from __future__ import division 10 | import os 11 | 12 | ### START UPDATE SYS.PATH ### 13 | ### END UPDATE SYS.PATH ### 14 | 15 | from iocbio.io.io import get_pathinfo 16 | from iocbio.optparse_gui import OptionParser 17 | from iocbio.io.script_options import set_ome_options 18 | 19 | 20 | 21 | def runner (parser, options, args): 22 | pathinfo = get_pathinfo(options.input_path) 23 | if pathinfo is not None: 24 | pathinfo.omexml(options) 25 | return 26 | config_files = [] 27 | for root, dirs, files in os.walk(options.input_path): 28 | if 'configuration.txt' in files: 29 | config_files.append(os.path.join (root, 'configuration.txt')) 30 | 31 | for config_file in config_files: 32 | pathinfo = get_pathinfo(config_file) 33 | protocol = pathinfo.get_protocol() 34 | if protocol=='rics': 35 | print 'Skipping RICS data in %s' % (config_file) 36 | continue 37 | pathinfo.omexml(options) 38 | 39 | def main (): 40 | parser = OptionParser() 41 | set_ome_options (parser) 42 | if hasattr(parser, 'runner'): 43 | parser.runner = runner 44 | options, args = parser.parse_args() 45 | runner(parser, options, args) 46 | return 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /iocbio/ops/setup.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from os.path import join 4 | 5 | def configuration(parent_package='',top_path=None): 6 | from numpy.distutils.misc_util import Configuration 7 | from numpy.distutils.system_info import get_info, NotFoundError 8 | config = Configuration('ops',parent_package,top_path) 9 | config.add_extension('apply_window_ext', join('src','apply_window_ext.c')) 10 | config.add_extension('local_extrema_ext', join('src','local_extrema_ext.c')) 11 | 12 | config.add_library('fminpack', 13 | sources = [join ('src', 'minpack', '*.f'), 14 | ], 15 | ) 16 | config.add_extension('regress_ext', 17 | sources = [join('src','regress_ext.c'), 18 | ], 19 | ) 20 | config.add_extension('acf_ext', 21 | sources = [join('src','acf_ext.c'), 22 | join('src','acf.c')], 23 | libraries = ['fminpack']) 24 | 25 | 26 | fftw3_info = get_info('fftw3') 27 | 28 | if fftw3_info: 29 | config.add_extension('discrete_gauss_ext', 30 | sources = [join('src','discrete_gauss_ext.c'), 31 | join('src','discrete_gauss.c')], 32 | extra_info = fftw3_info) 33 | else: 34 | print 'FFTW3 not found: skipping discrete_gauss_ext extension' 35 | return config 36 | -------------------------------------------------------------------------------- /iocbio/chaco/fft_viewer_task.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['FFTViewerTask'] 3 | import numpy 4 | 5 | from enthought.traits.api import Button, Any, Bool 6 | from enthought.traits.ui.api import View, VGroup, Item 7 | from .base_viewer_task import BaseViewerTask 8 | from .array_data_source import ArrayDataSource 9 | 10 | class FFTViewerTask(BaseViewerTask): 11 | 12 | 13 | compute_button = Button('Compute Fourier Transform') 14 | inverse = Bool(False) 15 | 16 | traits_view = View ( 17 | Item('compute_button', show_label = False), 18 | Item('inverse'), 19 | ) 20 | 21 | _fft_worker = Any 22 | 23 | def startup(self): 24 | # import fftw routines 25 | from iocbio.ops.fft_tasks import FFTTasks 26 | self._fft_worker = FFTTasks(self.viewer.data.shape) 27 | 28 | def _compute_button_fired(self): 29 | data = self.viewer.data 30 | if not isinstance (data, numpy.ndarray) or 1: 31 | data = data[:] # tiffarray 32 | # compute fft of data 33 | if self.inverse: 34 | fdata = self._fft_worker.ifft(data) 35 | self.viewer.add_data('IFFT', fdata) 36 | else: 37 | fdata = self._fft_worker.fft(data) 38 | self.viewer.add_data('FFT', fdata) 39 | #fdata[0,0,0] = 0 40 | #fdata = numpy.fft.fftshift (fdata) 41 | return 42 | 43 | fdata_source = ArrayDataSource(original_source = self.viewer.data_source, 44 | kind = self.viewer.data_source.kind, 45 | data = fdata) 46 | viewer = self.viewer.__class__(data_source = fdata_source) 47 | self.viewer.add_result(viewer) 48 | viewer.copy_tasks(self.viewer) 49 | -------------------------------------------------------------------------------- /iocbio/chaco/points_task.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['PointsTask'] 3 | 4 | import numpy 5 | 6 | from enthought.traits.api import Button, Any, Array, Float, DelegatesTo, on_trait_change, Dict, Bool, HasStrictTraits, List, Int, Tuple, Instance, on_trait_change 7 | from enthought.traits.ui.api import View, VGroup, Item, ListEditor, TableEditor 8 | from enthought.traits.ui.table_column import ObjectColumn, ExpressionColumn 9 | from enthought.traits.ui.extras.checkbox_column import CheckboxColumn 10 | from enthought.traits.ui.ui_editors.array_view_editor \ 11 | import ArrayViewEditor 12 | from enthought.chaco.api import Plot, ArrayPlotData, OverlayPlotContainer 13 | from enthought.chaco.overlays.api import ContainerOverlay 14 | 15 | from .base_viewer_task import BaseViewerTask 16 | from .array_data_source import ArrayDataSource 17 | from .point import Point 18 | 19 | table_editor = TableEditor( 20 | columns = [ 21 | ExpressionColumn( 22 | expression = '"(%3s, %3s, %3s)->%s" % (object.coordinates+ (object.value,))', 23 | label = '(Z, Y, X)->Value', 24 | ), 25 | CheckboxColumn(name = 'selected'), 26 | ], 27 | selected = 'selected_point', 28 | ) 29 | 30 | 31 | class PointsTask(BaseViewerTask): 32 | 33 | points = DelegatesTo('viewer') 34 | selected_point = Instance(Point) 35 | 36 | traits_view = View (#VGroup( 37 | Item('points', show_label = False, editor=table_editor), 38 | ) 39 | 40 | def startup(self): 41 | pass 42 | 43 | def _selected_point_changed (self): 44 | if self.selected_point is not None: 45 | slice_selector = self.viewer.slice_selector 46 | if slice_selector is not None: 47 | slice_selector.set_slices(*self.selected_point.coordinates) 48 | -------------------------------------------------------------------------------- /iocbio/analysis/src/fperiod.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for fperiod.c. See fperiod.c for documentation. 3 | 4 | Author: Pearu Peterson 5 | Created: March 2011 6 | */ 7 | 8 | #ifndef FPERIOD_H 9 | #define FPERIOD_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif 14 | extern int fperiod_compute_period(double* f, int n, int m, double structure_size, double exp, int method, double* period, double* period2); 15 | //extern int fperiod_compute_period_cache(double* f, int n, int m, double structure_size, double exp, int method, double *r, double* period, double* period2); 16 | extern int fperiod_compute_period_cache(double* f, int n, int m, double structure_size, double exp, int method, double *r, double* period, double* period2); 17 | extern double fperiod_find_cf_maximum(double* f, int n, int m, int lbound, int ubound); 18 | extern double fperiod_find_cf_d2_minimum(double* f, int n, int m, int lbound, int ubound); 19 | extern int fperiod_find_cf_argmax_argmin2der(double* f, int n, int m, int lbound, int ubound, double *argmax, double *argmin2der); 20 | extern double fperiod_cf(double y, double* f, int n, int m); 21 | extern double fperiod_cf_d1(double y, double* f, int n, int m); 22 | extern double fperiod_cf_d2(double y, double* f, int n, int m); 23 | extern void fperiod_subtract_average1(double* f, int n, int fstride, int smoothness, double* r, int rstride); 24 | extern void fperiod_subtract_average(double* f, int n, int m, int structure_size, double* r); 25 | extern void fperiod_mark_crests1(double* f, int n, int fstride, int smoothness, double* r, int rstride); 26 | extern void fperiod_mark_crests(double* f, int n, int m, int structure_size, int q, double* r); 27 | extern void fperiod_subtract_average_2d(double* f, int n, int m, int smoothness, double* r); 28 | 29 | #ifdef __cplusplus 30 | } 31 | #endif 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /iocbio/microscope/snr.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | __all__ = ['estimate_snr'] 4 | 5 | def estimate_snr(image, 6 | noise_type = 'poisson', 7 | use_peak = False): 8 | """ 9 | Estimate signal-to-noise ratio of the image stack. 10 | 11 | Signal-to-noise ratio is defined as follows:: 12 | 13 | SNR = E(image) / (sqrt(E(image - E(image))^2) 14 | 15 | where E(image) is the averaged image. In theory, calculating 16 | averaged image requires multiple acquisitions of the same image. 17 | E(image) can be estimated by smoothing the image with a gaussian. 18 | 19 | Parameters 20 | ---------- 21 | image : `iocbio.io.image_stack.ImageStack` 22 | 23 | noise_type : {'poisson'} 24 | 25 | Notes 26 | ----- 27 | 28 | In the case of Poisson noise the signal-to-noise ratio 29 | is defined as peak signal-to-noise ratio: 30 | 31 | SNR = sqrt(E(max image)). 32 | 33 | """ 34 | if noise_type=='poisson': 35 | if use_peak: 36 | mx = image.max() 37 | else: 38 | data = image 39 | values = [] 40 | for indices in zip (*numpy.where(data==data.max())): 41 | for i0 in range (indices[0]-1,indices[0]+2): 42 | if i0>=data.shape[0]: 43 | i0 -= data.shape[0] 44 | for i1 in range (indices[1]-1,indices[1]+2): 45 | if i1>=data.shape[1]: 46 | i1 -= data.shape[1] 47 | for i2 in range (indices[2]-1,indices[2]+2): 48 | if i2>=data.shape[2]: 49 | i2 -= data.shape[2] 50 | values.append (data[i0,i1,i2]) 51 | mx = numpy.mean(values) 52 | snr = numpy.sqrt(mx) 53 | else: 54 | raise NotImplementedError(`noise_type`) 55 | return snr 56 | 57 | -------------------------------------------------------------------------------- /iocbio/kinetics/demo_model.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | See 4 | http://code.google.com/p/iocbio/wiki/OxygenIsotopeEquationGenerator 5 | 6 | 7 | """ 8 | 9 | from builder import IsotopeModel 10 | 11 | class DemoModel(IsotopeModel): 12 | system_string = ''' 13 | # See IsotopeModel.parse_system_string.__doc__ for syntax specifications. 14 | # 15 | # Definitions of species labeling 16 | # = [] 17 | # 18 | A = A[**] 19 | B = B[*] 20 | C = C[**_*] 21 | 22 | # 23 | # Definitions of reactions 24 | # : (<=|=>|<=>) 25 | # 26 | F1 : A + B <=> C 27 | ''' 28 | def check_reaction(self, reaction): 29 | """ Validate reaction. 30 | 31 | For documentation, read the comments below. Also see 32 | IsotopeModel.check_reaction.__doc__ for more details. 33 | """ 34 | # Create label matcher object 35 | l = self.labels(reaction) 36 | 37 | # Note that the label matcher object is special Python 38 | # dictionary object that items can be accessed via attributes. 39 | # Keys are the names of species and values are labeling 40 | # indices. 41 | 42 | # First, handle transport reactions. Usage of `transport=True` 43 | # improves performance but, in general, it is not required. 44 | if l.match('Ai => A', transport=True): return l.Ai==l.A 45 | if l.match('C => Co', transport=True): return l.C==l.Co 46 | if l.match('A+B <=> C'): 47 | t1,t2 = l.C.split ('_') 48 | return l.A==t1 and l.B==t2 49 | # Unknown reaction, raise an exception 50 | return IsotopeModel.check_reaction(self, reaction) 51 | 52 | 53 | if __name__ == '__main__': 54 | 55 | # Create a model instance. 56 | model = DemoModel() 57 | 58 | # Demonstrate model equations 59 | model.demo() 60 | 61 | # Generate C code with kinetic equations 62 | #model.compile_ccode(debug=False) 63 | -------------------------------------------------------------------------------- /iocbio/microscope/tutorial/mk_figures.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | iocbio.show -i cell2_mitogreen_px25.tif --view-3d=c,c,c --no-gui -o cell_original.png 4 | convert -trim cell_original.png cell_original.png 5 | 6 | iocbio.show -i psf4_505_pxt50.tif --view-3d=25,480,550 --no-gui -o microspheres.png 7 | convert -trim microspheres.png microspheres.png 8 | 9 | #iocbio.estimate_psf -i psf4_505_pxt50.tif --save-intermediate-results -o psf_airy_478_water.tif --no-gui 10 | 11 | iocbio.show -i psf_airy_478_water.tif --view-3d=14,c,c --no-gui -o psf.png 12 | convert -trim psf.png psf.png 13 | 14 | #iocbio.deconvolve -i cell2_mitogreen_px25.tif -k psf_airy_478_water.tif -o result.tif \ 15 | # --rltv-estimate-lambda --rltv-lambda-lsq-coeff=0 --max-nof-iterations=20 \ 16 | # --no-degrade-input --save-intermediate-results --float-type=single --no-gui 17 | 18 | iocbio.rowfile_plot -i result.tif.iocbio.deconvolve/deconvolve_data.txt --x-keys=count --y-keys=lambda_lsq,mse,tau1 --no-gui -o deconvolve_result_params.png 19 | convert -trim deconvolve_result_params.png deconvolve_result_params.png 20 | 21 | iocbio.show -i result.tif.iocbio.deconvolve/result_7.tif --view-3d=c,c,c --no-gui -o deconvolve_result_7.png 22 | convert -trim deconvolve_result_7.png deconvolve_result_7.png 23 | 24 | #iocbio.deconvolve -i cell2_mitogreen_px25.tif -k psf_airy_478_water.tif -o result2.tif \ 25 | # --no-rltv-estimate-lambda --rltv-lambda-lsq-coeff=0 --max-nof-iterations=20 \ 26 | # --no-degrade-input --save-intermediate-results --float-type=single --rltv-lambda=6.4 \ 27 | # --rltv-compute-lambda-lsq --no-gui 28 | 29 | iocbio.show -i result2.tif.iocbio.deconvolve/result_8.tif --view-3d=c,c,c --no-gui -o deconvolve_result2_8.png 30 | convert -trim deconvolve_result2_8.png deconvolve_result2_8.png 31 | 32 | iocbio.rowfile_plot -i result2.tif.iocbio.deconvolve/deconvolve_data.txt --x-keys=count --y-keys=lambda_lsq,mse,tau1 --no-gui -o deconvolve_result2_params.png 33 | convert -trim deconvolve_result2_params.png deconvolve_result2_params.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | The IOCBio project provides open-source software that is developed in [Laboratory of Systems Biology](http://sysbio.ioc.ee) at [Institute of Cybernetics](http://www.ioc.ee). The project is created to publish the software, this includes distributing the source codes, continuing software development, supporting users as well as attracting users to contribute to the software. 2 | 3 | Currently, the project provides access to the following software: 4 | 5 | * [IOCBioMicroscope](IOCBioMicroscope.md) - a Python package for deconvolving 3D microscope images, see [DeconvolutionTutorial](DeconvolutionTutorial.md) for an example, see also [PyLibDeconv](http://code.google.com/p/pylibdeconv). 6 | * [IOCBioStrathKelvin](IOCBioStrathKelvin.md) - a wrapper to [Strathkelvin Instruments](http://www.strathkelvin.com/) 929 Oxygen System software. 7 | * [IOCBioSarcomereLength](IOCBioSarcomereLength.md) - a C library and Python package for estimating fundamental period of a sequence with an application to determining sarcomere length from microscopy images of cardiomyocytes. 8 | * [IOCBioOxygenIsotopeEquationGenerator](IOCBioOxygenIsotopeEquationGenerator.md) - a Python module for generation of mass isotopologue equations. 9 | 10 | which are parts of the IOCBio package. See [IOCBio Documentation](http://sysbio.ioc.ee/download/software/iocbio/index.html) and [List of documentations with examples](http://sysbio.ioc.ee/download/software/iocbio/generated/examples.html) for more details. 11 | 12 | In addition, we have created several independent software projects that we use together with the IOCBio project: 13 | * [PyLibNIDAQmx](http://code.google.com/p/pylibnidaqmx/) - a Python wrapper to libnidaqmx library 14 | * [PyLibTiff](http://code.google.com/p/pylibtiff/) - a Python TIFF library 15 | * [SympyCore](http://code.google.com/p/sympycore/) - an efficient pure Python Computer Algebra System (originally supported by Simula) 16 | * [Simple RPC C++](http://code.google.com/p/simple-rpc-cpp) - a simple RPC wrapper generator to C/C++ functions -------------------------------------------------------------------------------- /iocbio/microscope/dv.py: -------------------------------------------------------------------------------- 1 | """Provides dv function. 2 | 3 | Module content 4 | -------------- 5 | """ 6 | 7 | __all__ = ['dv'] 8 | 9 | from numpy import * 10 | 11 | def dx(f,h): 12 | """ 13 | f - 3D array 14 | h = [hx, hy, hz] 15 | """ 16 | shape = list(f.shape) 17 | shape[0] += 1 18 | result = zeros(shape) 19 | result[-1] = f[-1] 20 | result[0] = -f[0] 21 | result[:-1] += f 22 | result[1:] -= f 23 | result /= h[0] 24 | #return dx+ , dx- 25 | return result[1:], result[:-1] 26 | 27 | def dy(f,h): 28 | shape = list(f.shape) 29 | shape[1] += 1 30 | result = zeros(shape) 31 | result[:,-1] = f[:,-1] 32 | result[:,0] = -f[:,0] 33 | result[:,:-1] += f 34 | result[:,1:] -= f 35 | result /= h[1] 36 | #return dy+ , dy- 37 | return result[:,1:], result[:,:-1] 38 | 39 | def dz(f,h): 40 | shape = list(f.shape) 41 | shape[2] += 1 42 | result = zeros(shape) 43 | result[:,:,-1] = f[:,:,-1] 44 | result[:,:,0] = -f[:,:,0] 45 | result[:,:,:-1] += f 46 | result[:,:,1:] -= f 47 | result /= h[2] 48 | #return dz+ , dz- 49 | return result[:,:,1:], result[:,:,:-1] 50 | 51 | def m(a, b): 52 | return 0.5*(sign(a) + sign(b)) * minimum(absolute(a), absolute(b)) 53 | 54 | def dv(f, h): 55 | """Computes ``div(grad(f)/|grad(f)|)``. 56 | 57 | Parameters 58 | ---------- 59 | f : :numpy:`ndarray` 60 | h : 3-tuple 61 | """ 62 | fxp, fxm = dx(f, h) 63 | fyp, fym = dy(f, h) 64 | fzp, fzm = dz(f, h) 65 | mx = m(fxp, fxm) 66 | my = m(fyp, fym) 67 | mz = m(fzp, fzm) 68 | mx2 = mx ** 2 69 | my2 = my ** 2 70 | mz2 = mz ** 2 71 | fx2 = fxp**2 72 | fy2 = fyp**2 73 | fz2 = fzp**2 74 | sx = sqrt(fx2 + my2 + mz2) 75 | sy = sqrt(fy2 + mx2 + mz2) 76 | sz = sqrt(fz2 + my2 + mx2) 77 | fsx = fxp/sx 78 | fsy = fyp/sy 79 | fsz = fzp/sz 80 | fx = dx(where(sx==0, 0, fsx), h)[1] 81 | fy = dy(where(sy==0, 0, fsy), h)[1] 82 | fz = dz(where(sz==0, 0, fsz), h)[1] 83 | return fx + fy + fz 84 | -------------------------------------------------------------------------------- /installer/README.txt: -------------------------------------------------------------------------------- 1 | 2 | Installer tools 3 | =============== 4 | 5 | Overview 6 | -------- 7 | 8 | This directory contains Python modules for building a installer for 9 | iocbio software and all of its dependencies (Python, Numpy, Scipy, 10 | Matplotlib, Wx, etc). The installer is designed for Windows users to 11 | ease the iocbio software installation process. However, the model of 12 | installer is general and it should be easy to support other OS-s as 13 | well. 14 | 15 | The installer consists of a Python script that is turned to an EXE 16 | file using the pyinstaller program (http://www.pyinstaller.org/). The 17 | installer script depends on Python (obviously) and wx 18 | (http://www.wxpython.org/) that is used for GUI. The installer can be 19 | built under Wine (http://www.winehq.org/) using the Mingw 20 | (http://www.mingw.org/) tools. 21 | 22 | Quick reference 23 | --------------- 24 | 25 | To build iocbio installer, run 26 | 27 | ./wineit.sh make_iocbio_installer.bat 28 | 29 | that will create a file iocbio_installer_py26.exe, for 30 | instance. Before running the script, you have to install wine. The 31 | make_iocbio_installer.bat will download and install other components 32 | automatically. So, be ready to step through installer wizards of 33 | Python, wx, and pyinstaller programs. Note that the iocbio installer 34 | file depends on the Python version. 35 | 36 | To build iocbio installer for other Python versions, edit the header 37 | of the make_iocbio_installer.sh file accordingly. 38 | 39 | To test the iocbio installer within wine, run 40 | 41 | ./wineit2.sh iocbio_installer_py26.exe 42 | 43 | The installer can be also tested under Linux environment by running 44 | 45 | python iocbio_installer.py 46 | 47 | that will fireup a GUI window and you can step through all the 48 | software components. 49 | 50 | The ultimate installer test should be carried out under Windows. 51 | 52 | Notes 53 | ----- 54 | 55 | For using mingw-light, one must run 56 | 57 | make_iocbio_mingw.sh 58 | 59 | and copy the resulting file (say, mingw-20110802-light.zip) to 60 | 61 | /net/cens/home/www/sysbio/download/software/binaries/latest 62 | -------------------------------------------------------------------------------- /iocbio/fperiod/src/iocbio_ipwf_manual.c: -------------------------------------------------------------------------------- 1 | void iocbio_ipwf_e11_compute_coeffs_diff1(int j, double *fm, int n, int m, double* a0, double* a1, double* a2, double* a3) 2 | { 3 | #ifdef F 4 | #undef F 5 | #endif 6 | #define F(I) ((I)<0?((1-(I))*f[0]+(I)*f[1]):((I)>=n?(((I)-n+2)*f[n-1]-((I)-n+1)*f[n-2]):f[(I)])) 7 | 8 | /* diff(int((f1(x)-f1(x+y))*(f2(x)-f2(x+y)), x=0..L-y), y, order=1) = sum(a_k*r^k, k=0..3) where y=j+r 9 | f1(x)=sum([0<=s<1]*((-(F(i)) + (F(i+1)))*s + (F(i))), i=0..N-1) where s=x-i 10 | f2(x)=sum([0<=s<1]*((-(F(i)) + (F(i+1)))*s + (F(i))), i=0..N-1) where s=x-i */ 11 | 12 | int p, i; 13 | int k = n - 3 - j; 14 | double *f = fm; 15 | //printf("void iocbio_ipwf_e11_compute_coeffs_diff1(int j, double *fm, int n, int m, double* a0, double* a1, double* a2, double* a3)\n"); 16 | double b0 = 0.0; 17 | double b1 = 0.0; 18 | double b2 = 0.0; 19 | double b3 = 0.0; 20 | double f_ipj, f_ip2pj, f_ip1pj, f_m1mjpn, f_i, f_m2mjpn, f_m2pn, f_ip1, f_m1pn; 21 | if (j>=0 && j<=n-2) 22 | { 23 | for(p=0; p=2: 50 | last_lines[j].pop(0) 51 | lines[j].append(numpy.mean (last_lines[j])) 52 | time_lst.append (i) 53 | 54 | import matplotlib.pyplot as plt 55 | for line in lines: 56 | plt.plot (time_lst, line) 57 | 58 | plt.legend (labels) 59 | plt.show () 60 | 61 | #ImageStack(stack.images, pathinfo=stack.pathinfo).save('marked.tif') 62 | 63 | 64 | def main (): 65 | parser = OptionParser() 66 | set_sarcomere_length_options (parser) 67 | if hasattr(parser, 'runner'): 68 | parser.runner = runner 69 | options, args = parser.parse_args() 70 | runner(parser, options, args) 71 | 72 | if __name__ == '__main__': 73 | main() 74 | -------------------------------------------------------------------------------- /iocbio/ops/convolution.py: -------------------------------------------------------------------------------- 1 | """Provides convolve function. 2 | 3 | Example 4 | ------- 5 | 6 | The following example illustrates how to convolve data with a kernel:: 7 | 8 | from numpy import * 9 | from scipy.stats import poisson 10 | from iocbio.ops import convolve 11 | kernel = array([0,1,2,2,2,1,0]) 12 | x = arange(0,2*pi,0.1) 13 | data = 50+7*sin(x)+5*sin(2*x) 14 | data_with_noise = poisson.rvs(data) 15 | data_convolved = convolve(kernel, data_with_noise) 16 | 17 | .. image:: ../_static/convolve_1d.png 18 | :width: 60% 19 | 20 | """ 21 | 22 | from __future__ import division 23 | 24 | __all__ = ['convolve'] 25 | 26 | from scipy import fftpack 27 | from . import fft_tasks 28 | from .. import utils 29 | 30 | def convolve(kernel, data, kernel_background = None, options = None): 31 | """ 32 | Convolve kernel and data using FFT algorithm. 33 | 34 | Parameters 35 | ---------- 36 | kernel : numpy.ndarray 37 | Specify convolution kernel. The center of the kernel is assumed 38 | to be in the middle of kernel array. 39 | data : numpy.ndarray 40 | Specify convolution data. 41 | kernel_background : {int, float, None} 42 | If kernel has smaller size than data then kernel will be expanded 43 | with kernel_background value. By default, kernel_background value 44 | is ``kernel.min()``. 45 | options : {`iocbio.utils.Options`, None} 46 | options.float_type defines FFT algorithms floating point type: 47 | ``'float'`` (32-bit float) or ``'double'`` (64-bit float). 48 | 49 | Returns 50 | ------- 51 | result : numpy.ndarray 52 | 53 | See also 54 | -------- 55 | :mod:`iocbio.ops.convolution` 56 | """ 57 | if options is None: 58 | options = utils.Options() 59 | else: 60 | options = utils.Options(options) 61 | float_type = options.get (float_type='double') 62 | task = fft_tasks.FFTTasks(data.shape, float_type, options=options) 63 | if kernel.shape != data.shape: 64 | # assuming that kernel has smaller size than data 65 | kernel = utils.expand_to_shape(kernel, data.shape, float_type, background=kernel_background) 66 | 67 | kernel = fftpack.fftshift(kernel) 68 | 69 | kernel = kernel / kernel.sum() 70 | 71 | task.set_convolve_kernel(kernel) 72 | result = task.convolve(data) 73 | 74 | return result 75 | -------------------------------------------------------------------------------- /iocbio/chaco/scale_space_task.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['FFTViewerTask'] 3 | 4 | import numpy 5 | 6 | from enthought.traits.api import Button, Any, Array, Float 7 | from enthought.traits.ui.api import View, VGroup, Item 8 | from enthought.traits.ui.ui_editors.array_view_editor \ 9 | import ArrayViewEditor 10 | from enthought.chaco.api import Plot, ArrayPlotData, OverlayPlotContainer 11 | from enthought.chaco.overlays.api import ContainerOverlay 12 | 13 | from .base_viewer_task import BaseViewerTask 14 | from .array_data_source import ArrayDataSource 15 | 16 | 17 | class ScaleSpaceTask(BaseViewerTask): 18 | 19 | compute_button = Button('Compute Scale Space Data') 20 | 21 | scale = Float(0.0) 22 | results = Array 23 | 24 | traits_view = View (VGroup( 25 | Item('compute_button', show_label = False), 26 | Item('scale'), 27 | Item('results', editor = ArrayViewEditor (titles=['value', 'z', 'y', 'x'], 28 | format = '%.1f', font='Arial 8')) 29 | )) 30 | 31 | _fft_worker = Any 32 | 33 | def startup(self): 34 | # import fftw routines 35 | #from iocbio.ops.fft_tasks import FFTTasks 36 | #self._fft_worker = FFTTasks(self.viewer.data.shape) 37 | pass 38 | 39 | def _results_default (self): 40 | return numpy.array([[0,0,0,0]]) 41 | 42 | def _compute_button_fired(self): 43 | data = self.viewer.data 44 | if not isinstance (data, numpy.ndarray): 45 | data = data[:] # tiffarray 46 | # compute fft of data 47 | 48 | from iocbio.ops.local_extrema_ext import local_maxima 49 | l = local_maxima(data, 0) 50 | print len (l) 51 | l.sort(reverse=True) 52 | self.results = numpy.array(l) 53 | self.viewer.set_point_data(l) 54 | return 55 | 56 | fdata = self._fft_worker.fft(data) 57 | fdata[0,0,0] = 0 58 | fdata = numpy.fft.fftshift (fdata) 59 | fdata_source = ArrayDataSource(original_source = self.viewer.data_source, 60 | kind = self.viewer.data_source.kind, 61 | data = fdata) 62 | viewer = self.viewer.__class__(data_source = fdata_source) 63 | self.viewer.add_result(viewer) 64 | viewer.copy_tasks(self.viewer) 65 | 66 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009-2010, Laboratory of Systems Biology, Institute of 2 | Cybernetics at Tallinn University of Technology. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | 11 | * Redistributions in binary form must reproduce the above 12 | copyright notice, this list of conditions and the following 13 | disclaimer in the documentation and/or other materials provided 14 | with the distribution. 15 | 16 | * Neither the name of the Laboratory of Systems Biology nor the 17 | names of its contributors may be used to endorse or promote 18 | products derived from this software without specific prior 19 | written permission. 20 | 21 | THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDER AND CONTRIBUTORS ''AS 22 | IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 23 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 24 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER 25 | OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 26 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 27 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 28 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 29 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 30 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | 33 | In addition to the terms of the license, we ask to acknowledge the use 34 | of packages in scientific articles by citing the corresponding papers: 35 | 36 | IOCBio Microscope: 37 | 38 | * Laasmaa M, Vendelin M, Peterson P (2011). Application of 39 | regularized Richardson-Lucy algorithm for deconvolution of 40 | confocal microscopy images. J. Microscopy. In press. 41 | http://onlinelibrary.wiley.com/doi/10.1111/j.1365-2818.2011.03486.x/abstract 42 | 43 | IOCBio StrathKelvin: 44 | 45 | * Pearu Peterson (2010). IOCBio.StrathKelvin -- a wrapper to 46 | Strathkelvin 929 Oxygen System software. 47 | URL: http://code.google.com/p/iocbio/. 48 | -------------------------------------------------------------------------------- /iocbio/chaco/tiff_file_info.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ['TiffFileInfo'] 3 | 4 | import os 5 | import glob 6 | from enthought.traits.api import Property, Enum, cached_property, Bool 7 | from enthought.traits.ui.api import View, Tabbed, Item, VGroup 8 | from enthought.traits.ui.file_dialog import MFileDialogModel 9 | from libtiff import TIFFfile 10 | from .base_data_source import data_source_kinds 11 | 12 | 13 | class TiffFileInfo(MFileDialogModel): 14 | 15 | description = Property(depends_on = 'file_name') 16 | #preview = Property (depends_on = 'file_name') 17 | #kind = data_source_kinds 18 | is_ok = Bool (False) 19 | 20 | traits_view = View(VGroup( 21 | #Tabbed( 22 | Item ('description', style='readonly', show_label = False, resizable=True), 23 | #Item ('preview', style='readonly', show_label = False, resizable=True), 24 | # scrollable=True, 25 | # ), 26 | #Item('kind', label='Open as', style='custom'), 27 | ), 28 | resizable=True) 29 | 30 | @cached_property 31 | def _get_description(self): 32 | self.is_ok = False 33 | if not os.path.isfile (self.file_name): 34 | if os.path.exists (self.file_name): 35 | if os.path.isdir (self.file_name): 36 | files = [] 37 | for ext in ['tif', 'lsm']: 38 | files += glob.glob(self.file_name+'/*.'+ext) 39 | n = len (self.file_name) 40 | files = sorted([f[n+1:] for f in files]) 41 | return 'Directory contains:\n%s' % ('\n'.join (files)) 42 | return 'not a file' 43 | return 'file does not exists' 44 | if os.path.basename(self.file_name)=='configuration.txt': 45 | return unicode(open(self.file_name).read(), errors='ignore') 46 | raise NotImplementedError('opening configuration.txt data') 47 | try: 48 | tiff = TIFFfile(self.file_name, verbose=True) 49 | except ValueError, msg: 50 | return 'not a TIFF file\n%s' % (msg) 51 | self.is_ok = True 52 | try: 53 | r = tiff.get_info() 54 | except Exception, msg: 55 | r = 'failed to get TIFF info: %s' % (msg) 56 | #TODO: set self.preview object here 57 | tiff.close () 58 | return unicode(r, errors='ignore') 59 | -------------------------------------------------------------------------------- /iocbio/ops/scripts/convolve.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | """ 4 | """ 5 | # Author: Pearu Peterson 6 | # Created: September 2009 7 | 8 | from __future__ import division 9 | import os 10 | 11 | ### START UPDATE SYS.PATH ### 12 | ### END UPDATE SYS.PATH ### 13 | 14 | import numpy 15 | from iocbio.optparse_gui import OptionParser 16 | from iocbio.io import ImageStack 17 | from iocbio.ops import convolve 18 | from iocbio.io.io import fix_path 19 | from iocbio.ops.script_options import set_convolve_options 20 | 21 | def runner(parser, options, args): 22 | 23 | if not hasattr(parser, 'runner'): 24 | options.output_path = None 25 | 26 | if args: 27 | raise NotImplementedError (`args`) 28 | if len (args)==1: 29 | if options.input_path: 30 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 31 | options.input_path = args[0] 32 | elif len(args)==2: 33 | if options.input_path: 34 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 35 | options.input_path = args[0] 36 | options.output_path = args[1] 37 | else: 38 | parser.error("incorrect number of arguments (expected upto 2 but got %s)" % (len(args))) 39 | 40 | options.kernel_path = fix_path(options.kernel_path) 41 | options.input_path = fix_path(options.input_path) 42 | 43 | if options.output_path is None: 44 | b,e = os.path.splitext(options.input_path) 45 | suffix = '_convolved' % () 46 | options.output_path = b + suffix + (e or '.tif') 47 | 48 | options.output_path = fix_path(options.output_path) 49 | 50 | kernel = ImageStack.load(options.kernel_path, options=options) 51 | stack = ImageStack.load(options.input_path, options=options) 52 | 53 | result = convolve (kernel.images, stack.images, options=options) 54 | 55 | if 1: 56 | print 'Saving result to',options.output_path 57 | ImageStack(result, stack.pathinfo).save(options.output_path) 58 | 59 | def main (): 60 | parser = OptionParser() 61 | set_convolve_options (parser) 62 | if hasattr(parser, 'runner'): 63 | parser.runner = runner 64 | options, args = parser.parse_args() 65 | runner(parser, options, args) 66 | 67 | if __name__ == '__main__': 68 | main() 69 | -------------------------------------------------------------------------------- /iocbio/ops/src/acf.h: -------------------------------------------------------------------------------- 1 | /* Analytic autocorrelation functions. 2 | 3 | This code provides the following functions: 4 | 5 | double acf_evaluate(double* f, int n, double y, InterpolationMethod mth) 6 | double acf_maximum_point(double* f, int n, int start_j, InterpolationMethod mth) 7 | double acf_sine_fit(double* f, int n, int start_j, ACFInterpolationMethod mth) 8 | 9 | * acf_evaluate computes the value of an analytic autocorrelation 10 | function ACF(f)(y) of a piecewice polynomial function f(x). The 11 | parameters to acf_evaluate function are as follows: 12 | 13 | f - a pointer to function values f(i) at node points i=0,...,n-1 14 | n - the number of node points 15 | y - the argument to the ACF 16 | mth - interpolation method for finding f values between node points. 17 | 18 | Currently the impelented interpolation methods are Constant, Linear, 19 | and CatmullRom spline. 20 | 21 | Note that f(i)=0, i<0 or i>=n, is assumed. 22 | 23 | * acf_maximum_point returns the point after start_j where 24 | ACF(f)(y) obtains its maximum. start_j should be a floor of 25 | f(x) period for optimal computation. 26 | 27 | * acf_sine_fit returns sine fit parameter omega such that 28 | ACF(f)(y) = a * cos(omega*j)*(n-j)/n 29 | where a = ACF(f)(0). Note that acf_sine_fit uses 30 | acf_maximum_point as initial guess for omega = 2*pi/max_point, 31 | hence the start_j argument. 32 | 33 | Auhtor: Pearu Peterson 34 | Created: September 2010 35 | */ 36 | 37 | #ifndef ACF_H_INCLUDE 38 | #define ACF_H_INCLUDE 39 | 40 | #ifdef __cplusplus 41 | extern "C" { 42 | #endif 43 | 44 | typedef enum {\ 45 | ACFInterpolationConstant=0, 46 | ACFInterpolationLinear=1, 47 | ACFInterpolationCatmullRom=2, 48 | ACFInterpolationConstantWithSizeReduction=10, 49 | ACFInterpolationLinearWithSizeReduction=11, 50 | ACFInterpolationCatmullRomWithSizeReduction=12, 51 | ACFUnspecified=999} ACFInterpolationMethod; 52 | 53 | extern double acf_evaluate(double* f, int n, int rows, double y, ACFInterpolationMethod mth); 54 | extern double acf_maximum_point(double* f, int n, int rows, int start_j, ACFInterpolationMethod mth); 55 | #ifndef DISABLE_SINFIT 56 | extern double acf_sine_fit(double* f, int n, int rows, int start_j, ACFInterpolationMethod mth); 57 | #endif 58 | extern double acf_sine_power_spectrum(double* f, int n, int rows, double omega, ACFInterpolationMethod mth); 59 | 60 | #ifdef __cplusplus 61 | } 62 | #endif 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /iocbio/ops/window.py: -------------------------------------------------------------------------------- 1 | """Provides apply_window function. 2 | 3 | The :func:`apply_window` function can be used to multiply 3D images 4 | with a window that suppresses the boundaries to zero and leaves the 5 | inside image values constant. 6 | 7 | Multiplication by such a window provides a robust way to periodize 3D 8 | images and so minimize `Gibbs phenomenon 9 | `_ for tools using 10 | Fourier transform images. 11 | 12 | Example 13 | ------- 14 | 15 | The following example illustrates the result of applying window 16 | to a constant data=1, that is, the result will be window function 17 | itself:: 18 | 19 | 20 | from numpy import * 21 | from iocbio.ops import apply_window 22 | data = ones (50) 23 | window0 = apply_window(data, (1/20., ), smoothness=0, background=0.2) 24 | window1 = apply_window(data, (1/20., ), smoothness=1, background=0) 25 | 26 | .. image:: ../_static/apply_window_1d.png 27 | :width: 60% 28 | 29 | """ 30 | 31 | __all__ = ['apply_window'] 32 | 33 | try: 34 | from .apply_window_ext import apply_window_inplace 35 | except ImportError, msg: 36 | print msg 37 | 38 | def apply_window(data, scales, smoothness=1, 39 | background=0.0, inplace=False): 40 | """ Multiply data with window function. 41 | 42 | Each value in data will be multiplied with ``w=w[0]*w[1]*..`` 43 | where ``w[k] = f(scales[k] * min(index[k], 44 | shape[k]-index[k]-1))``, ``k=0,1,..``, and ``f(x)`` is 45 | ``2*smoothness+1`` times differentiable function such that 46 | ``f(x)=1`` if ``x>1`` and ``f(0)=0``. 47 | 48 | Parameters 49 | ---------- 50 | data : numpy.ndarray 51 | scales : tuple 52 | Scaling factors. ``1/scales[i]`` defines the width of 53 | non-constant window. 54 | 55 | smoothness : int 56 | Specifies smoothness of the window so that it will be 57 | ``2*smoothness+1`` times continuously differentiable. 58 | 59 | background : float 60 | Specifies the background level of data. When non-zero, 61 | the result of apply window is ``(data - background) * window + background``. 62 | 63 | inplace : bool 64 | When True then multiplication is performed in-situ. 65 | 66 | Returns 67 | ------- 68 | data : numpy.ndarray 69 | 70 | See also 71 | -------- 72 | :mod:`iocbio.ops.window` 73 | """ 74 | if not inplace: 75 | data = data.copy() 76 | apply_window_inplace(data, scales, smoothness, background) 77 | return data 78 | -------------------------------------------------------------------------------- /iocbio/ops/scripts/apply_noise.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | # Author: Pearu Peterson 4 | # Created: September 2009 5 | 6 | from __future__ import division 7 | import os 8 | 9 | ### START UPDATE SYS.PATH ### 10 | ### END UPDATE SYS.PATH ### 11 | 12 | import numpy 13 | from iocbio.optparse_gui import OptionParser 14 | from iocbio.io import ImageStack 15 | from iocbio.io.io import fix_path 16 | from iocbio.ops.script_options import set_apply_noise_options 17 | from scipy.stats import poisson 18 | 19 | def runner(parser, options, args): 20 | 21 | verbose = options.verbose if options.verbose is not None else True 22 | 23 | if not hasattr(parser, 'runner'): 24 | options.output_path = None 25 | 26 | if args: 27 | if len (args)==1: 28 | if options.input_path: 29 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 30 | options.input_path = args[0] 31 | elif len(args)==2: 32 | if options.input_path: 33 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 34 | options.input_path = args[0] 35 | if options.output_path: 36 | print >> sys.stderr, "WARNING: overwriting output path %r with %r" % (options.output_path, args[1]) 37 | options.output_path = args[1] 38 | else: 39 | parser.error("incorrect number of arguments (expected upto 2 but got %s)" % (len(args))) 40 | 41 | options.input_path = fix_path(options.input_path) 42 | 43 | if options.output_path is None: 44 | b,e = os.path.splitext(options.input_path) 45 | suffix = '_noised_%s' % (options.noise_type) 46 | options.output_path = b + suffix + (e or '.tif') 47 | 48 | options.output_path = fix_path(options.output_path) 49 | stack = ImageStack.load(options.input_path, options=options) 50 | 51 | if options.noise_type == 'poisson': 52 | new_images = stack.images.copy() 53 | new_images[new_images <= 0] = 1 54 | new_images = poisson.rvs(new_images) 55 | else: 56 | raise NotImplementedError(`options.noise_type`) 57 | if verbose: 58 | print 'Saving result to',options.output_path 59 | ImageStack(new_images, stack.pathinfo).save(options.output_path) 60 | 61 | 62 | def main (): 63 | parser = OptionParser() 64 | set_apply_noise_options (parser) 65 | if hasattr(parser, 'runner'): 66 | parser.runner = runner 67 | options, args = parser.parse_args() 68 | runner(parser, options, args) 69 | return 70 | 71 | if __name__ == '__main__': 72 | main() 73 | -------------------------------------------------------------------------------- /iocbio/microscope/scripts/estimate_psf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | """ 4 | Front end script for deconvolving microscope images. 5 | Execute this script with --help for usage information. 6 | """ 7 | # Author: Pearu Peterson 8 | # Created: May 2009 9 | 10 | import os 11 | import sys 12 | 13 | ### START UPDATE SYS.PATH ### 14 | ### END UPDATE SYS.PATH ### 15 | 16 | from iocbio.optparse_gui import OptionParser 17 | from iocbio.io.io import fix_path 18 | from iocbio.microscope import spots_to_psf 19 | from iocbio import utils 20 | from iocbio.microscope.script_options import set_estimate_psf_options 21 | 22 | def runner(parser, options, args): 23 | 24 | if not hasattr(parser, 'runner'): 25 | options.output_path = None 26 | 27 | if args: 28 | if len(args)==1: 29 | if options.input_path: 30 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 31 | options.input_path = args[0] 32 | elif len(args)==2: 33 | if options.input_path: 34 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 35 | options.input_path = args[0] 36 | if options.output_path: 37 | print >> sys.stderr, "WARNING: overwriting output path %r with %r" % (options.output_path, args[1]) 38 | options.output_path = args[1] 39 | else: 40 | parser.error("incorrect number of arguments (expected upto 2 but got %s)" % (len(args))) 41 | 42 | options.input_path = fix_path(options.input_path) 43 | 44 | if options.output_path is None: 45 | b,e = os.path.splitext(options.input_path) 46 | if options.cluster_background_level: 47 | suffix = '_psf_cbl%s_fz%s' % (options.cluster_background_level, options.psf_field_size) 48 | else: 49 | suffix = '_psf_fz%s' % (options.psf_field_size,) 50 | options.output_path = b + suffix + (e or '.tif') 51 | 52 | psf_dir = utils.get_path_dir(options.output_path, 'iocbio.estimate_psf') 53 | try: 54 | psf = spots_to_psf(options.input_path, psf_dir, options) 55 | except KeyboardInterrupt: 56 | print 'RECEIVED CTRL-C' 57 | return 58 | 59 | options.output_path = fix_path(options.output_path) 60 | if options.output_path is not None: 61 | print 'Saving results to %r' % (options.output_path) 62 | psf.save (options.output_path) 63 | 64 | 65 | def main(): 66 | parser = OptionParser() 67 | set_estimate_psf_options (parser) 68 | 69 | if hasattr(parser, 'runner'): 70 | parser.runner = runner 71 | 72 | options, args = parser.parse_args() 73 | 74 | runner(parser, options, args) 75 | return 76 | 77 | if __name__ == "__main__": 78 | main() 79 | -------------------------------------------------------------------------------- /iocbio/kinetics/DemoModel_mass.c: -------------------------------------------------------------------------------- 1 | /* See http://code.google.com/p/iocbio/wiki/OxygenIsotopeEquationGenerator */ 2 | /* 3 | A = A[**] 4 | B = B[*] 5 | C = C[**_*] 6 | F1 : A + B <=> C 7 | */ 8 | 9 | /* 10 | 11 | c_equations calculates the change in labeled species given an input of 12 | steady fluxes, constant pool sizes, and the current 13 | labeling state of all species. Typically this function is 14 | used inside of a differential equation solver. 15 | 16 | Input arguments: 17 | pool_list: Pool sizes for all metabolic species in the model. 18 | 19 | flux_list: Steady fluxes for all reactions in the model. If 20 | these are not steady your solver will complain ;) 21 | 22 | solver_time: The time provided by the differential equation 23 | solver. This can be used to change the default 24 | labeling step change into a function of time. 25 | 26 | input_list: This is a list of the initial labeling state of all 27 | mass isotopologue species. The order is defined in 28 | the code below. An initial list is provided by the 29 | user, and intermediate labeling states are provided 30 | by the differential equation solver. 31 | 32 | Output arguments: 33 | 34 | out: The time derivative of labeling state of all 35 | species. The order of this list is the same as the 36 | input_list. 37 | */ 38 | 39 | void c_equations(double* pool_list, double* flux_list, double* solver_time, double* input_list, double* out) 40 | { 41 | double A_0 = input_list[0] ; 42 | double A_1 = input_list[1] ; 43 | double A_2 = input_list[2] ; 44 | double B_0 = input_list[3] ; 45 | double B_1 = input_list[4] ; 46 | double C_0_0 = input_list[5] ; 47 | double C_0_1 = input_list[6] ; 48 | double C_1_0 = input_list[7] ; 49 | double C_1_1 = input_list[8] ; 50 | double C_2_0 = input_list[9] ; 51 | double C_2_1 = input_list[10] ; 52 | 53 | double fF1 = flux_list[0] ; 54 | double rF1 = flux_list[1] ; 55 | 56 | double pool_A = pool_list[0] ; 57 | double pool_C = pool_list[1] ; 58 | double pool_B = pool_list[2] ; 59 | 60 | /*dA_0/dt=*/ out[0] = ( +rF1*(C_0_0+C_0_1)-fF1*((B_0+B_1)*A_0) )/ pool_A ; 61 | 62 | /*dA_1/dt=*/ out[1] = ( +rF1*(C_1_0+C_1_1)-fF1*((B_0+B_1)*A_1) )/ pool_A ; 63 | 64 | /*dA_2/dt=*/ out[2] = ( +rF1*(C_2_0+C_2_1)-fF1*((B_0+B_1)*A_2) )/ pool_A ; 65 | 66 | /*dB_0/dt=*/ out[3] = ( +rF1*(C_0_0+C_1_0+C_2_0)-fF1*((A_0+A_1+A_2)*B_0) )/ pool_B ; 67 | 68 | /*dB_1/dt=*/ out[4] = ( +rF1*(C_0_1+C_1_1+C_2_1)-fF1*((A_0+A_1+A_2)*B_1) )/ pool_B ; 69 | 70 | /*dC_0_0/dt=*/ out[5] = ( +fF1*(A_0*B_0)-rF1*(C_0_0) )/ pool_C ; 71 | 72 | /*dC_0_1/dt=*/ out[6] = ( +fF1*(A_0*B_1)-rF1*(C_0_1) )/ pool_C ; 73 | 74 | /*dC_1_0/dt=*/ out[7] = ( +fF1*(A_1*B_0)-rF1*(C_1_0) )/ pool_C ; 75 | 76 | /*dC_1_1/dt=*/ out[8] = ( +fF1*(A_1*B_1)-rF1*(C_1_1) )/ pool_C ; 77 | 78 | /*dC_2_0/dt=*/ out[9] = ( +fF1*(A_2*B_0)-rF1*(C_2_0) )/ pool_C ; 79 | 80 | /*dC_2_1/dt=*/ out[10] = ( +fF1*(A_2*B_1)-rF1*(C_2_1) )/ pool_C ; 81 | 82 | } 83 | -------------------------------------------------------------------------------- /iocbio/analysis/tests/test_sarcomere.py: -------------------------------------------------------------------------------- 1 | 2 | from __future__ import division 3 | 4 | import sys 5 | import numpy 6 | 7 | def shape_func(i,w,r): 8 | """ Evaluate shape function. 9 | :: 10 | ^ 11 | ,_____|_____. 1 12 | / \ 13 | --' + '-- -> 0 14 | 0 i 15 | <-w*(1-2r)-> 16 | <-------- w --------> 17 | """ 18 | i = abs(i) 19 | if i <= w*(1-2*r)/2: 20 | return 1 21 | if i <= w/2: 22 | return (1 + numpy.cos((i-(w/2-r*w))/(r*w)*numpy.pi))/2 23 | return 0 24 | 25 | def compute_image(sarcomere_length_um, 26 | sarcomere_width_um, 27 | sarcomere_distance_um, # distance between neighboring sacromeres 28 | roi_width_px, roi_length_px, 29 | pixel_size_um): 30 | 31 | image = numpy.zeros ((roi_length_px, roi_width_px)) 32 | sarcomere_length_px = sarcomere_length_um / pixel_size_um 33 | sarcomere_width_px = sarcomere_width_um / pixel_size_um 34 | sarcomere_distance_px = sarcomere_distance_um / pixel_size_um 35 | 36 | nof_sarcomeres_length = int(roi_length_px / sarcomere_length_px) 37 | nof_sarcomeres_width = int(roi_width_px / sarcomere_distance_px) 38 | 39 | print nof_sarcomeres_length, nof_sarcomeres_width, sarcomere_distance_px, sarcomere_length_px 40 | 41 | for j in range(nof_sarcomeres_width + 1): 42 | cj = j * sarcomere_distance_px 43 | for i in range(nof_sarcomeres_length + 1): 44 | ci = i * sarcomere_length_px 45 | #ci += numpy.random.normal (scale=sarcomere_length_px/40) 46 | lcj = cj #+ numpy.random.normal (scale=sarcomere_distance_px/20) 47 | 48 | for j0 in range(-sarcomere_width_px/2, sarcomere_width_px/2+1): 49 | if lcj+j0 >= image.shape[1] or lcj+j0<0: 50 | continue 51 | sj = shape_func(j0, sarcomere_width_px, 0.4) 52 | 53 | for i0 in range(-sarcomere_length_px/2, sarcomere_length_px/2+1): 54 | if ci+i0 >= image.shape[0] or ci+i0<0: 55 | continue 56 | si = shape_func(i0, sarcomere_length_px, 0.5) 57 | image[ci+i0, lcj+j0] += si * sj * 100 58 | return image 59 | 60 | def main (): 61 | from libtiff import TIFFimage 62 | #import matplotlib.pyplot as plt 63 | 64 | N = 400 65 | for i in range (N): 66 | L = 1.8 + 0.2*numpy.cos(max(0,i-N//5)/N*2*numpy.pi) 67 | print i,L 68 | image = compute_image(L, 2.25, 1.5, 100, 640, 0.274) 69 | tif = TIFFimage(image.astype(numpy.uint8).T, description=''' 70 | VoxelSizeX: 0.274e-6 71 | VoxelSizeY: 0.274e-6 72 | VoxelSizeZ: 1 73 | MicroscopeType: widefield 74 | ObjectiveNA: 1.2 75 | ExcitationWavelength: 540.0 76 | RefractiveIndex: 1.33 77 | ''') 78 | tif.write_file ('fakesacromere_exact/image_%06d.tif' % i) 79 | del tif 80 | 81 | #plt.imshow (image.T*256, interpolation='nearest', cmap='gray') 82 | #plt.show () 83 | 84 | if __name__ == '__main__': 85 | main () 86 | -------------------------------------------------------------------------------- /iocbio/ops/src/discrete_gauss_ext.c: -------------------------------------------------------------------------------- 1 | /* 2 | Implements wrapper functions to discrete_gauss.c code. 3 | Author: Pearu Peterson 4 | Created: October 2010 5 | */ 6 | 7 | #include 8 | #define PY_ARRAY_UNIQUE_SYMBOL PyArray_API 9 | #include "numpy/arrayobject.h" 10 | 11 | #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ 12 | #define PyMODINIT_FUNC void 13 | #endif 14 | 15 | #ifndef M_PI 16 | #define M_PI 3.1415926535897932384626433832795 17 | #endif 18 | 19 | #include "discrete_gauss.h" 20 | 21 | static PyObject *py_dg_convolve(PyObject *self, PyObject *args) 22 | { 23 | int n, rows; 24 | PyObject* f_py = NULL; 25 | PyObject* f1_py = NULL; 26 | double t; 27 | double *f = NULL; 28 | if (!PyArg_ParseTuple(args, "Od", &f1_py, &t)) 29 | return NULL; 30 | f_py = PyArray_ContiguousFromAny(f1_py, PyArray_DOUBLE, 1, 2); 31 | if (f_py==NULL) 32 | return NULL; 33 | if (PyArray_NDIM(f_py)==2) 34 | { 35 | n = PyArray_DIMS(f_py)[0]; 36 | rows = PyArray_DIMS(f_py)[1]; 37 | if (rows<=0) 38 | { 39 | PyErr_SetString(PyExc_TypeError,"first argument is empty"); 40 | return NULL; 41 | } 42 | } 43 | else 44 | { 45 | n = PyArray_DIMS(f_py)[0]; 46 | rows = 1; 47 | } 48 | assert(rows==1); 49 | f = (double*)PyArray_DATA(f_py); 50 | dg_convolve(f, n, t); 51 | if (f1_py == f_py) 52 | { 53 | Py_INCREF(f_py); 54 | } 55 | return f_py; 56 | } 57 | 58 | 59 | static PyObject *py_dg_high_pass_filter(PyObject *self, PyObject *args) 60 | { 61 | int n, rows; 62 | PyObject* f_py = NULL; 63 | PyObject* f1_py = NULL; 64 | double t; 65 | double *f = NULL; 66 | if (!PyArg_ParseTuple(args, "Od", &f1_py, &t)) 67 | return NULL; 68 | f_py = PyArray_ContiguousFromAny(f1_py, PyArray_DOUBLE, 1, 2); 69 | if (f_py==NULL) 70 | return NULL; 71 | if (PyArray_NDIM(f_py)==2) 72 | { 73 | n = PyArray_DIMS(f_py)[1]; 74 | rows = PyArray_DIMS(f_py)[0]; 75 | if (rows<=0) 76 | { 77 | PyErr_SetString(PyExc_TypeError,"first argument is empty"); 78 | return NULL; 79 | } 80 | } 81 | else 82 | { 83 | n = PyArray_DIMS(f_py)[0]; 84 | rows = 1; 85 | } 86 | printf("n,rows=%d,%d\n", n, rows); 87 | f = (double*)PyArray_DATA(f_py); 88 | dg_high_pass_filter(f, n, rows, t); 89 | if (f1_py == f_py) 90 | { 91 | Py_INCREF(f_py); 92 | } 93 | return f_py; 94 | } 95 | 96 | 97 | static PyMethodDef module_methods[] = { 98 | {"convolve", py_dg_convolve, METH_VARARGS, "convolve(f, t)"}, 99 | {"high_pass_filter", py_dg_high_pass_filter, METH_VARARGS, "high_pass_filter(f, t)"}, 100 | {NULL} /* Sentinel */ 101 | }; 102 | 103 | PyMODINIT_FUNC 104 | initdiscrete_gauss_ext(void) 105 | { 106 | PyObject* m = NULL; 107 | import_array(); 108 | if (PyErr_Occurred()) 109 | {PyErr_SetString(PyExc_ImportError, "can't initialize module discrete_gauss_ext (failed to import numpy)"); return;} 110 | m = Py_InitModule3("discrete_gauss_ext", module_methods, "Provides wrappers to discrete_gauss.c functions."); 111 | } 112 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | 6 | NAME = 'iocbio' 7 | AUTHOR = 'Pearu Peterson' 8 | AUTHOR_EMAIL = 'pearu.peterson@gmail.com' 9 | LICENSE = 'BSD' 10 | URL = 'http://code.google.com/p/iocbio/' 11 | DOWNLOAD_URL = 'http://code.google.com/p/iocbio/downloads/list' 12 | DESCRIPTION = 'IOCBio Software' 13 | LONG_DESCRIPTION = '''\ 14 | See http://code.google.com/p/iocbio/ for more information. 15 | ''' 16 | 17 | CLASSIFIERS = '' 18 | PLATFORMS = ['Linux', 'Windows'] 19 | MAJOR = 1 20 | MINOR = 3 21 | MICRO = 0 22 | ISRELEASED = 'RELEASE' in sys.argv 23 | VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) 24 | if ISRELEASED: 25 | sys.argv.remove('RELEASE') 26 | 27 | 28 | if os.path.exists('MANIFEST'): os.remove('MANIFEST') 29 | 30 | def write_version_py(filename='iocbio/version.py'): 31 | cnt = """ 32 | # THIS FILE IS GENERATED FROM iocbio/setup.py 33 | short_version='%(version)s' 34 | version='%(version)s' 35 | release=%(isrelease)s 36 | 37 | if not release: 38 | version += '.dev' 39 | import os 40 | svn_version_file = os.path.join(os.path.dirname(__file__), 41 | '__svn_version__.py') 42 | svn_entries_file = os.path.join(os.path.dirname(__file__),'.svn', 43 | 'entries') 44 | if os.path.isfile(svn_version_file): 45 | import imp 46 | svn = imp.load_module('iocbio.__svn_version__', 47 | open(svn_version_file), 48 | svn_version_file, 49 | ('.py','U',1)) 50 | version += svn.version 51 | elif os.path.isfile(svn_entries_file): 52 | import subprocess 53 | try: 54 | svn_version = subprocess.Popen(["svnversion", os.path.dirname (__file__)], stdout=subprocess.PIPE).communicate()[0] 55 | except: 56 | pass 57 | else: 58 | version += svn_version.strip() 59 | 60 | print version 61 | """ 62 | a = open(filename, 'w') 63 | try: 64 | a.write(cnt % {'version': VERSION, 'isrelease': str(ISRELEASED)}) 65 | finally: 66 | a.close() 67 | 68 | 69 | def configuration(parent_package='',top_path=None): 70 | from numpy.distutils.misc_util import Configuration 71 | config = Configuration(None,parent_package,top_path) 72 | config.add_subpackage('iocbio') 73 | config.get_version('iocbio/version.py') 74 | config.add_data_files(('iocbio','LICENSE.txt')) 75 | return config 76 | 77 | if __name__ == '__main__': 78 | from numpy.distutils.core import setup 79 | 80 | # Rewrite the version file everytime 81 | if os.path.exists('iocbio/version.py'): os.remove('iocbio/version.py') 82 | write_version_py() 83 | 84 | setup( 85 | name = NAME, 86 | author = AUTHOR, 87 | author_email = AUTHOR_EMAIL, 88 | license = LICENSE, 89 | url = URL, 90 | download_url = DOWNLOAD_URL, 91 | description = DESCRIPTION, 92 | long_description = LONG_DESCRIPTION, 93 | classifiers = filter(None, CLASSIFIERS.split('\n')), 94 | platforms = PLATFORMS, 95 | configuration=configuration) 96 | -------------------------------------------------------------------------------- /iocbio/microscope/scripts/deconvolve_with_sphere.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | # Author: Pearu Peterson 4 | # Created: May 2009 5 | 6 | import os 7 | 8 | ### START UPDATE SYS.PATH ### 9 | ### END UPDATE SYS.PATH ### 10 | 11 | from iocbio.optparse_gui import OptionParser 12 | from iocbio.microscope.deconvolution import deconvolve_sphere 13 | from iocbio.io import ImageStack 14 | from iocbio.io.io import fix_path 15 | from iocbio.microscope.script_options import set_deconvolve_with_sphere_options 16 | 17 | file_extensions = ['.tif', '.lsm', 'tiff', '.raw'] 18 | 19 | def get_path_dir(path, suffix): 20 | """ Return a directory name with suffix that will be used to save data 21 | related to given path. 22 | """ 23 | if os.path.isfile(path): 24 | path_dir = path+'.'+suffix 25 | elif os.path.isdir(path): 26 | path_dir = os.path.join(path, suffix) 27 | elif os.path.exists(path): 28 | raise ValueError ('Not a file or directory: %r' % path) 29 | else: 30 | base, ext = os.path.splitext(path) 31 | if ext in file_extensions: 32 | path_dir = path +'.'+suffix 33 | else: 34 | path_dir = os.path.join(path, suffix) 35 | return path_dir 36 | 37 | 38 | def runner (parser, options, args): 39 | 40 | if not hasattr(parser, 'runner'): 41 | options.input_path = None 42 | options.output_path = None 43 | 44 | if args: 45 | if len(args) in [1,2]: 46 | if options.input_path: 47 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 48 | options.input_path = args[0] 49 | else: 50 | parser.error("Incorrect number of arguments (expected 1 or 2 but got %r)" % ((args))) 51 | if len(args)==2: 52 | if options.output_path: 53 | print >> sys.stderr, "WARNING: overwriting output path %r with %r" % (options.output_path, args[1]) 54 | options.output_path = args[1] 55 | 56 | options.input_path = fix_path (options.input_path) 57 | if options.output_path is None: 58 | deconvolve_dir = get_path_dir(options.input_path, 'ioc.deconvolve_w_sphere') 59 | else: 60 | deconvolve_dir = get_path_dir(options.output_path, 'ioc.deconvolve_w_sphere') 61 | 62 | stack = ImageStack.load(options.input_path, options=options) 63 | deconvolved_image = deconvolve_sphere(stack, options.diameter*1e-9, deconvolve_dir, options=options) 64 | 65 | if options.output_path is None: 66 | b,e = os.path.splitext(options.input_path) 67 | suffix = deconvolved_image.pathinfo.suffix 68 | options.output_path = b + suffix + (e or '.tif') 69 | options.output_path = fix_path(options.output_path) 70 | 71 | if 1: 72 | print 'Saving result to %r' % (options.output_path) 73 | deconvolved_image.save(options.output_path) 74 | 75 | def main (): 76 | parser = OptionParser() 77 | set_deconvolve_with_sphere_options (parser) 78 | if hasattr(parser, 'runner'): 79 | parser.runner = runner 80 | options, args = parser.parse_args() 81 | runner(parser, options, args) 82 | return 83 | 84 | if __name__ == "__main__": 85 | main() 86 | -------------------------------------------------------------------------------- /iocbio/ops/examples/acf_dominant_frequency.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from numpy import * 3 | from iocbio.ops.autocorrelation import acf, acf_argmax, acf_sinefit, acf_sine_power_spectrum 4 | from matplotlib import pyplot as plt 5 | import time 6 | 7 | dx = 0.05 8 | x = arange(0,2*pi,dx) 9 | N = len(x) 10 | y = arange(0,N,0.1) 11 | 12 | fig = plt.figure (0, (16*1.5,16*1.5)) 13 | fig.text(.5,.95, 'Finding dominant frequency via autocorrelation function analysis', ha='center') 14 | 15 | for ii, (f_expr, sp1, sp2, sp3) in enumerate([('7*sin(5*x)+4*sin(9*x)', 321,323,325), 16 | ('7*sin(5*x)+6*sin(9*x)', 322,324,326), 17 | ]): 18 | f = eval(f_expr) 19 | start = time.time() 20 | acf_data = acf(f, y) 21 | end = time.time() 22 | if not ii: 23 | print 'ACF computation time per point: %.3fus' % (1e6*(end-start)/len (y)) 24 | start = time.time() 25 | omega = acf_sinefit(f, start_j=1) 26 | end = time.time() 27 | if not ii: 28 | print 'Sine fit computation time: %.3fus' % (1e6*(end-start)) 29 | omega2 = acf_sinefit(f, start_j=int(2*pi/omega)+2) 30 | a = acf(f, 0.0) 31 | sinefit = a*cos(omega*y)*(N-y)/N 32 | sinefit2 = a*cos(omega2*y)*(N-y)/N 33 | 34 | omega_lst = arange(0, 0.8, 0.001) 35 | omega_arr = omega_lst/dx 36 | start = time.time() 37 | sine_power = acf_sine_power_spectrum (f, omega_lst) 38 | end = time.time() 39 | if not ii: 40 | print 'Sine power spectrum computation time per point: %.3fus' % (1e6*(end-start)/len (omega_lst)) 41 | 42 | plt.subplot(sp1) 43 | plt.plot(x, f, label='$f(x) = %s$' % (f_expr.replace('*','').replace ('sin','\sin'))) 44 | plt.plot(x, (a/N)**0.5 *sin(omega/dx*x), label='$f(x)=\sqrt{A/N}\sin(\omega_{sine_1}x)$') 45 | plt.plot(x, (a/N)**0.5 *sin(omega2/dx*x), label='$f(x)=\sqrt{A/N}\sin(\omega_{sine_2}x)$') 46 | plt.legend () 47 | plt.xlabel ('x') 48 | plt.ylabel ('f(x)') 49 | plt.title ('Test functions') 50 | 51 | plt.subplot (sp2) 52 | plt.plot(y, acf_data, label='ACF(f(x))') 53 | plt.plot(y, sinefit, label=r'$A\cos (\omega_{sine_1}y) \frac{N-y}{N}$, $\omega_{sine_1}$=%.3f' % (omega/dx)) 54 | plt.plot(y, sinefit2, label=r'$A\cos (\omega_{sine_2}y) \frac{N-y}{N}$, $\omega_{sine_2}$=%.3f' % (omega2/dx)) 55 | 56 | start_j = 1 57 | for n in range(1,4): 58 | start = time.time() 59 | y_max = acf_argmax(f, start_j) 60 | end = time.time() 61 | if not ii and n==1: 62 | print 'ACF 1stmax computation time: %.3fus' % (1e6*(end-start)) 63 | #sys.exit () 64 | start_j = y_max + 1 65 | est_period = dx * y_max/n 66 | 67 | plt.axvline(y_max, label='$%s\cdot2\pi/(\Delta x\cdot y_{max}^{(%s)})$=%.3f' % (n, n, 2*pi/est_period), 68 | color='k') 69 | plt.legend () 70 | plt.xlabel('y') 71 | plt.ylabel ('acf') 72 | plt.title ('Autocorrelation functions') 73 | 74 | plt.subplot (sp3) 75 | plt.semilogy(omega_arr, sine_power) 76 | plt.xlabel('omega') 77 | plt.ylabel ('SinePower(f(x))') 78 | plt.title ('Sine power spectrum') 79 | 80 | plt.savefig('acf_dominant_frequency.png') 81 | #plt.savefig('acf_data_6.png') 82 | plt.show () 83 | 84 | 85 | -------------------------------------------------------------------------------- /iocbio/analysis/tests/test_dp.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import numpy 4 | from iocbio.analysis import dp, ipwf 5 | 6 | def show_measure (f): 7 | from matplotlib import pyplot as plt 8 | n = f.shape[-1] 9 | y = numpy.arange(0,n+n/100, n/100) 10 | o = dp.objective (y, f, order=1, method=0) 11 | plt.subplot (211) 12 | plt.plot (f.T) 13 | plt.subplot (212) 14 | plt.plot(y, o) 15 | plt.axhline(0) 16 | plt.axvline(1) 17 | plt.axvline(2) 18 | plt.axvline(3) 19 | plt.axvline(4) 20 | plt.show () 21 | 22 | def test_find_zero (): 23 | # FE(f) has minimum and maximum within the interval [2,3] 24 | x = numpy.arange(10) 25 | f = numpy.sin(4.9*x/x[-1]*numpy.pi*2)/(1+x) 26 | status, zero, slope = ipwf.e11_find_zero(2,3,f,order=1) 27 | assert status==0,`status` 28 | assert 2.06<=zero<=2.07,`zero` # first nonzero minimum 29 | assert slope>0, `slope` 30 | fperiod = dp.fperiod(f) 31 | assert fperiod==zero,`fperiod, zero` 32 | 33 | 34 | status, zero, slope = ipwf.e11_find_zero(3,2,f,order=1) 35 | assert status==0,`status` 36 | assert 2.98<=zero<=2.99,`zero` 37 | assert slope<0, `slope` 38 | 39 | for initial_period in [0, 0.5, 1, 1.5, 2, 2.5, 2.9]: 40 | assert dp.fperiod(f, initial_period=initial_period)==fperiod,`initial_period, dp.fperiod(f, initial_period=initial_period)` 41 | #show_measure (f) 42 | 43 | # FE(f) has maximum and minimum within the interval [1,2] 44 | x = numpy.arange(20) 45 | w = 12.57 46 | f = numpy.sin(w*(x/x[-1])**2*numpy.pi*2) 47 | status, zero, slope = ipwf.e11_find_zero(1,2,f,order=1) 48 | assert status==0,`status` 49 | assert 1.65<=zero<=1.66,`zero` 50 | assert slope<0, `slope` 51 | status, zero, slope = ipwf.e11_find_zero(2,1,f,order=1) 52 | assert status==0,`status` 53 | assert 1.94<=zero<=1.95,`zero` # first nonzero minimum 54 | assert slope>0, `slope` 55 | fperiod = dp.fperiod(f) 56 | assert fperiod==zero,`fperiod, zero` 57 | 58 | for initial_period in [0, 0.5, 1, 1.5, 1.8, 2, 2.5, 2.9, 3]: 59 | assert dp.fperiod(f, initial_period=initial_period)==fperiod,`initial_period, dp.fperiod(f, initial_period=initial_period)` 60 | 61 | #show_measure (f) 62 | 63 | # FE(f) is constant 64 | x = numpy.arange(20) 65 | f = 0*x+1 66 | fperiod = dp.fperiod(f) 67 | assert fperiod==-2,`fperiod` 68 | fperiod = dp.fperiod(f, initial_period = 2) 69 | assert fperiod==-2,`fperiod` 70 | 71 | # FE(f) has no nonzero minimu 72 | x = numpy.arange(0,1,0.1) 73 | f = x*(1-x) 74 | fperiod = dp.fperiod(f) 75 | assert fperiod==-2,`fperiod` 76 | fperiod = dp.fperiod(f, initial_period = 2) 77 | assert fperiod==-2,`fperiod` 78 | fperiod = dp.fperiod(f, initial_period = 6) 79 | assert fperiod==-2,`fperiod` 80 | 81 | # FE(f) has exactly one non-zero minimume 82 | x = numpy.arange(0,1,0.1) 83 | f = x*(1-x)*(0.25-x)*(0.5-x)*(0.75-x) 84 | fperiod = dp.fperiod(f) 85 | for initial_period in [0, 0.5, 1, 4, 5, 6, 7, 7.5, 8.5]: 86 | assert dp.fperiod(f, initial_period=initial_period)==fperiod,`initial_period, dp.fperiod(f, initial_period=initial_period)` 87 | 88 | #show_measure (f) 89 | 90 | if __name__=='__main__': 91 | test_find_zero () 92 | -------------------------------------------------------------------------------- /iocbio/fperiod/tests/test_fperiod.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import numpy 4 | from iocbio import fperiod #dp, ipwf 5 | 6 | def show_measure (f): 7 | from matplotlib import pyplot as plt 8 | n = f.shape[-1] 9 | y = numpy.arange(0,n+n/100, n/100) 10 | o = fperiod.objective (y, f, order=1, method=0) 11 | plt.subplot (211) 12 | plt.plot (f.T) 13 | plt.subplot (212) 14 | plt.plot(y, o) 15 | plt.axhline(0) 16 | plt.axvline(1) 17 | plt.axvline(2) 18 | plt.axvline(3) 19 | plt.axvline(4) 20 | plt.show () 21 | 22 | def test_find_zero (): 23 | # FE(f) has minimum and maximum within the interval [2,3] 24 | x = numpy.arange(10) 25 | f = numpy.sin(4.9*x/x[-1]*numpy.pi*2)/(1+x) 26 | status, zero, slope = fperiod.ipwf.e11_find_zero(2,3,f,order=1) 27 | assert status==0,`status` 28 | assert 2.06<=zero<=2.07,`zero` # first nonzero minimum 29 | assert slope>0, `slope` 30 | fp = fperiod.fperiod(f) 31 | assert fp==zero,`fp, zero` 32 | 33 | 34 | status, zero, slope = fperiod.ipwf.e11_find_zero(3,2,f,order=1) 35 | assert status==0,`status` 36 | assert 2.98<=zero<=2.99,`zero` 37 | assert slope<0, `slope` 38 | 39 | for initial_period in [0, 0.5, 1, 1.5, 2, 2.5, 2.9]: 40 | assert fperiod.fperiod(f, initial_period=initial_period)==fp,`initial_period, fperiod.fperiod(f, initial_period=initial_period)` 41 | #show_measure (f) 42 | 43 | # FE(f) has maximum and minimum within the interval [1,2] 44 | x = numpy.arange(20) 45 | w = 12.57 46 | f = numpy.sin(w*(x/x[-1])**2*numpy.pi*2) 47 | status, zero, slope = fperiod.ipwf.e11_find_zero(1,2,f,order=1) 48 | assert status==0,`status` 49 | assert 1.65<=zero<=1.66,`zero` 50 | assert slope<0, `slope` 51 | status, zero, slope = fperiod.ipwf.e11_find_zero(2,1,f,order=1) 52 | assert status==0,`status` 53 | assert 1.94<=zero<=1.95,`zero` # first nonzero minimum 54 | assert slope>0, `slope` 55 | fp = fperiod.fperiod(f) 56 | assert fp==zero,`fp, zero` 57 | 58 | for initial_period in [0, 0.5, 1, 1.5, 1.8, 2, 2.5, 2.9, 3]: 59 | assert fperiod.fperiod(f, initial_period=initial_period)==fp,`initial_period, fperiod.fperiod(f, initial_period=initial_period)` 60 | 61 | #show_measure (f) 62 | 63 | # FE(f) is constant 64 | x = numpy.arange(20) 65 | f = 0*x+1 66 | fp = fperiod.fperiod(f) 67 | assert fp==-2,`fp` 68 | fp = fperiod.fperiod(f, initial_period = 2) 69 | assert fp==-2,`fp` 70 | 71 | # FE(f) has no nonzero minimum 72 | x = numpy.arange(0,1,0.1) 73 | f = x*(1-x) 74 | fp = fperiod.fperiod(f) 75 | assert fp==-2,`fp` 76 | fp = fperiod.fperiod(f, initial_period = 2) 77 | assert fp==-2,`fp` 78 | #show_measure (f) 79 | fp = fperiod.fperiod(f, initial_period = 6) 80 | assert fp==-2,`fp` 81 | 82 | # FE(f) has exactly one non-zero minimum 83 | x = numpy.arange(0,1,0.1) 84 | f = x*(1-x)*(0.25-x)*(0.5-x)*(0.75-x) 85 | fp = fperiod.fperiod(f) 86 | for initial_period in [0, 0.5, 1, 4, 5, 6, 7, 7.5, 8.5]: 87 | assert fperiod.fperiod(f, initial_period=initial_period)==fp,`initial_period, fperiod.fperiod(f, initial_period=initial_period)` 88 | 89 | #show_measure (f) 90 | 91 | if __name__=='__main__': 92 | test_find_zero () 93 | -------------------------------------------------------------------------------- /iocbio/fperiod/src/demo.c: -------------------------------------------------------------------------------- 1 | /* Demo program for estimating fundamental period of a sine signal. 2 | 3 | This program is part of the IOCBio project. See 4 | http://iocbio.googlecode.com/ for more information. 5 | 6 | To compile, run: 7 | 8 | cc demo.c libfperiod.c -o demo -lm 9 | 10 | Usage: 11 | 12 | demo [ [ []]] 13 | 14 | where n is the length of the signal, period is the expected 15 | fundamental period, and detrend!=0 enables using the detrend 16 | algorithm. 17 | 18 | Example session: 19 | 20 | $ ./demo 20 5.4 0 21 | Signal definition: f[i]=sin(2*pi*i/5.400000), i=0,1,..,19 22 | Number of repetitive patterns in the signal=3.703704 23 | Detrend algorithm is disabled 24 | Expected fundamental period=5.400000 25 | Estimated fundamental period=5.389328 26 | Relative error of the estimate=0.197630% 27 | $ 28 | 29 | */ 30 | 31 | /* 32 | Author: Pearu Peterson 33 | Created: November 2011 34 | */ 35 | 36 | #include 37 | #include 38 | #include 39 | #include "libfperiod.h" 40 | 41 | int main(int argc, char *argv[]) 42 | { 43 | 44 | int n = 30; /* default length of a signal (one row) */ 45 | int m = 1; /* number of signal rows */ 46 | double *f = NULL; /* holds signal data */ 47 | double period = 5.3; /* default value of expected period */ 48 | double initial_period = 0.0; /* 0.0 means unspecified */ 49 | int detrend = 0; /* when non-zero then detrend algorithm is applied 50 | prior the fundamental period estimation. The 51 | detrend algorithm removes background field from 52 | the signal. */ 53 | int method = 0; /* unused argument for libfperiod */ 54 | double fperiod; /* estimated fundamental period */ 55 | int i; 56 | 57 | /* Read parameters from program arguments */ 58 | switch(argc) 59 | { 60 | case 4: 61 | detrend = atoi(argv[3]); 62 | case 3: 63 | period = atof(argv[2]); 64 | case 2: 65 | n = atoi(argv[1]); 66 | case 1: 67 | break; 68 | default: 69 | printf("Unexpected number of arguments: %d\nUsage: %s [ [ []]]", argc, argv[0]); 70 | } 71 | 72 | /* Initialize signal */ 73 | printf("Signal definition: f[i]=sin(2*pi*i/%f), i=0,1,..,%d\n", period, n-1); 74 | printf("Number of repetitive patterns in the signal=%f\n", n/period); 75 | if (detrend) 76 | printf("Detrend algorithm is enabled\n"); 77 | else 78 | printf("Detrend algorithm is disabled\n"); 79 | f = (double*)malloc(sizeof(double)*n*m); 80 | for (i=0;i. 11 | 12 | See http://iocbio.googlecode.com/ for more information. 13 | 14 | License: BSD, see the footer of libfperiod.c. 15 | Author: Pearu Peterson 16 | Created: November 2011 17 | */ 18 | 19 | #ifndef LIBFPERIOD_H 20 | #define LIBFPERIOD_H 21 | 22 | #ifdef __cplusplus 23 | extern "C" { 24 | #endif 25 | extern void iocbio_objective(double *y, int k, double *f, int n, int m, int order, int method, double *r); 26 | extern double iocbio_fperiod(double *f, int n, int m, double initial_period, int detrend, int method); 27 | extern double iocbio_fperiod_cached(double *f, int n, int m, double initial_period, int detrend, int method, double *cache); 28 | extern double iocbio_fperiod2_cached(double *f, int n, int m, double min_period, double max_period, int detrend, int method, double *cache); 29 | extern void iocbio_detrend(double *f, int n, int m, double period, double *r); 30 | extern void iocbio_detrend1(double *f, int n, int fstride, double period, double *r, int rstride); 31 | extern void iocbio_ipwf_e11_compute_coeffs_diff0(int j, double *fm, int n, int m, double* a0, double* a1, double* a2, double* a3); 32 | extern int iocbio_ipwf_e11_find_zero_diff0(int j0, int j1, double *fm, int n, int m, double* result, double* slope); 33 | extern int iocbio_ipwf_e11_find_zero_diff1(int j0, int j1, double *fm, int n, int m, double* result, double* slope); 34 | extern void iocbio_ipwf_e11_compute_coeffs_diff2(int j, double *fm, int n, int m, double* a0, double* a1, double* a2, double* a3); 35 | extern int iocbio_ipwf_e11_find_zero_diff2(int j0, int j1, double *fm, int n, int m, double* result, double* slope); 36 | extern void iocbio_ipwf_e11_compute_coeffs_diff3(int j, double *fm, int n, int m, double* a0, double* a1, double* a2, double* a3); 37 | extern int iocbio_ipwf_e11_find_zero_diff3(int j0, int j1, double *fm, int n, int m, double* result, double* slope); 38 | extern void iocbio_ipwf_e11_compute_coeffs(int j, double *fm, int n, int m, int order, double* a0, double* a1, double* a2, double* a3); 39 | extern int iocbio_ipwf_e11_find_zero(int j0, int j1, double *fm, int n, int m, int order, double* result, double* slope); 40 | extern double iocbio_ipwf_e11_evaluate(double y, double *fm, int n, int m, int order); 41 | extern void iocbio_ipwf_linear_approximation_3_0(double a1_0, double a2_0, double a3_0, double* p0, double* p1); 42 | extern void iocbio_ipwf_linear_approximation_1_1(double a1_0, double a1_1, double* p0, double* p1); 43 | extern void iocbio_ipwf_linear_approximation_1_3(double a1_0, double a1_1, double a1_2, double a1_3, double* p0, double* p1); 44 | extern double iocbio_ipwf_find_real_zero_in_01_2(double a_0, double a_1, double a_2, int direction, double *slope); 45 | extern void iocbio_ipwf_e11_compute_coeffs_diff1(int j, double *fm, int n, int m, double* a0, double* a1, double* a2, double* a3); 46 | #ifdef __cplusplus 47 | } 48 | #endif 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /iocbio/setup.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | from os.path import join, basename, dirname, splitext 4 | from glob import glob 5 | 6 | from numpy.distutils import log 7 | from distutils.dep_util import newer 8 | 9 | 10 | def configuration(parent_package='',top_path=None): 11 | from numpy.distutils.misc_util import Configuration 12 | config = Configuration('iocbio',parent_package,top_path) 13 | 14 | # Add subpackages here: 15 | config.add_subpackage('io') 16 | config.add_subpackage('ops') 17 | config.add_subpackage('microscope') 18 | config.add_subpackage('scanner') 19 | config.add_subpackage('strathkelvin') 20 | config.add_subpackage('chaco') 21 | config.add_subpackage('fperiod') 22 | config.add_subpackage('kinetics') 23 | #config.add_subpackage('analysis') 24 | # eof add. 25 | 26 | config.make_svn_version_py() 27 | 28 | wininst = 'bdist_wininst' in sys.argv or sys.platform=='win32' 29 | try: 30 | import multiprocessing 31 | except ImportError: 32 | multiprocessing = None 33 | 34 | scripts = glob(join(config.local_path, 'scripts', '*.py')) 35 | scripts += glob(join(config.local_path, '*', 'scripts', '*.py')) 36 | for script in scripts: 37 | if basename (script).startswith ('iocbio'): 38 | config.add_scripts(script) 39 | continue 40 | 41 | def generate_a_script(build_dir, script=script, config=config): 42 | dist = config.get_distribution() 43 | install_lib = dist.get_command_obj('install_lib') 44 | if not install_lib.finalized: 45 | install_lib.finalize_options() 46 | 47 | script_replace_text = '' 48 | install_lib = install_lib.install_dir 49 | if install_lib is not None: 50 | script_replace_text = ''' 51 | import sys 52 | if %(d)r not in sys.path: 53 | sys.path.insert(0, %(d)r) 54 | ''' % dict(d=install_lib) 55 | if multiprocessing is not None: 56 | mp_install_lib = dirname(dirname(multiprocessing.__file__)) 57 | script_replace_text += ''' 58 | if %(d)r not in sys.path: 59 | sys.path.insert(0, %(d)r) 60 | ''' % dict(d=mp_install_lib) 61 | 62 | start_mark = '### START UPDATE SYS.PATH ###' 63 | end_mark = '### END UPDATE SYS.PATH ###' 64 | name = basename(script) 65 | if name.startswith ('iocbio'): 66 | target_name = name 67 | elif wininst: 68 | target_name = 'iocbio_' + name 69 | else: 70 | target_name = 'iocbio.' + splitext(name)[0] 71 | target = join(build_dir, target_name) 72 | if newer(script, target) or 1: 73 | log.info('Creating %r', target) 74 | f = open (script, 'r') 75 | text = f.read() 76 | f.close() 77 | 78 | i = text.find(start_mark) 79 | if i != -1: 80 | j = text.find (end_mark) 81 | if j == -1: 82 | log.warn ("%r missing %r line", script, start_mark) 83 | new_text = text[:i+len (start_mark)] + script_replace_text + text[j:] 84 | else: 85 | new_text = text 86 | 87 | f = open(target, 'w') 88 | f.write(new_text) 89 | f.close() 90 | config.add_scripts(generate_a_script) 91 | 92 | return config 93 | -------------------------------------------------------------------------------- /iocbio/microscope/scripts/deconvolve.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python -*- 3 | # Author: Pearu Peterson 4 | # Created: May 2009 5 | 6 | import os 7 | 8 | ### START UPDATE SYS.PATH ### 9 | ### END UPDATE SYS.PATH ### 10 | 11 | from iocbio.optparse_gui import OptionParser 12 | from iocbio.microscope.deconvolution import deconvolve 13 | from iocbio.io import ImageStack 14 | from iocbio.io.io import fix_path, get_psf_path 15 | from iocbio.microscope.script_options import set_deconvolve_options 16 | 17 | file_extensions = ['.tif', '.lsm', 'tiff', '.raw'] 18 | 19 | def runner (parser, options, args): 20 | 21 | if not hasattr(parser, 'runner'): 22 | options.psf_path = None 23 | options.input_path = None 24 | options.output_path = None 25 | 26 | if args: 27 | if len(args) in [2,3]: 28 | if options.psf_path: 29 | print >> sys.stderr, "WARNING: overwriting psf path %r with %r" % (options.psf_path, args[0]) 30 | options.psf_path = args[0] 31 | if options.input_path: 32 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[1]) 33 | options.input_path = args[1] 34 | else: 35 | parser.error("Incorrect number of arguments (expected 2 or 3 but got %r)" % ((args))) 36 | if len(args)==3: 37 | if options.output_path: 38 | print >> sys.stderr, "WARNING: overwriting output path %r with %r" % (options.output_path, args[2]) 39 | options.output_path = args[2] 40 | 41 | options.input_path = fix_path (options.input_path) 42 | if options.output_path is None: 43 | deconvolve_dir = get_path_dir(options.input_path, 'iocbio.deconvolve') 44 | else: 45 | deconvolve_dir = get_path_dir(options.output_path, 'iocbio.deconvolve') 46 | 47 | psf_path = get_psf_path(options) 48 | 49 | psf = ImageStack.load(psf_path, options=options) 50 | stack = ImageStack.load(options.input_path, options=options) 51 | deconvolved_image = deconvolve(psf, stack, deconvolve_dir, options=options) 52 | 53 | if options.output_path is None: 54 | b,e = os.path.splitext(options.input_path) 55 | suffix = deconvolved_image.pathinfo.suffix 56 | options.output_path = b + suffix + (e or '.tif') 57 | options.output_path = fix_path(options.output_path) 58 | 59 | if 1: 60 | print 'Saving result to %r' % (options.output_path) 61 | deconvolved_image.save(options.output_path) 62 | 63 | def get_path_dir(path, suffix): 64 | """ Return a directory name with suffix that will be used to save data 65 | related to given path. 66 | """ 67 | if os.path.isfile(path): 68 | path_dir = path+'.'+suffix 69 | elif os.path.isdir(path): 70 | path_dir = os.path.join(path, suffix) 71 | elif os.path.exists(path): 72 | raise ValueError ('Not a file or directory: %r' % path) 73 | else: 74 | base, ext = os.path.splitext(path) 75 | if ext in file_extensions: 76 | path_dir = path +'.'+suffix 77 | else: 78 | path_dir = os.path.join(path, suffix) 79 | return path_dir 80 | 81 | def main (): 82 | parser = OptionParser() 83 | set_deconvolve_options (parser) 84 | if hasattr(parser, 'runner'): 85 | parser.runner = runner 86 | options, args = parser.parse_args() 87 | runner(parser, options, args) 88 | return 89 | 90 | if __name__ == "__main__": 91 | main() 92 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | HTML_TARGET = ../apidocs 5 | 6 | # You can set these variables from the command line. 7 | SPHINXOPTS = -n -P 8 | SPHINXBUILD = sphinx-build 9 | PAPER = 10 | 11 | # Internal variables. 12 | PAPEROPT_a4 = -D latex_paper_size=a4 13 | PAPEROPT_letter = -D latex_paper_size=letter 14 | ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 15 | 16 | .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest 17 | 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 27 | @echo " changes to make an overview of all changed/added/deprecated items" 28 | @echo " linkcheck to check all external links for integrity" 29 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 30 | 31 | clean: 32 | -rm -rf _build source/generated source/reference/* $(HTML_TARGET)/* 33 | 34 | 35 | html: 36 | -mkdir -p $(HTML_TARGET) 37 | -touch $(HTML_TARGET)/index.html 38 | -echo `date -u` ": documentation is being updated... try again in few minutes." > $(HTML_TARGET)/index.html 39 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(HTML_TARGET) 40 | @echo 41 | @echo "Build finished. The HTML pages are in $(HTML_TARGET)." 42 | 43 | dirhtml: 44 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml 45 | @echo 46 | @echo "Build finished. The HTML pages are in _build/dirhtml." 47 | 48 | pickle: 49 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle 50 | @echo 51 | @echo "Build finished; now you can process the pickle files." 52 | 53 | json: 54 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json 55 | @echo 56 | @echo "Build finished; now you can process the JSON files." 57 | 58 | htmlhelp: 59 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp 60 | @echo 61 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 62 | ".hhp project file in _build/htmlhelp." 63 | 64 | qthelp: 65 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp 66 | @echo 67 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 68 | ".qhcp project file in _build/qthelp, like this:" 69 | @echo "# qcollectiongenerator _build/qthelp/Iocbio.qhcp" 70 | @echo "To view the help file:" 71 | @echo "# assistant -collectionFile _build/qthelp/Iocbio.qhc" 72 | 73 | latex: 74 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex 75 | @echo 76 | @echo "Build finished; the LaTeX files are in _build/latex." 77 | @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ 78 | "run these through (pdf)latex." 79 | 80 | changes: 81 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes 82 | @echo 83 | @echo "The overview file is in _build/changes." 84 | 85 | linkcheck: 86 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck 87 | @echo 88 | @echo "Link check complete; look for any errors in the above output " \ 89 | "or in _build/linkcheck/output.txt." 90 | 91 | doctest: 92 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest 93 | @echo "Testing of doctests in the sources finished, look at the " \ 94 | "results in _build/doctest/output.txt." 95 | -------------------------------------------------------------------------------- /doc/BuildWindowsInstallersOnLinux.txt: -------------------------------------------------------------------------------- 1 | ### Enthought based installers. 2 | sudo apt-get install wine 3 | mkdir wine && cd wine 4 | wget http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/mingw-get-inst-20100909/mingw-get-inst-20100909.exe 5 | wine mingw-get-inst-20100909.exe 6 | # Select C++ Compiler, Fortran Compiler, MSYS Basic System, MinGW Developer Toolkit 7 | # Lookup "PATH" environment variable and append ";C:\Python27;C:\Python27\Scripts;C:\MinGW\bin;C:\MinGW\msys\1.0\bin;C:\gtk\bin;C:\Program Files\GnuWin32\bin;C:\Program Files\Git\bin" to it. 8 | # The path to "PATH" is "HKEY_LOCAL_MACHINE/System/CurrentControlSet/Control/Session Manager/Environment/PATH". 9 | 10 | wget http://sysbio.ioc.ee/download/software/binaries/101019/deps/epd-6.2-2-win-x86.msi 11 | msiexec /i epd-6.2-2-win-x86.msi 12 | 13 | ########################### 14 | sudo apt-get install wine 15 | mkdir wine && cd wine 16 | wget http://www.python.org/ftp/python/2.7/python-2.7.msi 17 | msiexec /i python-2.7.msi 18 | wget http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/mingw-get-inst-20100909/mingw-get-inst-20100909.exe 19 | wine 20 | # Select C++ Compiler, Fortran Compiler, MSYS Basic System, MinGW Developer Toolkit 21 | regedit 22 | # Lookup "PATH" environment variable and append ";C:\Python27;C:\Python27\Scripts;C:\MinGW\bin;C:\MinGW\msys\1.0\bin;C:\gtk\bin;C:\Program Files\GnuWin32\bin;C:\Program Files\Git\bin" to it. 23 | # The path to "PATH" is "HKEY_LOCAL_MACHINE/System/CurrentControlSet/Control/Session Manager/Environment/PATH". 24 | wget http://sourceforge.net/projects/wxpython/files/wxPython/2.8.11.0/wxPython2.8-win32-unicode-2.8.11.0-py27.exe 25 | wineconsole bash 26 | mingw-get install msys-wget 27 | wget http://msysgit.googlecode.com/files/Git-1.7.3.1-preview20101002.exe 28 | wine Git-1.7.3.1-preview20101002.exe 29 | git clone git://github.com/numpy/numpy.git numpy 30 | cd numpy 31 | python setup.py build --compiler=mingw32 bdist_wininst 32 | cd dist && ./numpy-2.0.0.dev.win32-py2.7.exe 33 | wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11.win32-py2.7.exe 34 | ./setuptools-0.6c11.win32-py2.7.exe 35 | easy_install-2.7 nose 36 | 37 | wget http://www.siegward-jaekel.de/mc.zip 38 | # copy mc.exe and mc.ini to C:\MinGW\bin 39 | 40 | cd src 41 | wget http://www.netlib.org/lapack/lapack.tgz 42 | tar xzf lapack.tgz 43 | cd lapack-3.2.2/ 44 | wget http://iocbio.googlecode.com/files/make.inc.MINGW 45 | cp make.inc.MINGW-g77 make.inc 46 | cd SRC 47 | make -j 4 48 | mv lapack_MINGW.a libflapack.a 49 | 50 | wget http://www.netlib.org/blas/blas.tgz 51 | tar xzf blas.tgz 52 | cd BLAS 53 | gfortran -fno-second-underscore -O2 -c *.f 54 | ar r libfblas.a *.o 55 | ranlib libfblas.a 56 | 57 | svn co http://svn.scipy.org/svn/scipy/trunk scipy 58 | cd scipy 59 | export BLAS=~/src/BLAS/libfblas.a 60 | export LAPACK=~/src/lapack-3.2.2/libflapack.a 61 | python setup.py build --compiler=mingw32 bdist_wininst 62 | 63 | 64 | http://download.microsoft.com/download/vc60pro/update/1/w9xnt4/en-us/vc6redistsetup_enu.exe 65 | ./vc6redistsetup_enu.exe 66 | http://sourceforge.net/projects/win32svn/files/1.5.5/Setup-Subversion-1.5.5.msi 67 | msiexec /i Setup-Subversion-1.5.5.msi 68 | 69 | cd c: 70 | mkdir gtk 71 | cd gtk 72 | wget http://ftp.acc.umu.se/pub/gnome/binaries/win32/gtk+/2.16/gtk+-bundle_2.16.6-20100912_win32.zip 73 | mingw-get install msys-unzip 74 | unzip gtk+-bundle_2.16.6-20100912_win32.zip 75 | 76 | wget http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.16/pygtk-2.16.0+glade.win32-py2.6.exe 77 | wget http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/2.20/pygobject-2.20.0.win32-py2.6.exe 78 | 79 | -------------------------------------------------------------------------------- /iocbio/ops/src/minpack/enorm.f: -------------------------------------------------------------------------------- 1 | double precision function enorm(n,x) 2 | integer n 3 | double precision x(n) 4 | c ********** 5 | c 6 | c function enorm 7 | c 8 | c given an n-vector x, this function calculates the 9 | c euclidean norm of x. 10 | c 11 | c the euclidean norm is computed by accumulating the sum of 12 | c squares in three different sums. the sums of squares for the 13 | c small and large components are scaled so that no overflows 14 | c occur. non-destructive underflows are permitted. underflows 15 | c and overflows do not occur in the computation of the unscaled 16 | c sum of squares for the intermediate components. 17 | c the definitions of small, intermediate and large components 18 | c depend on two constants, rdwarf and rgiant. the main 19 | c restrictions on these constants are that rdwarf**2 not 20 | c underflow and rgiant**2 not overflow. the constants 21 | c given here are suitable for every known computer. 22 | c 23 | c the function statement is 24 | c 25 | c double precision function enorm(n,x) 26 | c 27 | c where 28 | c 29 | c n is a positive integer input variable. 30 | c 31 | c x is an input array of length n. 32 | c 33 | c subprograms called 34 | c 35 | c fortran-supplied ... dabs,dsqrt 36 | c 37 | c argonne national laboratory. minpack project. march 1980. 38 | c burton s. garbow, kenneth e. hillstrom, jorge j. more 39 | c 40 | c ********** 41 | integer i 42 | double precision agiant,floatn,one,rdwarf,rgiant,s1,s2,s3,xabs, 43 | * x1max,x3max,zero 44 | data one,zero,rdwarf,rgiant /1.0d0,0.0d0,3.834d-20,1.304d19/ 45 | s1 = zero 46 | s2 = zero 47 | s3 = zero 48 | x1max = zero 49 | x3max = zero 50 | floatn = n 51 | agiant = rgiant/floatn 52 | do 90 i = 1, n 53 | xabs = dabs(x(i)) 54 | if (xabs .gt. rdwarf .and. xabs .lt. agiant) go to 70 55 | if (xabs .le. rdwarf) go to 30 56 | c 57 | c sum for large components. 58 | c 59 | if (xabs .le. x1max) go to 10 60 | s1 = one + s1*(x1max/xabs)**2 61 | x1max = xabs 62 | go to 20 63 | 10 continue 64 | s1 = s1 + (xabs/x1max)**2 65 | 20 continue 66 | go to 60 67 | 30 continue 68 | c 69 | c sum for small components. 70 | c 71 | if (xabs .le. x3max) go to 40 72 | s3 = one + s3*(x3max/xabs)**2 73 | x3max = xabs 74 | go to 50 75 | 40 continue 76 | if (xabs .ne. zero) s3 = s3 + (xabs/x3max)**2 77 | 50 continue 78 | 60 continue 79 | go to 80 80 | 70 continue 81 | c 82 | c sum for intermediate components. 83 | c 84 | s2 = s2 + xabs**2 85 | 80 continue 86 | 90 continue 87 | c 88 | c calculation of norm. 89 | c 90 | if (s1 .eq. zero) go to 100 91 | enorm = x1max*dsqrt(s1+(s2/x1max)/x1max) 92 | go to 130 93 | 100 continue 94 | if (s2 .eq. zero) go to 110 95 | if (s2 .ge. x3max) 96 | * enorm = dsqrt(s2*(one+(x3max/s2)*(x3max*s3))) 97 | if (s2 .lt. x3max) 98 | * enorm = dsqrt(x3max*((s2/x3max)+(x3max*s3))) 99 | go to 120 100 | 110 continue 101 | enorm = x3max*dsqrt(s3) 102 | 120 continue 103 | 130 continue 104 | return 105 | c 106 | c last card of function enorm. 107 | c 108 | end 109 | -------------------------------------------------------------------------------- /iocbio/chaco/image_timeseries_viewer.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | __all__ = ['ImageTimeseriesViewer'] 4 | 5 | import numpy 6 | 7 | from enthought.traits.api import HasStrictTraits, Instance, Dict, Int, Bool, DelegatesTo, on_trait_change, Button, Any 8 | from enthought.traits.ui.api import View, HSplit, VSplit, Item, VGrid, HGroup, Group, VGroup, Tabbed, RangeEditor 9 | from enthought.enable.api import Component, ComponentEditor 10 | from enthought.chaco.tools.api import ZoomTool, PanTool, ImageInspectorTool, ImageInspectorOverlay 11 | from enthought.chaco.api import ArrayPlotData, Plot, GridContainer, PlotAxis 12 | from enthought.chaco.tools.cursor_tool import BaseCursorTool 13 | from enthought.chaco.default_colormaps import bone 14 | 15 | from .base_data_source import BaseDataSource 16 | from .base_data_viewer import BaseDataViewer 17 | 18 | class ImageTimeseriesViewer(BaseDataViewer): 19 | 20 | plots = Dict 21 | 22 | plotdata = Instance(ArrayPlotData) 23 | image = Any 24 | 25 | time_index = Int 26 | time_points = Int 27 | time = Any 28 | 29 | traits_view = View(Tabbed (HSplit(VGroup(Item('plot', editor=ComponentEditor(), 30 | show_label = False, 31 | resizable = True, label = 'View'), 32 | Item ("time_index", style='custom', editor=RangeEditor (low=0, high_name='time_points')), 33 | Item ("time", style='readonly'), 34 | ), 35 | Item('tasks', style='custom', show_label = False, label = 'Tasks'), 36 | ), 37 | Item ('results', style='custom', show_label = False, label = 'Results'), 38 | ), 39 | ) 40 | 41 | def _time_points_default (self): 42 | return self.data.shape[0]-1 43 | 44 | def _time_index_default (self): 45 | return 0 46 | 47 | def _time_default (self): 48 | return self.get_data_time(0, 0) 49 | 50 | def _plotdata_default(self): 51 | data = self.get_data_slice(0, 0) 52 | plotdata = ArrayPlotData() 53 | plotdata.set_data('xy', data) 54 | return plotdata 55 | 56 | def _time_index_changed (self): 57 | self.select_xy_slice (self.time_index) 58 | 59 | def select_xy_slice(self, t): 60 | data = self.get_data_slice(t, 0) 61 | self.time = self.get_data_time(t, 0) 62 | self.plotdata.set_data('xy', data) 63 | self.image.invalidate_and_redraw() 64 | 65 | def reset (self): 66 | pass 67 | 68 | def redraw (self): 69 | self.image.invalidate_and_redraw() 70 | 71 | def get_plot(self): 72 | pixel_sizes = self.data_source.pixel_sizes 73 | shape = self.data.shape[1:] 74 | m = min(pixel_sizes) 75 | s = [int(d*sz/m) for d, sz in zip(shape, pixel_sizes)] 76 | plot_sizes = dict (xy = (s[1], s[0])) 77 | plot = Plot(self.plotdata, padding=30, fixed_preferred_size = plot_sizes['xy'], 78 | ) 79 | image = plot.img_plot('xy', colormap=bone)[0] 80 | image.overlays.append(ZoomTool(image)) 81 | image.tools.append(PanTool(image, drag_button='right')) 82 | imgtool = ImageInspectorTool(image) 83 | image.tools.append(imgtool) 84 | overlay = ImageInspectorOverlay(component=image, 85 | bgcolor = 'white', 86 | image_inspector=imgtool) 87 | image.overlays.append(overlay) 88 | self.image = image 89 | 90 | self.plots = dict(xy = image) 91 | return plot 92 | 93 | 94 | -------------------------------------------------------------------------------- /iocbio/ops/scripts/apply_window.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | # Author: Pearu Peterson 4 | # Created: September 2009 5 | 6 | from __future__ import division 7 | import os 8 | 9 | ### START UPDATE SYS.PATH ### 10 | ### END UPDATE SYS.PATH ### 11 | 12 | import numpy 13 | from iocbio.optparse_gui import OptionParser 14 | from iocbio.io import ImageStack 15 | from iocbio.ops.apply_window_ext import apply_window_inplace 16 | from iocbio.io.io import fix_path 17 | from iocbio import utils 18 | from iocbio.ops.script_options import set_apply_window_options 19 | 20 | import time 21 | 22 | def runner(parser, options, args): 23 | 24 | smoothness = int(options.smoothness or 1) 25 | verbose = options.verbose if options.verbose is not None else True 26 | 27 | if not hasattr(parser, 'runner'): 28 | options.output_path = None 29 | 30 | if args: 31 | if len (args)==1: 32 | if options.input_path: 33 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 34 | options.input_path = args[0] 35 | elif len(args)==2: 36 | if options.input_path: 37 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 38 | options.input_path = args[0] 39 | options.output_path = args[1] 40 | else: 41 | parser.error("incorrect number of arguments (expected upto 2 but got %s)" % (len(args))) 42 | 43 | options.input_path = fix_path(options.input_path) 44 | stack = ImageStack.load(options.input_path, options=options) 45 | voxel_sizes = stack.get_voxel_sizes() 46 | new_images = stack.images.copy() 47 | background = (stack.pathinfo.get_background() or [0,0])[0] 48 | print 'Image has background', background 49 | window_width = options.window_width or None 50 | 51 | if window_width is None: 52 | dr = stack.get_lateral_resolution() 53 | dz = stack.get_axial_resolution() 54 | if dr is None or dz is None: 55 | window_width = 3.0 56 | scales = tuple([s/(window_width*min(voxel_sizes)) for s in voxel_sizes]) 57 | else: 58 | print 'lateral resolution: %.3f um (%.1f x %.1f px^2)' % (1e6*dr, dr/voxel_sizes[1], dr/voxel_sizes[2]) 59 | print 'axial resolution: %.3f um (%.1fpx)' % (1e6*dz, dz / voxel_sizes[0]) 60 | vz,vy,vx = voxel_sizes 61 | m = 3 62 | scales = (m*vz/dz, m*vy/dr, m*vx/dr) 63 | window_width = '%.1fx%.1f' % (dz/m/vz, dr/m/vy) 64 | else: 65 | window_width = options.window_width 66 | scales = tuple([s/(window_width*min(voxel_sizes)) for s in voxel_sizes]) 67 | 68 | print 'Window size in pixels:', [1/s for s in scales] 69 | apply_window_inplace (new_images, scales, smoothness, background) 70 | 71 | if options.output_path is None: 72 | b,e = os.path.splitext(options.input_path) 73 | suffix = '_window%s_%s' % (window_width, smoothness) 74 | options.output_path = b + suffix + (e or '.tif') 75 | options.output_path = fix_path(options.output_path) 76 | 77 | if verbose: 78 | print 'Leak: %.3f%%' % ( 100*(1-new_images.sum ()/stack.images.sum ())) 79 | print 'MSE:', ((new_images - stack.images)**2).mean() 80 | print 'Energy:', ((stack.images)**2).sum() 81 | print 'Saving result to',options.output_path 82 | ImageStack(new_images, stack.pathinfo).save(options.output_path) 83 | 84 | def main (): 85 | parser = OptionParser() 86 | set_apply_window_options (parser) 87 | if hasattr(parser, 'runner'): 88 | parser.runner = runner 89 | options, args = parser.parse_args() 90 | runner(parser, options, args) 91 | 92 | if __name__ == '__main__': 93 | main() 94 | -------------------------------------------------------------------------------- /iocbio/chaco_examples/tiff_viewer.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from enthought.etsconfig.api import ETSConfig 3 | ETSConfig.toolkit='wx' # wx, qt4, null 4 | 5 | from enthought.traits.api import HasStrictTraits, Instance, DelegatesTo, List, Str, on_trait_change 6 | from enthought.traits.ui.api import Handler, View, Item, Group, Action, ListEditor, Tabbed 7 | 8 | from iocbio.chaco.base_data_source import BaseDataSource 9 | from iocbio.chaco.base_data_viewer import BaseDataViewer 10 | from iocbio.chaco.image_stack_viewer import ImageStackViewer 11 | from iocbio.chaco.image_timeseries_viewer import ImageTimeseriesViewer 12 | from iocbio.chaco.tiff_data_source import TiffDataSource 13 | from iocbio.chaco.array_data_source import ArrayDataSource 14 | from iocbio.chaco.box_selector_task import BoxSelectorTask 15 | from iocbio.chaco.slice_selector_task import SliceSelectorTask 16 | from iocbio.chaco.fft_viewer_task import FFTViewerTask 17 | from iocbio.chaco.ops_viewer_task import OpsViewerTask 18 | from iocbio.chaco.scale_space_task import ScaleSpaceTask 19 | from iocbio.chaco.points_task import PointsTask 20 | from iocbio.utils import bytes2str 21 | 22 | class ViewHandler (Handler): 23 | 24 | def object_has_data_changed (self, info): 25 | #print 'object_has_data_changed', info.object.has_data, info.object.data_source.kind 26 | if info.object.has_data: 27 | if info.object.data_source.kind=='image_stack': 28 | info.object.data_viewer = None 29 | viewer = ImageStackViewer(data_source = info.object.data_source) 30 | info.object.data_viewer = viewer 31 | viewer.add_task(SliceSelectorTask) 32 | viewer.add_task(BoxSelectorTask) 33 | viewer.add_task(OpsViewerTask) 34 | viewer.add_task(PointsTask) 35 | return 36 | if info.object.data_source.kind=='image_timeseries': 37 | info.object.data_viewer = None 38 | viewer = ImageTimeseriesViewer(data_source = info.object.data_source) 39 | info.object.data_viewer = viewer 40 | #viewer.add_task(SliceSelectorTask) 41 | #viewer.add_task(BoxSelectorTask) 42 | #viewer.add_task(FFTViewerTask) 43 | return 44 | print '%s.object_has_data_changed: notimplemented kind=%r' % (self.__class__.__name__, info.object.data_source.kind) 45 | 46 | object_kind_changed = object_has_data_changed 47 | 48 | class ControlPanel (HasStrictTraits): 49 | 50 | data_source = Instance(BaseDataSource) 51 | data_viewer = Instance(BaseDataViewer) 52 | has_data = DelegatesTo('data_source') 53 | kind = DelegatesTo('data_source') 54 | memusage = DelegatesTo('data_viewer') 55 | status = DelegatesTo('data_viewer') 56 | statusbar = Str 57 | 58 | @on_trait_change('data_viewer.memusage, data_viewer.status') 59 | def update_statusbar(self): 60 | if hasattr (self, 'memusage'): 61 | memusage = bytes2str (self.memusage) 62 | self.statusbar = 'MEMUSAGE=%s STATUS: %s' % (memusage, self.status) 63 | 64 | traits_view = View (Tabbed(Item("data_source", style='custom', show_label=False), 65 | Item('data_viewer', style='custom', resizable=True, show_label = False), 66 | show_border = True, ), 67 | buttons = ['OK'], 68 | resizable = True, 69 | handler = ViewHandler(), 70 | height = 600, 71 | width = 800, 72 | statusbar = 'statusbar' 73 | ) 74 | 75 | try: 76 | file_name = sys.argv[1] 77 | except Exception, msg: 78 | print msg 79 | file_name = 'psf.tif' 80 | ControlPanel(data_source = TiffDataSource(file_name=file_name)).configure_traits() 81 | -------------------------------------------------------------------------------- /iocbio/ops/src/minpack/fdjac2.f: -------------------------------------------------------------------------------- 1 | subroutine fdjac2(fcn,m,n,x,fvec,fjac,ldfjac,iflag,epsfcn,wa) 2 | integer m,n,ldfjac,iflag 3 | double precision epsfcn 4 | double precision x(n),fvec(m),fjac(ldfjac,n),wa(m) 5 | c ********** 6 | c 7 | c subroutine fdjac2 8 | c 9 | c this subroutine computes a forward-difference approximation 10 | c to the m by n jacobian matrix associated with a specified 11 | c problem of m functions in n variables. 12 | c 13 | c the subroutine statement is 14 | c 15 | c subroutine fdjac2(fcn,m,n,x,fvec,fjac,ldfjac,iflag,epsfcn,wa) 16 | c 17 | c where 18 | c 19 | c fcn is the name of the user-supplied subroutine which 20 | c calculates the functions. fcn must be declared 21 | c in an external statement in the user calling 22 | c program, and should be written as follows. 23 | c 24 | c subroutine fcn(m,n,x,fvec,iflag) 25 | c integer m,n,iflag 26 | c double precision x(n),fvec(m) 27 | c ---------- 28 | c calculate the functions at x and 29 | c return this vector in fvec. 30 | c ---------- 31 | c return 32 | c end 33 | c 34 | c the value of iflag should not be changed by fcn unless 35 | c the user wants to terminate execution of fdjac2. 36 | c in this case set iflag to a negative integer. 37 | c 38 | c m is a positive integer input variable set to the number 39 | c of functions. 40 | c 41 | c n is a positive integer input variable set to the number 42 | c of variables. n must not exceed m. 43 | c 44 | c x is an input array of length n. 45 | c 46 | c fvec is an input array of length m which must contain the 47 | c functions evaluated at x. 48 | c 49 | c fjac is an output m by n array which contains the 50 | c approximation to the jacobian matrix evaluated at x. 51 | c 52 | c ldfjac is a positive integer input variable not less than m 53 | c which specifies the leading dimension of the array fjac. 54 | c 55 | c iflag is an integer variable which can be used to terminate 56 | c the execution of fdjac2. see description of fcn. 57 | c 58 | c epsfcn is an input variable used in determining a suitable 59 | c step length for the forward-difference approximation. this 60 | c approximation assumes that the relative errors in the 61 | c functions are of the order of epsfcn. if epsfcn is less 62 | c than the machine precision, it is assumed that the relative 63 | c errors in the functions are of the order of the machine 64 | c precision. 65 | c 66 | c wa is a work array of length m. 67 | c 68 | c subprograms called 69 | c 70 | c user-supplied ...... fcn 71 | c 72 | c minpack-supplied ... dpmpar 73 | c 74 | c fortran-supplied ... dabs,dmax1,dsqrt 75 | c 76 | c argonne national laboratory. minpack project. march 1980. 77 | c burton s. garbow, kenneth e. hillstrom, jorge j. more 78 | c 79 | c ********** 80 | integer i,j 81 | double precision eps,epsmch,h,temp,zero 82 | double precision dpmpar 83 | data zero /0.0d0/ 84 | c 85 | c epsmch is the machine precision. 86 | c 87 | epsmch = dpmpar(1) 88 | c 89 | eps = dsqrt(dmax1(epsfcn,epsmch)) 90 | do 20 j = 1, n 91 | temp = x(j) 92 | h = eps*dabs(temp) 93 | if (h .eq. zero) h = eps 94 | x(j) = temp + h 95 | call fcn(m,n,x,wa,iflag) 96 | if (iflag .lt. 0) go to 30 97 | x(j) = temp 98 | do 10 i = 1, m 99 | fjac(i,j) = (wa(i) - fvec(i))/h 100 | 10 continue 101 | 20 continue 102 | 30 continue 103 | return 104 | c 105 | c last card of subroutine fdjac2. 106 | c 107 | end 108 | -------------------------------------------------------------------------------- /mingw/matplotlib-1.0.0.patch: -------------------------------------------------------------------------------- 1 | *** setupext.py.orig 2010-10-20 13:42:54.666471771 +0300 2 | --- setupext.py 2010-10-20 13:46:49.496567156 +0300 3 | *************** import re 4 | *** 48,54 **** 5 | import subprocess 6 | 7 | basedir = { 8 | ! 'win32' : ['win32_static',], 9 | 'linux2-alpha' : ['/usr/local', '/usr'], 10 | 'linux2-hppa' : ['/usr/local', '/usr'], 11 | 'linux2-mips' : ['/usr/local', '/usr'], 12 | --- 48,54 ---- 13 | import subprocess 14 | 15 | basedir = { 16 | ! 'win32' : [r'c:\gtk', r'c:\Program Files\GnuWin32'], 17 | 'linux2-alpha' : ['/usr/local', '/usr'], 18 | 'linux2-hppa' : ['/usr/local', '/usr'], 19 | 'linux2-mips' : ['/usr/local', '/usr'], 20 | *************** basedir = { 21 | *** 80,85 **** 22 | --- 80,94 ---- 23 | import sys, os, stat 24 | if sys.platform != 'win32': 25 | import commands 26 | + commands_getstatusoutput = commands.getstatusoutput 27 | + else: 28 | + def commands_getstatusoutput (cmd): 29 | + import subprocess 30 | + p = subprocess.Popen([cmd], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) 31 | + p.stdin.close() 32 | + p.wait() 33 | + return p.returncode, p.stdout.read() 34 | + 35 | from textwrap import fill 36 | from distutils.core import Extension 37 | import glob 38 | *************** if sys.platform == 'win32' and win32_com 39 | *** 241,254 **** 40 | else: 41 | std_libs = ['stdc++', 'm'] 42 | 43 | def has_pkgconfig(): 44 | if has_pkgconfig.cache is not None: 45 | return has_pkgconfig.cache 46 | ! if sys.platform == 'win32': 47 | has_pkgconfig.cache = False 48 | else: 49 | #print 'environ', os.environ['PKG_CONFIG_PATH'] 50 | ! status, output = commands.getstatusoutput("pkg-config --help") 51 | has_pkgconfig.cache = (status == 0) 52 | return has_pkgconfig.cache 53 | has_pkgconfig.cache = None 54 | --- 250,266 ---- 55 | else: 56 | std_libs = ['stdc++', 'm'] 57 | 58 | + if 'bdist_wininst' in sys.argv: 59 | + std_libs.append ('msvcrt') 60 | + 61 | def has_pkgconfig(): 62 | if has_pkgconfig.cache is not None: 63 | return has_pkgconfig.cache 64 | ! if 0 and sys.platform == 'win32': 65 | has_pkgconfig.cache = False 66 | else: 67 | #print 'environ', os.environ['PKG_CONFIG_PATH'] 68 | ! status, output = commands_getstatusoutput("pkg-config --help") 69 | has_pkgconfig.cache = (status == 0) 70 | return has_pkgconfig.cache 71 | has_pkgconfig.cache = None 72 | *************** def get_pkgconfig(module, 73 | *** 270,276 **** 74 | '-U': 'undef_macros'} 75 | 76 | cmd = "%s %s %s" % (pkg_config_exec, flags, packages) 77 | ! status, output = commands.getstatusoutput(cmd) 78 | if status == 0: 79 | for token in output.split(): 80 | attr = _flags.get(token[:2], None) 81 | --- 282,288 ---- 82 | '-U': 'undef_macros'} 83 | 84 | cmd = "%s %s %s" % (pkg_config_exec, flags, packages) 85 | ! status, output = commands_getstatusoutput(cmd) 86 | if status == 0: 87 | for token in output.split(): 88 | attr = _flags.get(token[:2], None) 89 | *************** def get_pkgconfig_version(package): 90 | *** 298,304 **** 91 | if not has_pkgconfig(): 92 | return default 93 | 94 | ! status, output = commands.getstatusoutput( 95 | "pkg-config %s --modversion" % (package)) 96 | if status == 0: 97 | return output 98 | --- 310,316 ---- 99 | if not has_pkgconfig(): 100 | return default 101 | 102 | ! status, output = commands_getstatusoutput( 103 | "pkg-config %s --modversion" % (package)) 104 | if status == 0: 105 | return output 106 | -------------------------------------------------------------------------------- /iocbio/analysis/src/dp.pyf: -------------------------------------------------------------------------------- 1 | ! -*- f90 -*- 2 | python module dp 3 | interface 4 | 5 | subroutine detrend(f, n, m, period, r) 6 | fortranname iocbio_detrend 7 | intent(c) detrend 8 | double precision dimension (m, n), intent(in,c):: f 9 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 10 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 11 | double precision intent(c,in), optional :: period = 0.0 12 | double precision intent(c,out), dimension (m,n) :: r 13 | end subroutine detrend 14 | 15 | subroutine trend(f, n, m, period, r) 16 | fortranname iocbio_trend 17 | intent(c) trend 18 | double precision dimension (m, n), intent(in,c):: f 19 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 20 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 21 | double precision intent(c,in), optional :: period = 0.0 22 | double precision intent(c,out), dimension (m,n) :: r 23 | end subroutine trend 24 | 25 | subroutine trend_spline(f, n, period, nof_extremes, extreme_positions, extreme_values, nof_averages, average_positions, average_values) 26 | fortranname iocbio_compute_trend_spline_data 27 | intent(c) trend_spline 28 | double precision dimension (n), intent(in,c):: f 29 | integer, depend(f), intent(c,hide) :: n = len(f) 30 | double precision intent(c,in), optional :: period = 0.0 31 | integer intent (out) :: nof_extremes, nof_averages 32 | double precision intent(c,out), depend(n), dimension (n) :: extreme_positions, extreme_values, average_positions, average_values 33 | end subroutine trend_spline 34 | 35 | function fperiod_cached(f, n, m, initial_period, detrend, method, cache) result (period) 36 | fortranname iocbio_fperiod_cached 37 | intent (c) fperiod_cached 38 | double precision dimension (m, n), intent(in,c):: f 39 | double precision dimension (m, n), intent(in,c,cache):: cache 40 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 41 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 42 | double precision intent(c,in), optional :: initial_period = 0.0 43 | integer, intent(c,in), optional :: detrend = 0 44 | double precision :: period 45 | integer, intent(c,in), optional :: method = 0 ! 0:e11, 1:a11 46 | end function fperiod_cached 47 | 48 | function fperiod (f, n, m, initial_period, detrend, method) result (period) 49 | fortranname iocbio_fperiod 50 | intent (c) fperiod 51 | double precision dimension (m, n), intent(in,c):: f 52 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 53 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 54 | double precision intent(c,in), optional :: initial_period = 0.0 55 | integer, intent(c,in), optional :: detrend = 0 56 | double precision :: period 57 | integer, intent(c,in), optional :: method = 0 ! 0:e11, 1:a11 58 | end function fperiod 59 | 60 | subroutine objective(y, k, f, n, m, order, method, r) 61 | fortranname iocbio_objective 62 | intent(c) objective 63 | double precision dimension (k), intent (in, c) :: y 64 | integer, depend (y), intent (c, hide) :: k = len(y) 65 | double precision dimension (m, n), intent(in,c):: f 66 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 67 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 68 | integer, intent (c), optional :: order = 0 69 | double precision intent(c,out), dimension (k), depend(k) :: r 70 | integer, intent(c,in), optional :: method = 0 ! 0:e11, 1:a11 71 | end subroutine objective 72 | 73 | end interface 74 | end module dp 75 | -------------------------------------------------------------------------------- /iocbio/fperiod/src/fperiod.pyf: -------------------------------------------------------------------------------- 1 | ! -*- f90 -*- 2 | python module fperiod_ext 3 | interface 4 | 5 | subroutine detrend(f, n, m, period, r) 6 | fortranname iocbio_detrend 7 | intent(c) detrend 8 | double precision dimension (m, n), intent(in,c):: f 9 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 10 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 11 | double precision intent(c,in), optional :: period = 0.0 12 | double precision intent(c,out), dimension (m,n) :: r 13 | end subroutine detrend 14 | 15 | subroutine trend(f, n, m, period, r) 16 | fortranname iocbio_trend 17 | intent(c) trend 18 | double precision dimension (m, n), intent(in,c):: f 19 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 20 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 21 | double precision intent(c,in), optional :: period = 0.0 22 | double precision intent(c,out), dimension (m,n) :: r 23 | end subroutine trend 24 | 25 | subroutine trend_spline(f, n, period, nof_extremes, extreme_positions, extreme_values, nof_averages, average_positions, average_values) 26 | fortranname iocbio_compute_trend_spline_data 27 | intent(c) trend_spline 28 | double precision dimension (n), intent(in,c):: f 29 | integer, depend(f), intent(c,hide) :: n = len(f) 30 | double precision intent(c,in), optional :: period = 0.0 31 | integer intent (out) :: nof_extremes, nof_averages 32 | double precision intent(c,out), depend(n), dimension (n) :: extreme_positions, extreme_values, average_positions, average_values 33 | end subroutine trend_spline 34 | 35 | function fperiod_cached(f, n, m, initial_period, detrend, method, cache) result (period) 36 | fortranname iocbio_fperiod_cached 37 | intent (c) fperiod_cached 38 | double precision dimension (m, n), intent(in,c):: f 39 | double precision dimension (m, n), intent(in,c,cache):: cache 40 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 41 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 42 | double precision intent(c,in), optional :: initial_period = 0.0 43 | integer, intent(c,in), optional :: detrend = 0 44 | double precision :: period 45 | integer, intent(c,in), optional :: method = 0 ! 0:e11, 1:a11 46 | end function fperiod_cached 47 | 48 | function fperiod (f, n, m, initial_period, detrend, method) result (period) 49 | fortranname iocbio_fperiod 50 | intent (c) fperiod 51 | double precision dimension (m, n), intent(in,c):: f 52 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 53 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 54 | double precision intent(c,in), optional :: initial_period = 0.0 55 | integer, intent(c,in), optional :: detrend = 0 56 | double precision :: period 57 | integer, intent(c,in), optional :: method = 0 ! 0:e11, 1:a11 58 | end function fperiod 59 | 60 | subroutine objective(y, k, f, n, m, order, method, r) 61 | fortranname iocbio_objective 62 | intent(c) objective 63 | double precision dimension (k), intent (in, c) :: y 64 | integer, depend (y), intent (c, hide) :: k = len(y) 65 | double precision dimension (m, n), intent(in,c):: f 66 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 67 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 68 | integer, intent (c), optional :: order = 0 69 | double precision intent(c,out), dimension (k), depend(k) :: r 70 | integer, intent(c,in), optional :: method = 0 ! 0:e11, 1:a11 71 | end subroutine objective 72 | 73 | end interface 74 | end module fperiod_ext 75 | -------------------------------------------------------------------------------- /iocbio/analysis/src/fperiod.pyf: -------------------------------------------------------------------------------- 1 | ! -*- f90 -*- 2 | python module fperiod 3 | interface 4 | 5 | function fperiod_compute_period(f, n, m, structure_size, exp, method, period, period2) result (status) 6 | intent(c) fperiod_compute_period 7 | integer :: status 8 | double precision, dimension (m, n), intent(in,c):: f 9 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 10 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 11 | double precision, intent(c,in), optional :: structure_size = 0 12 | double precision, intent(c,in), optional :: exp = 1.0 13 | integer, intent(c,in), optional :: method = 3 14 | double precision, intent(out) :: period, period2 15 | end function fperiod_compute_period 16 | 17 | function fperiod_cf(y, f, n, m) result (v) 18 | intent(c) fperiod_cf 19 | double precision intent(in, c) :: y 20 | double precision dimension (m, n), intent(in,c):: f 21 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 22 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 23 | double precision :: v 24 | end function fperiod_cf 25 | 26 | function fperiod_cf_d1(y, f, n, m) result (v) 27 | intent(c) fperiod_cf_d1 28 | double precision intent(in, c) :: y 29 | double precision dimension (m, n), intent(in,c):: f 30 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 31 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 32 | double precision :: v 33 | end function fperiod_cf_d1 34 | 35 | function fperiod_cf_d2(y, f, n, m) result (v) 36 | intent(c) fperiod_cf_d2 37 | double precision intent(in, c) :: y 38 | double precision dimension (m, n), intent(in,c):: f 39 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 40 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 41 | double precision :: v 42 | end function fperiod_cf_d2 43 | 44 | subroutine fperiod_subtract_average(f, n, m, structure_size, r) 45 | intent(c) fperiod_subtract_average 46 | double precision intent(in, c) :: y 47 | double precision dimension (m, n), intent(in,c):: f 48 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 49 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 50 | integer, intent(c,in), optional :: structure_size = 0 51 | double precision intent(c,out), dimension (m,n) :: r 52 | end subroutine fperiod_subtract_average 53 | 54 | subroutine fperiod_mark_crests(f, n, m, structure_size, q, r) 55 | intent(c) fperiod_mark_crests 56 | double precision intent(in, c) :: y 57 | double precision dimension (m, n), intent(in,c):: f 58 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 59 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 60 | integer, intent(c,in), optional :: structure_size = 0 61 | integer, intent (c, in), optional :: q = 10 62 | double precision intent(c,out), dimension (m,n*q), depend(n,m,q) :: r 63 | end subroutine fperiod_mark_crests 64 | 65 | subroutine fperiod_subtract_average_2d(f, n, m, smoothness, r) 66 | intent(c) fperiod_subtract_average_2d 67 | double precision intent(in, c) :: y 68 | double precision dimension (m, n), intent(in,c):: f 69 | integer, depend(f), intent(c,hide) :: n = (shape(f,1)==1?shape (f,0):shape(f,1)) 70 | integer, depend(f), intent(c,hide) :: m = (shape(f,1)==1?1:shape(f,0)) 71 | integer, intent(c,in), optional :: smoothness = 0 72 | double precision intent(c,out), dimension (m,n) :: r 73 | end subroutine fperiod_subtract_average_2d 74 | 75 | end interface 76 | end module fperiod 77 | -------------------------------------------------------------------------------- /iocbio/strathkelvin/reader.py: -------------------------------------------------------------------------------- 1 | 2 | # Author: Pearu Peterson 3 | # Created: June 2010 4 | 5 | import numpy 6 | from datetime import datetime 7 | from iocbio.timeunit import Time, Seconds 8 | from collections import defaultdict 9 | 10 | def splitline(line): 11 | r = line.split(None, 3) 12 | if len(r)==3: 13 | r.append ('') 14 | return r 15 | 16 | def reader (filename): 17 | """ Reader of strathkelvin929 output files. 18 | 19 | Parameters 20 | ---------- 21 | filename : str 22 | Path to experiment file. 23 | 24 | Returns 25 | ------- 26 | data : dict 27 | Dictionary of time, oxygen, respiration_rate, and event arrays. 28 | info : dict 29 | Dictionary of experimental parameters. 30 | """ 31 | start_time_format = '%y-%m-%d %H:%M' 32 | lines = open (filename, 'r').readlines () 33 | timeunit = None 34 | info = {} 35 | keys = [] 36 | data = defaultdict (list) 37 | events = {} 38 | for i, line in enumerate(lines): 39 | if line.startswith('#'): 40 | if line.startswith('# Configuration.rate_regression_points :'): 41 | n = int(line.split (':',1)[-1].strip()) 42 | elif line.startswith('# protocol :'): 43 | protocol = line.split (':',1)[-1].strip() 44 | elif line.startswith ('# start time :'): 45 | start_time = datetime.strptime(line.split(':',1)[-1].strip(), start_time_format) 46 | elif line.startswith ('# Configuration.oxygen_units :'): 47 | oxygenunit = line.split(':', 1)[-1].strip() 48 | elif line.startswith ('# Configuration.time_units :'): 49 | timeunit = line.split(':', 1)[-1].strip() 50 | elif 'volume_ml :' in line: 51 | if line.startswith('# %s.' % (protocol)): 52 | volume_ml = float(line.split (':',1)[-1].strip ()) 53 | else: 54 | t1, t2 = line.split (':',1) 55 | other_volumes[t1[1:-1].strip()] = float(t2.strip()) 56 | if ':' in line: 57 | key, value = line[1:].split (':', 1) 58 | info[key.strip()] = value.strip() 59 | elif not keys: 60 | for i,w in enumerate (line[1:].strip().split()): 61 | if i%2: 62 | keys[-1] += ' ' + w.strip() 63 | else: 64 | keys.append (w.strip()) 65 | print keys 66 | else: 67 | index = None 68 | for i,w in enumerate(splitline(line[1:].strip())): 69 | if i==0: 70 | time = float(Seconds(Time (w, timeunit))) 71 | for index, t in enumerate (data[keys[0]]): 72 | if t > value: 73 | break 74 | elif i<3: 75 | value = float (w) 76 | else: 77 | events[time] = w 78 | #print 'Unprocessed line: %r' % (line) 79 | else: 80 | for i,w in enumerate(splitline(line.strip())): 81 | if i==0: 82 | value = float(Seconds(Time (w, timeunit))) 83 | elif i<3: 84 | value = float (w) 85 | else: 86 | value = w 87 | data[keys[i]].append (value) 88 | for k in keys[:-1]: 89 | data[k] = numpy.array (data[k]) 90 | info['events'] = events 91 | return data, info 92 | 93 | if __name__=='__main__': 94 | import sys 95 | filename = sys.argv[1] 96 | data, info = reader (filename) 97 | print info 98 | print data.keys () 99 | from matplotlib import pyplot as plt 100 | plt.plot (data['time [min]'], data['oxygen [umol/l]']) 101 | plt.show () 102 | #print info 103 | -------------------------------------------------------------------------------- /iocbio/chaco/line_selector_task.py: -------------------------------------------------------------------------------- 1 | 2 | from enthought.traits.api import HasStrictTraits, Instance, Int, DelegatesTo, Bool, on_trait_change, Button, Str, Range 3 | from enthought.chaco.tools.cursor_tool import BaseCursorTool 4 | from enthought.traits.ui.api import View, HSplit, VSplit, Item, VGrid, HGroup, Group, VGroup, Tabbed, RangeEditor 5 | 6 | from .cursor_tool import CursorTool 7 | from .markers import LowerLeftMarker, UpperRightMarker 8 | from .base_viewer_task import BaseViewerTask 9 | 10 | class LineSelectorTask (BaseViewerTask): 11 | 12 | min_x = min_y = Int(0) 13 | max_x = Int; max_y = Int 14 | 15 | corner_xll = Int (editor=RangeEditor (low_name='min_x', high_name='corner_xur', is_float=False)) 16 | corner_yll = Int (editor=RangeEditor (low_name='min_y', high_name='corner_yur', is_float=False)) 17 | 18 | corner_xur = Int (editor=RangeEditor (low_name='corner_xll', high_name='max_x', is_float=False)) 19 | corner_yur = Int (editor=RangeEditor (low_name='corner_yll', high_name='max_y', is_float=False)) 20 | 21 | cursor_xyll = Instance (BaseCursorTool) 22 | cursor_xyur = Instance (BaseCursorTool) 23 | 24 | have_cursors = Bool(False) 25 | visible = Bool(True) 26 | 27 | traits_view = View(VGroup( 28 | Item('visible', label='Visible'), 29 | Item('corner_xll', label='Xll'), 30 | Item('corner_yll', label='Yll'), 31 | Item('corner_xur', label='Xur'), 32 | Item('corner_yur', label='Yur'), 33 | #Item('create_button', show_label = False), 34 | #Item('message', show_label=False, style='readonly'), 35 | )) 36 | 37 | def startup(self): 38 | self._create_cursors() 39 | 40 | def _visible_changed(self): 41 | if self.have_cursors: 42 | b = self.visible 43 | self.cursor_xyll.visible = b 44 | self.cursor_xyur.visible = b 45 | self.viewer.redraw() 46 | 47 | def _max_x_default(self): return self.viewer.data.shape[2] 48 | def _max_y_default(self): return self.viewer.data.shape[1] 49 | 50 | @property 51 | def corner_ll(self): 52 | return self.corner_xll, self.corner_yll 53 | @property 54 | def corner_ur(self): 55 | return self.corner_xur, self.corner_yur 56 | 57 | def _corner_xll_changed(self): 58 | if self.have_cursors: 59 | self.cursor_xyll.current_position = (self.corner_xll, self.corner_yll) 60 | 61 | def _corner_yll_changed(self): 62 | if self.have_cursors: 63 | self.cursor_xyll.current_position = (self.corner_xll, self.corner_yll) 64 | 65 | def _corner_xur_changed(self): 66 | if self.have_cursors: 67 | self.cursor_xyur.current_position = (self.corner_xur, self.corner_yur) 68 | 69 | def _corner_yur_changed(self): 70 | if self.have_cursors: 71 | self.cursor_xyur.current_position = (self.corner_xur, self.corner_yur) 72 | 73 | @on_trait_change('cursor_xyll.current_position') 74 | def _on_cursor_xyll_change(self): 75 | self.corner_xll, self.corner_yll = self.cursor_xyll.current_position 76 | 77 | @on_trait_change('cursor_xyur.current_position') 78 | def _on_cursor_xyur_change(self): 79 | self.corner_xur, self.corner_yur = self.cursor_xyur.current_position 80 | 81 | def _create_cursors(self): 82 | plot_name = 'xy' 83 | plot = self.viewer.plots[plot_name] 84 | a, b = plot_name 85 | 86 | cursor = CursorTool(plot, color='green', marker=LowerLeftMarker(), marker_size=5, threshold=5) 87 | plot.overlays.append (cursor) 88 | cursor.current_position = eval('self.corner_%sll, self.corner_%sll' % (a, b)) 89 | setattr (self, 'cursor_%sll' % (plot_name), cursor) 90 | 91 | cursor = CursorTool(plot, color='green', marker=UpperRightMarker(), marker_size=5, threshold=5) 92 | plot.overlays.append (cursor) 93 | cursor.current_position = eval('self.corner_%sur, self.corner_%sur' % (a, b)) 94 | setattr (self, 'cursor_%sur' % (plot_name), cursor) 95 | 96 | self.have_cursors = True 97 | -------------------------------------------------------------------------------- /iocbio/scanner/sample_clock.py: -------------------------------------------------------------------------------- 1 | 2 | from __future__ import division 3 | 4 | from configuration import sample_clock_max_rate, sample_clock_max_user_rate, \ 5 | sample_clock_min_user_rate, pixel_min_size, pixel_rate_factor,\ 6 | pixel_min_tune_rate, pixel_flyback_rate 7 | 8 | class SampleClock: 9 | 10 | def __init__ (self, pixel_time, pixel_size): 11 | self.pixel_time = pixel_time #sec 12 | self.pixel_size = pixel_size #m 13 | #print self.get_optimal_scanning_parameters() 14 | 15 | def get_key (self): 16 | return (self.__class__.__name__, self.pixel_time, self.pixel_size) 17 | 18 | def __hash__ (self): 19 | return hash(self.get_key ()) 20 | 21 | def get_optimal_scanning_parameters(self, verbose=True): 22 | """ 23 | Returns a 3-tuple: 24 | (samples_per_pixel, clock_rate, min_tune_clock_rate) 25 | """ 26 | ticks_per_pixel_max = int(self.pixel_time * sample_clock_max_rate) 27 | assert ticks_per_pixel_max>0,`ticks_per_pixel_max, pixel_time, sample_clock_max_rate` 28 | samples_per_pixel_min = int(self.pixel_time * sample_clock_min_user_rate) or 1 29 | samples_per_pixel_max = min(int(self.pixel_size / pixel_min_size) or 1, ticks_per_pixel_max) 30 | 31 | pixel_rate = self.pixel_size / self.pixel_time 32 | 33 | if verbose: 34 | print 'Pixel rate: %.3e m/s' % (pixel_rate) 35 | 36 | print 'Flyback ratio: %s' % (pixel_flyback_rate / pixel_rate) 37 | 38 | print 'Samples per pixel range: [%s (to avoid stepping), %s (to avoid stopping)] <= %s (defined by hw clock max rate)' \ 39 | % (samples_per_pixel_min, samples_per_pixel_max, ticks_per_pixel_max) 40 | 41 | if samples_per_pixel_min*pixel_rate_factor > samples_per_pixel_max: 42 | if verbose: 43 | print 'Switching to one sample per one pixel mode' 44 | samples_per_pixel = 1 45 | ticks_per_sample = ticks_per_pixel_max // samples_per_pixel 46 | pixel_rate = sample_clock_max_rate // (samples_per_pixel * ticks_per_sample) 47 | self.clock_rate = pixel_rate 48 | return samples_per_pixel, pixel_rate, pixel_rate 49 | else: 50 | if samples_per_pixel_min > samples_per_pixel_max: 51 | if verbose: 52 | print 'Forcing continuous mirror movement at the expense of extra nof samples.' 53 | samples_per_pixel_max = samples_per_pixel_min 54 | pixel_min_tune_rate_per_pixel = int(pixel_min_tune_rate / self.pixel_size) 55 | if verbose: 56 | print 'Minimal user tuning pixel rate: %s Hz' % (pixel_min_tune_rate_per_pixel) 57 | for samples_per_pixel in range (samples_per_pixel_min, samples_per_pixel_max+1): 58 | ticks_per_sample = ticks_per_pixel_max // samples_per_pixel 59 | next_ticks_per_sample = ticks_per_pixel_max // (samples_per_pixel+1) 60 | if ticks_per_sample == next_ticks_per_sample: 61 | continue 62 | clock_rate = sample_clock_max_rate // (samples_per_pixel * ticks_per_sample) 63 | #print sample_clock_max_rate / clock_rate, clock_rate 64 | # minimal pixel rate that avoids stepping 65 | min_clock_rate = sample_clock_min_user_rate // samples_per_pixel 66 | if verbose: 67 | print 'Samples per pixel: %s, ticks per sample: %s, actual pixel time: %s s, ticks per second: %s, min ticks per second: %s' \ 68 | % (samples_per_pixel, ticks_per_sample, 1/clock_rate, clock_rate, 69 | min_clock_rate) 70 | if pixel_min_tune_rate_per_pixel > min_clock_rate: 71 | break 72 | if verbose: 73 | print 'Flyback ratio: %s (how many times more pixels are needed for flyback compared to line scan)' % (samples_per_pixel_max / samples_per_pixel) 74 | 75 | 76 | self.clock_rate = clock_rate 77 | return samples_per_pixel, clock_rate, max(pixel_min_tune_rate_per_pixel, min_clock_rate) 78 | 79 | def get_flyback (self, samples_per_pixel): 80 | return 81 | 82 | if __name__ == '__main__': 83 | c = SampleClock(pixel_time = 1e-5, pixel_size = 10e-6) 84 | -------------------------------------------------------------------------------- /iocbio/chaco/main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from enthought.etsconfig.api import ETSConfig 3 | print 'Using ETS_TOOLKIT=%s' % (ETSConfig.toolkit) 4 | #ETSConfig.toolkit='wx' # wx, qt4, null 5 | 6 | from enthought.traits.api import HasStrictTraits, Instance, DelegatesTo, List, Str, on_trait_change 7 | from enthought.traits.ui.api import Handler, View, Item, Group, Action, ListEditor, Tabbed, StatusItem 8 | 9 | from iocbio.chaco.base_data_source import BaseDataSource 10 | from iocbio.chaco.base_data_viewer import BaseDataViewer 11 | from iocbio.chaco.image_stack_viewer import ImageStackViewer 12 | from iocbio.chaco.image_timeseries_viewer import ImageTimeseriesViewer 13 | from iocbio.chaco.tiff_data_source import TiffDataSource 14 | from iocbio.chaco.array_data_source import ArrayDataSource 15 | from iocbio.chaco.box_selector_task import BoxSelectorTask 16 | from iocbio.chaco.slice_selector_task import SliceSelectorTask 17 | from iocbio.chaco.fft_viewer_task import FFTViewerTask 18 | from iocbio.chaco.ops_viewer_task import OpsViewerTask 19 | from iocbio.chaco.scale_space_task import ScaleSpaceTask 20 | from iocbio.chaco.points_task import PointsTask 21 | from iocbio.chaco.table_plot_task import TablePlotTask 22 | from iocbio.chaco.line_selector_task import LineSelectorTask 23 | from iocbio.utils import bytes2str 24 | 25 | class ViewHandler (Handler): 26 | 27 | def object_has_data_changed (self, info): 28 | #print 'object_has_data_changed', info.object.has_data, info.object.data_source.kind 29 | if info.object.has_data: 30 | if info.object.data_source.kind=='image_stack': 31 | info.object.data_viewer = None 32 | viewer = ImageStackViewer(data_source = info.object.data_source) 33 | info.object.data_viewer = viewer 34 | viewer.add_task(SliceSelectorTask) 35 | viewer.add_task(BoxSelectorTask) 36 | viewer.add_task(OpsViewerTask) 37 | viewer.add_task(PointsTask) 38 | return 39 | if info.object.data_source.kind=='image_timeseries': 40 | info.object.data_viewer = None 41 | viewer = ImageTimeseriesViewer(data_source = info.object.data_source) 42 | info.object.data_viewer = viewer 43 | viewer.add_task(TablePlotTask) 44 | viewer.add_task(BoxSelectorTask) 45 | #viewer.add_task(SliceSelectorTask) 46 | #viewer.add_task(BoxSelectorTask) 47 | #viewer.add_task(FFTViewerTask) 48 | return 49 | print '%s.object_has_data_changed: notimplemented kind=%r' % (self.__class__.__name__, info.object.data_source.kind) 50 | 51 | object_kind_changed = object_has_data_changed 52 | object_selected_channel_changed = object_has_data_changed 53 | 54 | class ControlPanel (HasStrictTraits): 55 | 56 | data_source = Instance(BaseDataSource) 57 | data_viewer = Instance(BaseDataViewer) 58 | has_data = DelegatesTo('data_source') 59 | kind = DelegatesTo('data_source') 60 | selected_channel = DelegatesTo('data_source') 61 | memusage = DelegatesTo('data_viewer') 62 | status = DelegatesTo('data_viewer') 63 | statusbar = Str 64 | 65 | @on_trait_change('data_viewer.memusage, data_viewer.status') 66 | def update_statusbar(self): 67 | if hasattr (self, 'memusage'): 68 | memusage = bytes2str (self.memusage) 69 | status = self.status 70 | if status: 71 | self.statusbar = 'MEMUSAGE=%s | STATUS: %s' % (memusage, status) 72 | else: 73 | self.statusbar = 'MEMUSAGE=%s' % (memusage) 74 | 75 | traits_view = View (Tabbed(Item("data_source", style='custom', show_label=False, resizable=True), 76 | Item('data_viewer', style='custom', resizable=True, show_label = False), 77 | show_border = True, ), 78 | buttons = ['OK'], 79 | resizable = True, 80 | handler = ViewHandler(), 81 | height = 800, 82 | width = 1000, 83 | statusbar = 'statusbar', 84 | ) 85 | 86 | def analyze (file_name = ''): 87 | control_panel = ControlPanel(data_source = TiffDataSource(file_name=file_name)) 88 | control_panel.configure_traits() 89 | return control_panel 90 | -------------------------------------------------------------------------------- /iocbio/ops/scripts/estimate_snr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | # Author: Pearu Peterson 4 | # Created: September 2009 5 | 6 | from __future__ import division 7 | import os 8 | 9 | ### START UPDATE SYS.PATH ### 10 | ### END UPDATE SYS.PATH ### 11 | 12 | import numpy 13 | from iocbio.optparse_gui import OptionParser 14 | from iocbio.io import ImageStack 15 | from iocbio.io.io import fix_path 16 | from iocbio import utils 17 | from iocbio.ops.script_options import set_estimate_snr_options 18 | 19 | import time 20 | 21 | def runner(parser, options, args): 22 | 23 | if not hasattr(parser, 'runner'): 24 | options.output_path = None 25 | 26 | options.input_path = fix_path(options.input_path) 27 | stack = ImageStack.load(options.input_path, options=options) 28 | voxel_sizes = stack.get_voxel_sizes() 29 | 30 | dr = stack.get_lateral_resolution() 31 | dz = stack.get_axial_resolution() 32 | if dr is not None: 33 | print 'lateral resolution: %.3f um (%.1f x %.1f px^2)' % (1e6*dr, dr/voxel_sizes[1], dr/voxel_sizes[2]) 34 | print 'axial resolution: %.3f um (%.1fpx)' % (1e6*dz, dz / voxel_sizes[0]) 35 | vz,vy,vx = voxel_sizes 36 | m = 1 37 | scales = (m*vz/dz, m*vy/dr, m*vx/dr) 38 | else: 39 | raise NotImplementedError ('get_lateral_resolution') 40 | 41 | kdims = [1+2*(int(numpy.ceil(1/s))//2) for s in scales] 42 | k = 'x'.join (map (str, kdims)) 43 | print 'Averaging window box:', k 44 | 45 | kernel_type = options.kernel 46 | smoothing_method = options.method 47 | boundary_condition = options.boundary 48 | 49 | mn, mx = stack.images.min (), stack.images.max() 50 | high_indices = numpy.where(stack.images >= mn + 0.9*(mx-mn)) 51 | high = stack.images[high_indices] 52 | 53 | from iocbio.ops import regress 54 | average, average_grad = regress (stack.images, scales, 55 | kernel = kernel_type, 56 | method = smoothing_method, 57 | boundary = boundary_condition, 58 | verbose = True, enable_fft=True) 59 | 60 | ImageStack(average, pathinfo=stack.pathinfo).save('average.tif') 61 | noise = stack.images - average 62 | ImageStack(noise-noise.min(), pathinfo=stack.pathinfo).save('noise.tif') 63 | 64 | bright_level = 0.999 *average.max() + 0.001 * average.min() 65 | 66 | bright_indices = numpy.where (average >= bright_level) 67 | print len(bright_indices[0]) 68 | 69 | bright_noise = stack.images[bright_indices] - average[bright_indices] 70 | 71 | a = stack.images[bright_indices].mean() 72 | d = stack.images[bright_indices].std() 73 | print 'mean=',a,'std=',d 74 | print 'peak SNR=',a/d 75 | 76 | 77 | print 'AVERAGE min, max, mean = %s, %s, %s' % (average.min (), average.max (), average.mean ()) 78 | 79 | print numpy.histogram(stack.images)[0] 80 | 81 | sys.exit () 82 | 83 | noise = stack.images - average 84 | 85 | var, var_grad = regress (noise*noise, scales, 86 | kernel = kernel_type, 87 | method = smoothing_method, 88 | boundary = boundary_condition, 89 | verbose = True, enable_fft=True) 90 | 91 | print 'VAR min, max, mean = %s, %s, %s' % (var.min (), var.max (), var.mean ()) 92 | 93 | indices = numpy.where (var > 0) 94 | 95 | print len(numpy.where (var==0)[0]), var.shape, var.dtype 96 | var[numpy.where (var<=0)] = 1 97 | snr = average / numpy.sqrt(var) 98 | snr1 = snr[indices] 99 | print 'STACK min, max = %s, %s' % (mn, mx) 100 | 101 | print 'SNR min, max, mean = %s, %s, %s' % (snr1.min (), snr1.max (), snr1.mean ()) 102 | 103 | 104 | ImageStack(average, pathinfo=stack.pathinfo).save('average.tif') 105 | ImageStack(snr, pathinfo=stack.pathinfo).save('snr.tif') 106 | ImageStack(noise-noise.min(), pathinfo=stack.pathinfo).save('noise.tif') 107 | 108 | def main (): 109 | parser = OptionParser() 110 | set_estimate_snr_options (parser) 111 | if hasattr(parser, 'runner'): 112 | parser.runner = runner 113 | options, args = parser.parse_args() 114 | runner(parser, options, args) 115 | 116 | if __name__ == '__main__': 117 | main() 118 | -------------------------------------------------------------------------------- /iocbio/scanner/configuration.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy 3 | 4 | # Sample clock of NI card (that applies to analog output): 5 | sample_clock_max_rate = 10000000 #Hz 6 | 7 | # Mirrors cannot move faster than 2kHz x 2kHz, so we define maximal 8 | # user sample clock: 9 | sample_clock_max_user_rate = 4000000 #Hz 10 | 11 | # Mirror small angle response time is 100us, ie 10kHz. To achive 12 | # continuous movement of mirrors (that is, not giving time mirrors to 13 | # stabilize), mirror positions should be updated faster than 14 | # 100us. Say, 10 times faster: 15 | sample_clock_min_user_rate = int(10*(1/100e-6)) #Hz 16 | 17 | # Image area is maximal area that can be scanned for an image. 18 | # It depends on the objective. 19 | image_area_width = 623e-6 # m 20 | image_area_height = 623e-6 # m 21 | 22 | # Camera area is normalized image area that is used for 23 | # selecting regions of interest. 24 | camera_area_width = 1000 # au 25 | camera_area_height = 1000 # au 26 | 27 | # Scanner mirror maximal angle corresponding to borders of image 28 | # area. Numeric value of mirror angle corresponds to the voltage value 29 | # given as the input to mirror driver. 30 | mirror_max_user_angle = 4.7 # deg, volts 31 | 32 | # Maximal allowed voltage to mirror driver. 33 | mirror_max_angle = 10 # deg, volts 34 | 35 | # X and Y mirrors offsets are used to center image area to scanning 36 | # area center. 37 | mirror_x_offset = 0.0 # volts 38 | mirror_y_offset = 0.0 # volts 39 | 40 | # Mirror (position detector) short term repeatability is 8urad = 0.45 41 | # mdeg. With total scan range of 10 degrees that corresponds to scan 42 | # area 0.623mm width, the resolution is 10/0.45e-3 = 22222 < 2**16 (NI 43 | # cards resolution). The minimal pixel size corresponding to highest 44 | # resolution of the mirror movement, is 0.028um. So, the maximum 45 | # number of samples per 1um pixel would be 1um / 0.028um = 36, for 46 | # example. 47 | mirror_min_step = 8e-6 * 180/numpy.pi # deg, volts 48 | 49 | # Mirror settling time (step 0.1deg, 99% accuracy). 50 | mirror_settling_time = 100e-6 # sec 51 | 52 | # Mirror large angle settling time, assuming a step 1deg for Y mirror. 53 | mirror_large_angle_settling_time = 200e-6 54 | 55 | def get_mirror_settling_time(angle): 56 | return mirror_large_angle_settling_time + (mirror_large_angle_settling_time - mirror_settling_time)*(abs(angle) - 1)/(1-0.1) 57 | 58 | # Mirror maximim overshoot angle during flyback 59 | mirror_max_overshoot = 1.0 # deg, volts 60 | 61 | # Minimal pixel size defined by the resolution of scanning mirrors. 62 | pixel_min_size = min(image_area_width, image_area_height) * mirror_min_step / mirror_max_user_angle 63 | 64 | # For long pixel times, it is not possible to avoid stepping when 65 | # forcing mirrors minimal steps (which defines memory bounds for 66 | # driver signal). In such cases it is better to have one sample 67 | # per one pixel. Minimal pixel rate is defined as 68 | 69 | pixel_min_rate = pixel_min_size * sample_clock_min_user_rate 70 | 71 | # and if pixel rate (defined as pixel size/pixel time) is 72 | # pixel_rate_factor smaller than minimal pixel rate, then 73 | # the algorithm switches to one sample per one pixel mode. 74 | pixel_rate_factor = 0.1 75 | 76 | # Maximal controlled pixel speed. 77 | pixel_max_rate = 2000 * image_area_width * mirror_max_angle / mirror_max_user_angle 78 | 79 | # For high pixel speeds, mirror driver input needs to be 80 | # tuned to achive desired mirror movement. Minimal tuning pixel rate 81 | # specifies minimal rate that requires tuning. Smaller rates 82 | # are assumed to provide mirror driver input that guarantees 83 | # specified mirror trajectory. The parameter is used for 84 | # estimating smallest clock rate at which tuning algorithm 85 | # starts to iterate. 86 | pixel_min_tune_rate = pixel_max_rate / 10 87 | 88 | # The mirror driver input tuning algorithm uses given number of steps 89 | # between minimal tuning pixel rate and given pixel rate. 90 | mirror_tuning_steps = 4 91 | 92 | # Flyback pixel rate. Flyback should be as fast as possible 93 | # but with reasonable errors. 94 | pixel_flyback_rate = pixel_max_rate / 30 95 | 96 | 97 | 98 | 99 | print ''' 100 | Configuration parameters: 101 | 102 | Hardware sample clock rate: %(sample_clock_max_rate)s Hz 103 | Maximal user sample clock rate: %(sample_clock_max_user_rate)s Hz 104 | Minimal user sample clock rate: %(sample_clock_min_user_rate)s Hz 105 | Minimal pixel size (estimated): %(pixel_min_size).3e m 106 | Minimal pixel rate: %(pixel_min_rate).3e m/s 107 | Maximal pixel rate: %(pixel_max_rate).3e m/s 108 | Minimal tuning pixel rate: %(pixel_min_tune_rate).3e m/s 109 | 110 | ''' % (locals()) 111 | -------------------------------------------------------------------------------- /installer/make_iocbio_installer.sh: -------------------------------------------------------------------------------- 1 | 2 | # Author: Pearu Peterson 3 | # Created: Apr 2011 4 | 5 | export ARCH=32 # 32, 64 6 | 7 | if [ "$1" == "2.6" ] ; then 8 | export PYTHON_VERSION=2.6.6 9 | elif [ "$1" == "2.7" ] ; then 10 | export PYTHON_VERSION=2.7.1 11 | elif [ "$1" == "2.5" ] ; then 12 | export PYTHON_VERSION=2.5.4 13 | else 14 | echo $* 15 | echo 16 | echo "Usage: $0 " 17 | exit 1 18 | export PYTHON_VERSION=2.6.6 # [3.2], 3.1.3, 3.0.1, [2.7.1], 2.6.6, 2.5.4, 2.4.4, 2.3.7 19 | fi 20 | export PYINSTALLER_VERSION=1.5 # 1.5, 1.5-rc1, 1.4 21 | export WXPYTHON_VERSION=2.9.1.1 # 2.9.1.1, 2.8.10.1 (for py2.4) 22 | 23 | PYVER=${PYTHON_VERSION:0:3} 24 | PYVR=${PYTHON_VERSION:0:1}${PYTHON_VERSION:2:1} 25 | WXVER=${WXPYTHON_VERSION:0:3} 26 | 27 | PYINSTALLER_ZIP=http://www.pyinstaller.org/static/source/$PYINSTALLER_VERSION/pyinstaller-$PYINSTALLER_VERSION.zip 28 | 29 | if [ "$ARCH" == "64" ] ; then 30 | PYTHON_INSTALLER=http://www.python.org/ftp/python/$PYTHON_VERSION/python-$PYTHON_VERSION.amd64.msi 31 | PYWIN32_INSTALLER=http://sourceforge.net/projects/pywin32/files/pywin32/Build216/pywin32-216.win-amd64-py$PYVER.exe 32 | else 33 | PYTHON_INSTALLER=http://www.python.org/ftp/python/$PYTHON_VERSION/python-$PYTHON_VERSION.msi 34 | PYWIN32_INSTALLER=http://sourceforge.net/projects/pywin32/files/pywin32/Build216/pywin32-216.win32-py$PYVER.exe 35 | fi 36 | if [ "$WXPYTHON_VERSION" == "2.8.10.1" ] ; then 37 | WXPYTHON_INSTALLER=http://sourceforge.net/projects/wxpython/files/wxPython/2.8.10.1/wxPython2.8-win32-unicode-2.8.10.1-py$PYVR.exe 38 | else 39 | WXPYTHON_INSTALLER=http://sourceforge.net/projects/wxpython/files/wxPython/$WXPYTHON_VERSION/wxPython$WXVER-win32-$WXPYTHON_VERSION-py$PYVR.exe 40 | fi 41 | 42 | START_EXE=/c/windows/command/start.exe 43 | START_EXE="c:\\windows\\command\\start.exe" 44 | test -f $START_EXE || START_EXE="start" 45 | echo "Using START_EXE=$START_EXE" 46 | 47 | export PATH=$PATH:/c/Python$PYVR 48 | PYTHON_EXE=/c/Python$PYVR/python.exe 49 | 50 | test -d work-py$PYVR || mkdir work-py$PYVR 51 | cd work-py$PYVR 52 | 53 | function download { 54 | test -f `basename $1` || wget $1 55 | test -f `basename $1` || (echo "Failed to download $1" && exit 1) 56 | } 57 | 58 | function run_command 59 | { 60 | echo $PATH 61 | cmd /c "echo path=%path%" 62 | echo 63 | cmd /c "dir" 64 | echo "Running command: $*" 65 | cmd /c "$*" 66 | } 67 | 68 | function start_installer { 69 | run_command $START_EXE /W $1 70 | } 71 | 72 | function check_python { 73 | if [ -f $PYTHON_EXE ]; then 74 | echo "\"$PYTHON_EXE\" exists" 75 | else 76 | download $PYTHON_INSTALLER || exit 1 77 | start_installer `basename $PYTHON_INSTALLER` || exit 1 78 | fi 79 | $PYTHON_EXE -c "import sys; print 'Python',sys.version" 80 | } 81 | 82 | function check_win32 { 83 | SUCCESS="YES" 84 | $PYTHON_EXE -c "import win32api" || SUCCESS="NO" 85 | if [ "$SUCCESS" == "NO" ]; then 86 | download $PYWIN32_INSTALLER || exit 1 87 | start_installer `basename $PYWIN32_INSTALLER` 88 | fi 89 | } 90 | 91 | function configure_pyinstaller { 92 | cd pyinstaller-$PYINSTALLER_VERSION 93 | $PYTHON_EXE Configure.py 94 | cd - 95 | } 96 | 97 | function check_pyinstaller { 98 | if [ -d pyinstaller-$PYINSTALLER_VERSION ]; then 99 | echo "\"pyinstaller-$PYINSTALLER_VERSION\" exists" 100 | else 101 | download $PYINSTALLER_ZIP || exit 1 102 | unzip `basename $PYINSTALLER_ZIP` 103 | configure_pyinstaller 104 | fi 105 | 106 | } 107 | 108 | function check_wxpython { 109 | wxVERSION=`$PYTHON_EXE -c "import wx; print wx.VERSION_STRING" || echo "NONE"` 110 | if [ "$wxVERSION" == "NONE" ]; then 111 | check_python 112 | download $WXPYTHON_INSTALLER | exit 1 113 | start_installer `basename $WXPYTHON_INSTALLER` 114 | $PYTHON_EXE -c "import wx; print \"Succesfully installed wxPython\", wx.VERSION_STRING" 115 | else 116 | echo "Found wxPython $wxVERSION" 117 | fi 118 | } 119 | 120 | function make_iocbio_installer_spec 121 | { 122 | $PYTHON_EXE pyinstaller-$PYINSTALLER_VERSION/Makespec.py --onefile ../iocbio_installer.py 123 | } 124 | 125 | 126 | function make_iocbio_installer 127 | { 128 | export PYTHONPATH=pyinstaller-$PYINSTALLER_VERSION 129 | test -f iocbio_installer.spec || (make_iocbio_installer_spec || (configure_pyinstaller && (make_iocbio_installer_spec || exit 1))) 130 | $PYTHON_EXE pyinstaller-$PYINSTALLER_VERSION/Build.py iocbio_installer.spec 131 | mv -v dist/iocbio_installer.exe ../iocbio_installer_py$PYVR.exe 132 | } 133 | 134 | check_python 135 | check_win32 136 | check_pyinstaller 137 | check_wxpython 138 | make_iocbio_installer 139 | 140 | test $? == 0 && echo "$0 OK" || echo "$0 FAILED" 141 | -------------------------------------------------------------------------------- /iocbio/io/scripts/rowfile_plot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- python-mode -*- 3 | # Author: Pearu Peterson 4 | # Created: August 2009 5 | 6 | from __future__ import division 7 | import os 8 | 9 | ### START UPDATE SYS.PATH ### 10 | ### END UPDATE SYS.PATH ### 11 | 12 | import numpy 13 | from iocbio.io import ImageStack 14 | from iocbio.optparse_gui import OptionParser 15 | from iocbio.io.io import fix_path, RowFile 16 | from iocbio.utils import tostr, Options 17 | 18 | def runner (parser, options, args): 19 | 20 | options = Options (options) 21 | 22 | run_method = getattr(parser, 'run_method', 'subcommand') 23 | if os.name=='posix' and run_method == 'subprocess': 24 | print 'This script cannot be run using subprocess method. Choose subcommand to continue.' 25 | return 26 | 27 | if args: 28 | if len (args)==1: 29 | if options.input_path: 30 | print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) 31 | options.input_path = args[0] 32 | 33 | if options.input_path is None: 34 | parser.error('Expected --input-path but got nothing') 35 | 36 | data, titles = RowFile (options.input_path).read(with_titles = True) 37 | if options.print_keys: 38 | print 'rowfile keys:' + ', '.join(data.keys()) 39 | print 'length:', len(data[data.keys()[0]] or []) 40 | return 41 | 42 | if not options.x_keys and not options.y_keys: 43 | options.x_keys = titles[0] 44 | options.y_keys = ','.join(titles[1:]) 45 | parser.save_options(options, []) 46 | 47 | if not options.x_keys or not options.y_keys: 48 | print 'No x or y keys specified for the plot.' 49 | return 50 | 51 | x_keys = [str (k).strip() for k in options.x_keys.split (',')] 52 | y_keys = [str (k).strip() for k in options.y_keys.split (',')] 53 | 54 | from mpl_toolkits.axes_grid.parasite_axes import HostAxes, ParasiteAxes 55 | import matplotlib.pyplot as plt 56 | fig = plt.figure(1, figsize=(12,6)) 57 | host = HostAxes(fig, [0.1, 0.1, 0.55, 0.8]) 58 | host.axis["right"].set_visible(False) 59 | fig.add_axes(host) 60 | 61 | host.set_title(options.input_path) 62 | 63 | legend_list = [] 64 | axes_ylim = [] 65 | plot_axes = [] 66 | 67 | for x_key in x_keys: 68 | x_data = data.get(x_key) 69 | if x_data is None: 70 | print 'Rowfile does not contain a column named %r' % (x_key) 71 | continue 72 | offset = 20 73 | host.set_xlabel(x_key) 74 | for y_key in y_keys: 75 | plot_str = 'plot' 76 | if y_key.startswith('log:'): 77 | y_key = y_key[4:] 78 | plot_str = 'semilogy' 79 | y_data = data.get(y_key) 80 | if y_data is None: 81 | print 'Rowfile does not contain a column named %r' % (y_key) 82 | continue 83 | if axes_ylim: 84 | ax = ParasiteAxes(host, sharex=host) 85 | host.parasites.append(ax) 86 | #ax.axis["right"].set_visible(True) 87 | #ax.axis["right"].major_ticklabels.set_visible(True) 88 | #ax.axis["right"].label.set_visible(True) 89 | new_axisline = ax._grid_helper.new_fixed_axis 90 | ax_line = ax.axis["right2"] = new_axisline(loc="right", 91 | axes=ax, 92 | offset=(offset,0)) 93 | if plot_str=='semilogy': 94 | offset += 60 95 | else: 96 | offset += 40 97 | else: 98 | ax = host 99 | ax_line = ax.axis['left'] 100 | ax.set_ylabel(y_key) 101 | p, = getattr(ax, plot_str)(x_data, y_data, label = y_key) 102 | axes_ylim.append((ax, min (y_data), max (y_data))) 103 | plot_axes.append((p, ax_line)) 104 | [ax.set_ylim(mn,mx) for ax,mn,mx in axes_ylim] 105 | #[ax_line.label.set_color (p.get_color()) for p, ax in plot_axes] 106 | host.legend() 107 | 108 | def on_keypressed(event): 109 | key = event.key 110 | if key=='q': 111 | sys.exit(0) 112 | 113 | fig.canvas.mpl_connect('key_press_event', on_keypressed) 114 | 115 | plt.draw() 116 | 117 | output_path = options.get (output_path='') 118 | if output_path: 119 | plt.savefig (output_path) 120 | print 'wrote',output_path 121 | sys.exit(0) 122 | plt.show() 123 | 124 | def main (): 125 | parser = OptionParser() 126 | from iocbio.io.script_options import set_rowfile_plot_options 127 | set_rowfile_plot_options(parser) 128 | if hasattr(parser, 'runner'): 129 | parser.runner = runner 130 | options, args = parser.parse_args() 131 | runner(parser, options, args) 132 | return 133 | 134 | if __name__=="__main__": 135 | main() 136 | -------------------------------------------------------------------------------- /iocbio/ops/src/minpack/lmdif1.f: -------------------------------------------------------------------------------- 1 | subroutine lmdif1(fcn,m,n,x,fvec,tol,info,iwa,wa,lwa) 2 | integer m,n,info,lwa 3 | integer iwa(n) 4 | double precision tol 5 | double precision x(n),fvec(m),wa(lwa) 6 | external fcn 7 | c ********** 8 | c 9 | c subroutine lmdif1 10 | c 11 | c the purpose of lmdif1 is to minimize the sum of the squares of 12 | c m nonlinear functions in n variables by a modification of the 13 | c levenberg-marquardt algorithm. this is done by using the more 14 | c general least-squares solver lmdif. the user must provide a 15 | c subroutine which calculates the functions. the jacobian is 16 | c then calculated by a forward-difference approximation. 17 | c 18 | c the subroutine statement is 19 | c 20 | c subroutine lmdif1(fcn,m,n,x,fvec,tol,info,iwa,wa,lwa) 21 | c 22 | c where 23 | c 24 | c fcn is the name of the user-supplied subroutine which 25 | c calculates the functions. fcn must be declared 26 | c in an external statement in the user calling 27 | c program, and should be written as follows. 28 | c 29 | c subroutine fcn(m,n,x,fvec,iflag) 30 | c integer m,n,iflag 31 | c double precision x(n),fvec(m) 32 | c ---------- 33 | c calculate the functions at x and 34 | c return this vector in fvec. 35 | c ---------- 36 | c return 37 | c end 38 | c 39 | c the value of iflag should not be changed by fcn unless 40 | c the user wants to terminate execution of lmdif1. 41 | c in this case set iflag to a negative integer. 42 | c 43 | c m is a positive integer input variable set to the number 44 | c of functions. 45 | c 46 | c n is a positive integer input variable set to the number 47 | c of variables. n must not exceed m. 48 | c 49 | c x is an array of length n. on input x must contain 50 | c an initial estimate of the solution vector. on output x 51 | c contains the final estimate of the solution vector. 52 | c 53 | c fvec is an output array of length m which contains 54 | c the functions evaluated at the output x. 55 | c 56 | c tol is a nonnegative input variable. termination occurs 57 | c when the algorithm estimates either that the relative 58 | c error in the sum of squares is at most tol or that 59 | c the relative error between x and the solution is at 60 | c most tol. 61 | c 62 | c info is an integer output variable. if the user has 63 | c terminated execution, info is set to the (negative) 64 | c value of iflag. see description of fcn. otherwise, 65 | c info is set as follows. 66 | c 67 | c info = 0 improper input parameters. 68 | c 69 | c info = 1 algorithm estimates that the relative error 70 | c in the sum of squares is at most tol. 71 | c 72 | c info = 2 algorithm estimates that the relative error 73 | c between x and the solution is at most tol. 74 | c 75 | c info = 3 conditions for info = 1 and info = 2 both hold. 76 | c 77 | c info = 4 fvec is orthogonal to the columns of the 78 | c jacobian to machine precision. 79 | c 80 | c info = 5 number of calls to fcn has reached or 81 | c exceeded 200*(n+1). 82 | c 83 | c info = 6 tol is too small. no further reduction in 84 | c the sum of squares is possible. 85 | c 86 | c info = 7 tol is too small. no further improvement in 87 | c the approximate solution x is possible. 88 | c 89 | c iwa is an integer work array of length n. 90 | c 91 | c wa is a work array of length lwa. 92 | c 93 | c lwa is a positive integer input variable not less than 94 | c m*n+5*n+m. 95 | c 96 | c subprograms called 97 | c 98 | c user-supplied ...... fcn 99 | c 100 | c minpack-supplied ... lmdif 101 | c 102 | c argonne national laboratory. minpack project. march 1980. 103 | c burton s. garbow, kenneth e. hillstrom, jorge j. more 104 | c 105 | c ********** 106 | integer maxfev,mode,mp5n,nfev,nprint 107 | double precision epsfcn,factor,ftol,gtol,xtol,zero 108 | data factor,zero /1.0d2,0.0d0/ 109 | info = 0 110 | c 111 | c check the input parameters for errors. 112 | c 113 | if (n .le. 0 .or. m .lt. n .or. tol .lt. zero 114 | * .or. lwa .lt. m*n + 5*n + m) go to 10 115 | c 116 | c call lmdif. 117 | c 118 | maxfev = 200*(n + 1) 119 | ftol = tol 120 | xtol = tol 121 | gtol = zero 122 | epsfcn = zero 123 | mode = 1 124 | nprint = 0 125 | mp5n = m + 5*n 126 | call lmdif(fcn,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn,wa(1), 127 | * mode,factor,nprint,info,nfev,wa(mp5n+1),m,iwa, 128 | * wa(n+1),wa(2*n+1),wa(3*n+1),wa(4*n+1),wa(5*n+1)) 129 | if (info .eq. 8) info = 4 130 | 10 continue 131 | return 132 | c 133 | c last card of subroutine lmdif1. 134 | c 135 | end 136 | -------------------------------------------------------------------------------- /iocbio/ops/src/discrete_gauss.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "discrete_gauss.h" 8 | 9 | 10 | int dg_convolve(double *seq, int n, double t) 11 | { 12 | int k; 13 | double c; 14 | double *fseq = (double*)malloc(n*sizeof(double)); 15 | fftw_plan plan = fftw_plan_r2r_1d(n, seq, fseq, FFTW_R2HC, FFTW_ESTIMATE); 16 | fftw_plan iplan = fftw_plan_r2r_1d(n, fseq, seq, FFTW_HC2R, FFTW_ESTIMATE); 17 | fftw_execute(plan); 18 | /* real part: */ 19 | fseq[0] /= n; /* DC component */ 20 | for (k = 1; k < (n+1)/2; ++k) /* (k < N/2 rounded up) */ 21 | { 22 | c = exp((cos((2.0*M_PI*k)/n)-1.0)*t)/n; 23 | fseq[k] *= c; // real part 24 | fseq[n-k] *= c; // imaginary part 25 | } 26 | if (n % 2 == 0) /* N is even */ 27 | fseq[n/2] *= exp((cos((2.0*M_PI*(n/2))/n)-1.0)*t)/n; /* Nyquist freq. */ 28 | fftw_execute(iplan); 29 | fftw_destroy_plan(plan); 30 | fftw_destroy_plan(iplan); 31 | free(fseq); 32 | return 0; 33 | } 34 | 35 | int dg_DGR2HCConfig_init(DGR2HCConfig *config, int rank, int dims[3], int howmany) 36 | { 37 | int i, sz; 38 | fftw_r2r_kind *r2hckinds = NULL; 39 | fftw_r2r_kind *hc2rkinds = NULL; 40 | config->rank = rank; 41 | r2hckinds = (fftw_r2r_kind*)malloc(rank*sizeof(fftw_r2r_kind)); 42 | hc2rkinds = (fftw_r2r_kind*)malloc(rank*sizeof(fftw_r2r_kind)); 43 | sz = 1; 44 | for (i=0; idims[i] = dims[i]; 48 | r2hckinds[i] = FFTW_R2HC; 49 | hc2rkinds[i] = FFTW_HC2R; 50 | } 51 | config->howmany = howmany; 52 | config->sz = sz; 53 | config->rdata = (double*)fftw_malloc((sz*howmany)*sizeof(double)); 54 | config->hcdata = (double*)fftw_malloc((sz*howmany)*sizeof(double)); 55 | config->r2hc_plan = fftw_plan_many_r2r(rank, // rank 56 | config->dims, // n 57 | howmany, // howmany 58 | config->rdata, // in 59 | NULL, // inembed 60 | 1, // istride 61 | sz, // idist 62 | config->hcdata, NULL, 1, sz, 63 | r2hckinds, 64 | FFTW_ESTIMATE); 65 | config->hc2r_plan = fftw_plan_many_r2r(rank, // rank 66 | config->dims, // n 67 | howmany, // howmany 68 | config->hcdata, // in 69 | NULL, // inembed 70 | 1, // istride 71 | sz, // idist 72 | config->rdata, NULL, 1, sz, 73 | hc2rkinds, 74 | FFTW_ESTIMATE); 75 | free(r2hckinds); 76 | free(hc2rkinds); 77 | return 0; 78 | } 79 | 80 | int dg_DGR2HCConfig_clean(DGR2HCConfig *config) 81 | { 82 | if (config->sz==0) 83 | return 0; 84 | fftw_destroy_plan(config->r2hc_plan); 85 | fftw_destroy_plan(config->hc2r_plan); 86 | if (config->rdata != NULL) 87 | fftw_free(config->rdata); 88 | if (config->hcdata != NULL) 89 | fftw_free(config->hcdata); 90 | if (config->kernel_real != NULL) 91 | free(config->kernel_real); 92 | if (config->kernel_imag != NULL) 93 | free(config->kernel_imag); 94 | config->rdata = NULL; 95 | config->hcdata = NULL; 96 | config->kernel_real = NULL; 97 | config->kernel_imag = NULL; 98 | config->sz = config->rank = config->howmany = 0; 99 | return 0; 100 | } 101 | 102 | int dg_DGR2HCConfig_apply_real_filter(DGR2HCConfig *config) 103 | { 104 | int m, k; 105 | int n = config->dims[0]; 106 | assert(config->rank==1); 107 | for (m=0; mhowmany; ++m) 108 | { 109 | (config->hcdata+m*n)[0] *= config->kernel_real[0]; 110 | for (k = 1; k < (n+1)/2; ++k) /* (k < N/2 rounded up) */ 111 | { 112 | (config->hcdata+m*n)[k] *= config->kernel_real[k]; // real part 113 | (config->hcdata+m*n)[n-k] *= config->kernel_real[k]; // imaginary part 114 | } 115 | if (n % 2 == 0) /* N is even */ 116 | (config->hcdata+m*n)[n/2] *= config->kernel_real[n/2]; /* Nyquist freq. */ 117 | } 118 | return 0; 119 | } 120 | 121 | int dg_high_pass_filter_init(DGR2HCConfig *config, int rank, int dims[3], int howmany, double scale_parameter) 122 | { 123 | int k; 124 | dg_DGR2HCConfig_init(config, rank, dims, howmany); 125 | config->kernel_real = (double*)malloc(config->sz*sizeof(double)); 126 | config->kernel_imag = NULL; 127 | assert(rank==1); // todo: generalize to rank 2 and 3 128 | for (k=0; k<(dims[0]+1)/2; ++k) 129 | config->kernel_real[k] = (1.0-exp((cos((2.0*M_PI*k)/dims[0])-1.0)*scale_parameter))/dims[0]; 130 | return 0; 131 | } 132 | 133 | int dg_high_pass_filter_clean(DGR2HCConfig *config) 134 | { 135 | return dg_DGR2HCConfig_clean(config); 136 | } 137 | 138 | int dg_high_pass_filter_apply(DGR2HCConfig *config, double *seq) 139 | { 140 | memcpy(config->rdata, seq, config->sz*config->howmany*sizeof(double)); 141 | fftw_execute(config->r2hc_plan); 142 | dg_DGR2HCConfig_apply_real_filter(config); 143 | fftw_execute(config->hc2r_plan); 144 | memcpy(seq, config->rdata, config->sz*config->howmany*sizeof(double)); 145 | return 0; 146 | } 147 | 148 | int dg_high_pass_filter(double *seq, int n, int rows, double t) 149 | { 150 | DGR2HCConfig config; 151 | int dims[3] = {n,1,1}; 152 | dg_high_pass_filter_init(&config, 1, dims, rows, t); 153 | dg_high_pass_filter_apply(&config, seq); 154 | dg_high_pass_filter_clean(&config); 155 | return 0; 156 | } 157 | -------------------------------------------------------------------------------- /iocbio/chaco/slice_selector_task.py: -------------------------------------------------------------------------------- 1 | 2 | from enthought.traits.api import HasStrictTraits, Instance, Int, Bool, on_trait_change, Range, Tuple 3 | from enthought.traits.ui.api import View, HSplit, VSplit, Item, VGrid, HGroup, Group, VGroup, Tabbed 4 | from enthought.chaco.tools.cursor_tool import BaseCursorTool 5 | from .cursor_tool import CursorTool 6 | from .base_viewer_task import BaseViewerTask 7 | from .base_data_viewer import BaseDataViewer 8 | 9 | 10 | class SliceSelectorTask(BaseViewerTask): 11 | 12 | # indices of plane slices 13 | min_x = min_y = min_z = Int(0) 14 | max_x = Int; max_y = Int; max_z = Int 15 | value_x = Int; value_y = Int; value_z = Int 16 | slice_x = Range(low='min_x', high='max_x', value='value_x') 17 | slice_y = Range(low='min_y', high='max_y', value='value_y') 18 | slice_z = Range(low='min_z', high='max_z', value='value_z') 19 | 20 | last_slice = Tuple (Int, Int, Int) 21 | 22 | # cursors for plane slice 23 | cursor_xy = Instance (BaseCursorTool) 24 | cursor_xz = Instance (BaseCursorTool) 25 | cursor_zy = Instance (BaseCursorTool) 26 | 27 | have_cursors = Bool(False) 28 | visible = Bool(True) 29 | 30 | traits_view = View(VGroup( 31 | Item('visible', label='Visible'), 32 | Item('slice_x', label='X'), 33 | Item('slice_y', label='Y'), 34 | Item('slice_z', label='Z'), 35 | )) 36 | 37 | def _max_x_default(self): return self.viewer.data.shape[2]-1 38 | def _max_y_default(self): return self.viewer.data.shape[1]-1 39 | def _max_z_default(self): return self.viewer.data.shape[0]-1 40 | def _value_z_default (self): return self.viewer.data.shape[0]//2 41 | def _value_y_default (self): return self.viewer.data.shape[1]//2 42 | def _value_x_default (self): return self.viewer.data.shape[2]//2 43 | 44 | def reset_slices(self): 45 | self.set_slices (*self.last_slice) 46 | 47 | def set_slices (self, z, y, x): 48 | self.last_slice = (z, y, x) 49 | if self.viewer.shifted_view: 50 | z = self.viewer.ifftshift (z, self.viewer.data.shape[0]) 51 | y = self.viewer.ifftshift (y, self.viewer.data.shape[1]) 52 | x = self.viewer.ifftshift (x, self.viewer.data.shape[2]) 53 | self.set(slice_x=x, slice_y=y, slice_z=z) 54 | self.viewer.reset() 55 | 56 | def startup(self): 57 | self._create_cursors() 58 | self.viewer.select_zy_slice (self.slice_x) 59 | self.viewer.select_xz_slice (self.slice_y) 60 | self.viewer.select_xy_slice (self.slice_z) 61 | 62 | def _visible_changed(self): 63 | if self.have_cursors: 64 | b = self.visible 65 | self.cursor_xy.visible = b 66 | self.cursor_xz.visible = b 67 | self.cursor_zy.visible = b 68 | self.viewer.redraw() 69 | 70 | def _create_cursors(self): 71 | slice_dict = dict(x=self.slice_x, y=self.slice_y, z=self.slice_z) 72 | for plot_name in ['xy', 'xz', 'zy']: 73 | a1, a2 = plot_name 74 | 75 | plot = self.viewer.plots[plot_name] 76 | default_slice = (slice_dict[a1], slice_dict[a2]) 77 | 78 | cursor = CursorTool(plot, color='red', threshold=3, marker_size = 1) 79 | plot.overlays.append(cursor) 80 | cursor.current_position = default_slice 81 | setattr (self, 'cursor_%s' % (plot_name), cursor) 82 | 83 | self.have_cursors = True 84 | 85 | def _slice_x_changed (self, old, new): 86 | if new < 0 or new >= self.viewer.data.shape[2]: 87 | self.slice_x = old 88 | return 89 | if self.have_cursors: 90 | self.cursor_xy.current_position = (self.slice_x, self.slice_y) 91 | self.cursor_xz.current_position = (self.slice_x, self.slice_z) 92 | 93 | self.viewer.select_zy_slice (self.slice_x) 94 | 95 | def _slice_y_changed (self, old, new): 96 | if new < 0 or new >= self.viewer.data.shape[1]: 97 | self.slice_y = old 98 | return 99 | if self.have_cursors: 100 | self.cursor_xy.current_position = (self.slice_x, self.slice_y) 101 | self.cursor_zy.current_position = (self.slice_z, self.slice_y) 102 | 103 | self.viewer.select_xz_slice (self.slice_y) 104 | 105 | def _slice_z_changed (self, old, new): 106 | if new < 0 or new >= self.viewer.data.shape[0]: 107 | self.slice_z = old 108 | return 109 | if self.have_cursors: 110 | self.cursor_xz.current_position = (self.slice_x, self.slice_z) 111 | self.cursor_zy.current_position = (self.slice_z, self.slice_y) 112 | 113 | self.viewer.select_xy_slice (self.slice_z) 114 | 115 | 116 | @on_trait_change('cursor_xy.current_position') 117 | def _on_cursor_xy_change(self): 118 | self.slice_x, self.slice_y = self.cursor_xy.current_position 119 | 120 | @on_trait_change('cursor_xz.current_position') 121 | def _on_cursor_xz_change(self): 122 | self.slice_x, self.slice_z = self.cursor_xz.current_position 123 | 124 | @on_trait_change('cursor_zy.current_position') 125 | def _on_cursor_zy_change(self): 126 | self.slice_z, self.slice_y = self.cursor_zy.current_position 127 | --------------------------------------------------------------------------------