├── .gitignore ├── README.md ├── ccm.py ├── csv2sqlite.py ├── doc └── nichkawde_summary.tex ├── example ├── existing_sim_analysis │ ├── README.md │ ├── generate_jobs.py │ ├── plot_heatmaps.R │ ├── plot_heatmaps.py │ ├── plot_lags.py │ └── run_job.py └── existing_sim_plots │ ├── generate_plot_jobs.py │ ├── interactive_plots.py │ ├── plot_timeseries.html │ ├── plot_timeseries.py │ └── run_plot_job.py ├── jsonobject.py ├── models.py ├── models_pypy.py ├── npybuffer.py ├── optimal_embedding ├── COPYING ├── INSTALL ├── Makefile ├── Makefile.in ├── README ├── autoscan.log ├── bins.sh ├── configure ├── configure.in ├── configure.scan ├── examples │ ├── chua.dat │ ├── chua_1.gnu │ ├── chua_2.gnu │ ├── chua_fdc.amp │ ├── mcgl17.dat │ ├── mcgl_1.gnu │ └── mcgl_2.gnu ├── index.html ├── install-sh ├── logo └── source_c │ ├── Makefile │ ├── Makefile.in │ ├── costfunc.c │ └── routines │ ├── Makefile │ ├── Makefile.in │ ├── arima.tgz │ ├── check_alloc.c │ ├── check_option.c │ ├── diffc.log │ ├── diffh.log │ ├── eigen.c │ ├── exclude_interval.c │ ├── find_multi_neighbors.c │ ├── find_neighbors.c │ ├── get_multi_series.c │ ├── get_series.c │ ├── invert_matrix.c │ ├── make_box.c │ ├── make_multi_box.c │ ├── make_multi_box2.c │ ├── make_multi_index.c │ ├── myfgets.c │ ├── rand.c │ ├── rand_arb_dist.c │ ├── rescale_data.c │ ├── scan_help.c │ ├── search_datafile.c │ ├── solvele.c │ ├── test_outfile.c │ ├── tisean_cec.h │ ├── tsa.h │ ├── variance.c │ └── what_i_do.c ├── projection.py ├── pyembedding.py ├── statutils.py └── uzalcost.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .DS_Store 3 | *~ 4 | *.pyc 5 | *.o 6 | *.png 7 | *.json 8 | *.log 9 | *_old* 10 | *.status 11 | costfunc 12 | *.a 13 | *.sqlite 14 | work -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyembedding 2 | 3 | Ed Baskerville 4 | last update: 26 February 2015 5 | 6 | NB: Usage instructions out of date but repo is published for the sake of reproducibility for paper. 7 | 8 | ## Overview 9 | 10 | This package contains a Python implementation of nonlinear time-series embedding methods. 11 | 12 | ## Installation 13 | 14 | Requires Python 2.7.x with numpy and scipy. 15 | 16 | Recommended way to install Python: 17 | * [Anaconda distribution](http://continuum.io/downloads) 18 | 19 | After you have installed Anaconda and configured your `PATH` environment variable, make 20 | sure that 21 | 22 | ```{sh} 23 | $ python --version 24 | ``` 25 | 26 | includes the word "Anaconda" in the description. 27 | 28 | ## ccm.py 29 | 30 | The script `ccm.py` automates the method of convergent cross-mapping (TODO: ref Sugihara et al.). 31 | 32 | Run 33 | ```{sh} 34 | ccm.py --help 35 | ``` 36 | to see detailed usage information. 37 | 38 | Example: 39 | ```{sh} 40 | ccm.py --n-cores 4 -E 4 -t 1 -L "5:50:5" -R 100 -C "x,y" -V "x:y,y:x" input.sqlite timeseries output.sqlite 41 | ``` 42 | will read time-series data from columns `x` and `y` (`-C "x,y"`) in table `timeseries` 43 | in the SQLite database `input.sqlite`; test causality for `x` causing `y` as well as 44 | `y` causing `x`; and write output to the file `output.sqlite`; using these parameters: 45 | * embedding dimension: 4 (`-E 4`) 46 | * lag (tau): 1 (`-t 1`) 47 | * library lengths: 5, 10, ..., 45, 50 (`-L "5:50:5"`) 48 | * replicate samples per library length: 100 (`-R 100`) 49 | 50 | The output database will contain two tables: 51 | * `args`: contains the arguments used to run the program 52 | * `results`: contains analysis results. 53 | 54 | The `results` table contains these columns: 55 | * `cause`: the variable being tested as cause 56 | * `effect`: the variable being tested as effect 57 | * `L`: the library length being tested 58 | * `replicate_id`: unique ID for this replicate 59 | * `corr`: the correlation between the original "cause" time series and the version 60 | reconstructed from lagged vectors sampled from "effect". 61 | 62 | ## API 63 | 64 | TODO 65 | -------------------------------------------------------------------------------- /csv2sqlite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | import csv 6 | import json 7 | import sqlite3 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | 11 | def dbExecute(c, sqlCmd, args=None): 12 | # print(sqlCmd) 13 | if args is not None: 14 | # print(args) 15 | c.execute(sqlCmd, args) 16 | else: 17 | c.execute(sqlCmd) 18 | 19 | if __name__ == '__main__': 20 | if len(sys.argv) < 4: 21 | print('Usage: {0} '.format(__file__)) 22 | 23 | csvFilename = sys.argv[1] 24 | dbFilename = sys.argv[2] 25 | tableName = sys.argv[3] 26 | 27 | with open(csvFilename, 'rU') as csvFile: 28 | cr = csv.reader(csvFile) 29 | colNames = cr.next() 30 | 31 | with sqlite3.connect(dbFilename) as db: 32 | c = db.cursor() 33 | 34 | createCmd = 'CREATE TABLE {0} ({1})'.format(tableName, ', '.join(colNames)) 35 | dbExecute(c, createCmd) 36 | 37 | for row in cr: 38 | insertCmd = 'INSERT INTO {0} VALUES ({1})'.format( 39 | tableName, ','.join(['?'] * len(row)) 40 | ) 41 | dbExecute(c, insertCmd, [None if x == '' else x for x in row]) 42 | -------------------------------------------------------------------------------- /doc/nichkawde_summary.tex: -------------------------------------------------------------------------------- 1 | \documentclass[10pt]{article} 2 | 3 | \usepackage{amsmath} 4 | \usepackage{amssymb} 5 | 6 | \newcommand{\bx}{\mathbf{x}} 7 | \newcommand{\bX}{\mathbf{X}} 8 | \newcommand{\btau}{\boldsymbol{\tau}} 9 | \newcommand{\reals}{\mathbb{R}} 10 | 11 | \title{Summary of Nichkawde embedding method} 12 | \author{Ed Baskerville} 13 | \date{10 September 2015} 14 | 15 | \begin{document} 16 | 17 | \maketitle 18 | 19 | 20 | \section{Summary} 21 | 22 | The idea of the method is to iteratively add dimensions to a time-delay embedding in a way that the new time-delay dimension maximizes the (average) distance, in the newly added dimension, to nearest neighbors in the existing embedding, per unit of change in the direction of each point's respective nearest neighbor. That is, the goal is to maximize the derivative of the new dimension in the direction of existing nearest neighbors. Hence the name: Maximizing Derivatives On Projection (MDOP). 23 | 24 | \section{Algorithm} 25 | 26 | Given a (discretized) time series $x_1, \ldots, x_n$, the goal is to construct a (discretized) embedding $\bX = \{ \bx_D, \ldots, \bx_n \}$, a set of points $\bx_i \in \reals^d$. The value $D$ is the maximum embedding dimension, and $d$ is the actual embedding dimension used. 27 | 28 | The embedding is defined by a subset $\btau = \{ \tau_1, \ldots, \tau_d \}$ of $\{0, \ldots, D - 1 \}$ of size $d$, such that 29 | 30 | \begin{align} 31 | \bx_i &= \{ x_{i - \tau_1}, \ldots , x_{i - \tau_d} \} 32 | \end{align} 33 | 34 | \subsection{Identifying the maximum embedding dimension} 35 | 36 | TODO: implement this; expand description. The maximum embedding dimension $D$ is chosen to be the dimension where a complete embedding has the minimum value of the Uzal cost function $L_k$. 37 | 38 | \subsection{Identifying the minimum time between nearest neighbors} 39 | 40 | TODO 41 | 42 | \subsection{Identifying the delay subset} 43 | 44 | Delays are chosen iteratively using MDOP. The first delay is always chosen to be $\tau_1 = 0$. 45 | 46 | The final delay is always chosen to be $\tau_d = D - 1$. The algorithm terminates when $D - 1$ is added to the delay set. 47 | 48 | Given a partial subset of delays $\btau_k$ whose last entry is $\tau_k < D - 1$, the next entry $\tau_{k+1}$ is chosen like so: 49 | 50 | \begin{enumerate} 51 | 52 | \item Identify the nearest neighbor $j$ for each point $i$ in the partial embedding defined by $\btau_k$, along with the Euclidean distance to that neighbor $\delta_{ijk}$. 53 | 54 | \item For each $\tau$, $\tau_{i + 1} < \tau \leq D - 1$, calculate the harmonic mean $\beta(\tau)$ of the directional derivative across points in the partial embedding defined by $\btau$: 55 | 56 | \begin{enumerate} 57 | 58 | \item Calculate the distance between each point $i$ and its nearest neighbor $j$ in the partial embedding, in the dimension defined by $\tau$, 59 | \begin{align} 60 | \delta_{ij}(\tau) &= | x_{i - \tau} - x_{j - \tau} | \, . 61 | \end{align} 62 | \item Calculate the directional derivative $\phi_{ij}'(\tau)$ for each point $i$: 63 | \begin{align} 64 | \phi_{ij}'(\tau) &= \frac{\delta_{ij}(\tau)}{\delta_{ijk}} 65 | \end{align} 66 | \item Calculate the harmonic mean directional derivative across points: 67 | \begin{align} 68 | \beta(\tau) &= \exp \left[ 69 | \frac{1}{n - D + 1} 70 | \sum_{i=D}^n \log \phi_{ij}'(\tau) 71 | \right] 72 | \end{align} 73 | \item Choose the $\tau$ with maximum $\beta(\tau)$: $\btau_{k+1} = \btau_k \cup \left\{ \tau \right\}$. 74 | 75 | 76 | \end{enumerate} 77 | 78 | \end{enumerate} 79 | 80 | \end{document} 81 | -------------------------------------------------------------------------------- /example/existing_sim_analysis/README.md: -------------------------------------------------------------------------------- 1 | # Analysis scripts for existing simulations 2 | 3 | The scripts in this directory are used to perform CCM analyses for simulations already 4 | present in an output database (see example/simulation). The following sections describe 5 | the steps required to run an analysis. 6 | 7 | ## Get the code 8 | 9 | ```{sh} 10 | mkdir 2015-11-11-analysis 11 | cd 2015-11-11-analysis 12 | git clone git@bitbucket.org:cobeylab/pyembedding.git 13 | cp pyembedding/example/existing_sim_analysis/* . 14 | ``` 15 | 16 | ## Modify generate_jobs.py 17 | 18 | Modify `generate_jobs.py` to contain desired settings. Make sure `simulation_db_path` is set to the 19 | actual absolute path of the simulation database. 20 | 21 | ## Modify generate_jobs.py for a test run 22 | 23 | Modify generate_jobs.py with `n_replicates = 1` as a test. This will ensure that 24 | only the first replicate from each parameter combination will be used from the simulation 25 | database. 26 | 27 | ## Run generate_jobs.py 28 | 29 | ```{sh} 30 | ./generate_jobs.py 31 | ``` 32 | 33 | This will create a directory called `jobs` containing subdirectories for each simulation 34 | run; these are used as working directories for the analysis. 35 | 36 | ## Test a single job manually 37 | 38 | Using a single processor, manually use the `run_job.py` script to make sure things work 39 | for a single run. E.g.: 40 | 41 | ``` 42 | sinteractive 43 | cd jobs/eps=0.0-beta00=0.30-sigma01=1.00-sd_proc=0.100/000 44 | ../../../run_job.py 45 | ``` 46 | 47 | The `run_job.py` script knows to load information from the `runmany_info.json` file in the 48 | current working directory, so it doesn't need any arguments; it just needs to run 49 | in the right place. 50 | 51 | ## Test the 1-replicate sweep 52 | 53 | Use `runmany` to run a sweep: 54 | 55 | ```{sh} 56 | runmany slurm ccm jobs chunks 57 | ``` 58 | 59 | ## Gather jobs together 60 | 61 | ```{sh} 62 | gather jobs results_gathered.sqlite 63 | ``` 64 | 65 | ## Set up the real thing 66 | 67 | Remove the test `jobs` and `chunks` directories: 68 | 69 | ```{sh} 70 | rm -r jobs 71 | rm -r chunks 72 | rm results_gathered.sqlite 73 | ``` 74 | 75 | and then modify `generate_jobs.py` to have `N_REPLICATES = 100`. 76 | 77 | Then, re-run things for real: 78 | 79 | ```{sh} 80 | ./generate_jobs.py 81 | runmany slurm ccm jobs chunks 82 | gather jobs results_gathered.sqlite 83 | ``` 84 | -------------------------------------------------------------------------------- /example/existing_sim_analysis/generate_jobs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | import random 6 | import sqlite3 7 | from collections import OrderedDict 8 | import json 9 | 10 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 11 | 12 | sys.path.append(os.path.join(SCRIPT_DIR, 'pyembedding')) 13 | import uzalcost 14 | 15 | # Simulations database: make sure this is an absolute path 16 | #SIM_DB_PATH = '/Users/ebaskerv/uchicago/midway_cobey/ccmproject-storage/2015-10-23-simulations/results_gathered.sqlite' 17 | SIM_DB_PATH = '/project/cobey/ccmproject-storage/2015-10-23-simulations/results_gathered.sqlite' 18 | 19 | # Must be less than or equal to the number of replicates in the sim db (100). 20 | # If less than 100, will only use the first N_REPLICATES replicates 21 | #N_REPLICATES = 100 22 | N_REPLICATES = 1 23 | 24 | def get_ccm_settings(): 25 | simulation_samples_per_year = 36 # This is an assumption about the time series being loaded; don't change 26 | # unless a new simulation DB is being used with different settings. 27 | # 36 implies 10-day samples in a 360-day year in the original simulations. 28 | 29 | timeseries_x_label = 'time (years)' # Labels for time-series plot. Rewrite to match settings 30 | timeseries_y_label= 'monthly cases' # below. 31 | 32 | years = 100 # Number of years to use at end of time series 33 | 34 | ccm_samples_per_year = 12 # E.g., 12 implies 30-day samples in a 360-day year. 35 | # Must divide evenly into SIMULATION_SAMPLES_PER_YEAR 36 | 37 | max_theiler_window = 60 # Maximum window for exclude nearest neighbors temporally 38 | 39 | max_prediction_horizon = 120 # Twice the Theiler window is used to set the prediction 40 | # horizon for the Uzal cost function; it is also bounded 41 | # by this value. 42 | 43 | variable_name = 'C' # Can also be 'logS' or 'logI'. 44 | 45 | add_samples = True # If True, uses *sum* of original samples for analysis 46 | # rather than throwing out intervening samples. 47 | # For C (cases), this should probably be True, since it's a 48 | # measure of cumulative cases during a time period. 49 | 50 | log_transform = False # If True, takes the natural log of samples. 51 | # If ADD_SAMPLES is True, then this is applied *after* 52 | # adding samples together. 53 | 54 | first_difference = False # If True, first-differences time series. 55 | # This is applied after ADD_SAMPLES and LOG_TRANSFORM. 56 | 57 | standardize = False # If True, each time series is standardized to mean=0, sd=1. 58 | # This is applied after all other transformations. 59 | 60 | # Runs Uzal cost function to find upper bound on Nichkawde embedding lags, and then does bootstrapped CCM 61 | # at Lmin, Lmax for that embedding 62 | # embedding_algorithm = 'uzal_nichkawde' 63 | # uzal_factor = 2.0 # Multiplies Uzal upper bound by this much 64 | # override_uzal_upper_bound = None # If not None, skip Uzal algorithm and use this Nichkawde bound instead 65 | 66 | # Runs all valid E/tau combinations: SWEEP_EMBEDDING_DIMENSIONS x SWEEP_DELAYS 67 | # embedding_algorithm = 'uniform_sweep' 68 | 69 | # Searches for E/tau combination with highest CCM rho at Lmax, and then does bootstrapped CCM 70 | # at Lmin, Lmax for chosen E/tau combinations 71 | # embedding_algorithm = 'max_ccm_rho' 72 | 73 | # Searches for E/tau combination with highest univariate prediction for effect variable, and then does bootstrapped CCM 74 | # at Lmin, Lmax for chosen E/tau combinations 75 | embedding_algorithm = 'max_univariate_prediction' 76 | 77 | # These lists control the uniform_sweep, max_ccm_rho, and max_univariate_prediction modes above 78 | sweep_embedding_dimensions = range(1, 11) 79 | sweep_delays = [1, 2, 4] 80 | 81 | n_ccm_bootstraps = 1000 82 | 83 | return locals() 84 | 85 | RUNMANY_INFO_TEMPLATE = OrderedDict([ 86 | ('executable', os.path.join(SCRIPT_DIR, 'run_job.py')), 87 | ('minutes', 30), 88 | ('megabytes', 2000), 89 | ('simulation_db_path', SIM_DB_PATH), 90 | ('ccm_settings', get_ccm_settings()) 91 | ]) 92 | 93 | def main(): 94 | jobs_dir = os.path.join(SCRIPT_DIR, 'jobs') 95 | seed_rng = random.SystemRandom() 96 | 97 | if os.path.exists(jobs_dir): 98 | sys.stderr.write('{} already exists; aborting.\n'.format(jobs_dir)) 99 | sys.exit(1) 100 | 101 | if not os.path.exists(SIM_DB_PATH): 102 | sys.stderr.write('simulations DB not present; aborting.\n') 103 | sys.exit(1) 104 | 105 | # Make sure uzal costfunc binary has been built 106 | sys.stderr.write('Ensuring costfunc binary has been built...\n') 107 | uzalcost.set_up_uzal_costfunc() 108 | 109 | with sqlite3.connect(SIM_DB_PATH) as db: 110 | for job_id, job_subdir, eps, beta00, sigma01, sd_proc, replicate_id, random_seed in db.execute( 111 | 'SELECT * FROM job_info WHERE replicate_id < ?', [N_REPLICATES] 112 | ): 113 | job_dir = os.path.join(SCRIPT_DIR, job_subdir) 114 | sys.stderr.write('{0}\n'.format(job_dir)) 115 | os.makedirs(job_dir) 116 | 117 | runmany_info = OrderedDict(RUNMANY_INFO_TEMPLATE) 118 | runmany_info['simulation_job_id'] = job_id 119 | runmany_info['job_info'] = OrderedDict([ 120 | ('eps', eps), 121 | ('beta00', beta00), 122 | ('sigma01', sigma01), 123 | ('sd_proc', sd_proc), 124 | ('replicate_id', replicate_id), 125 | ('random_seed', seed_rng.randint(1, 2**31-1)) 126 | ]) 127 | 128 | dump_json(runmany_info, os.path.join(job_dir, 'runmany_info.json')) 129 | 130 | def dump_json(obj, filename): 131 | with open(filename, 'w') as f: 132 | json.dump(obj, f, indent=2) 133 | f.write('\n') 134 | 135 | if __name__ == '__main__': 136 | main() 137 | -------------------------------------------------------------------------------- /example/existing_sim_analysis/plot_heatmaps.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(DBI) 4 | library(RSQLite) 5 | library(ggplot2) 6 | 7 | DB_FILENAME <- 'results_gathered.sqlite' 8 | 9 | main <- function() 10 | { 11 | create_indexes() 12 | 13 | variable_names <- load_variable_names() 14 | 15 | ccm_data <- load_ccm_data() 16 | ccm_summ <- summarize_ccm_data(ccm_data, pvalue_threshold = 0.05) 17 | 18 | p <- qplot( 19 | data = ccm_summ, 20 | x = factor(sigma01), y=factor(sd_proc), 21 | geom = 'tile', fill=increase_fraction, 22 | facets = seasonal * identical ~ direction 23 | ) 24 | 25 | ggsave(filename='increase_fraction.png', p) 26 | } 27 | 28 | # Creates needed DB indexes if not present 29 | create_indexes <- function() 30 | { 31 | db <- dbConnect(SQLite(), DB_FILENAME) 32 | 33 | dbGetQuery(db, 'CREATE INDEX IF NOT EXISTS job_info_index ON job_info (job_id, eps, beta00, sigma01, sd_proc)') 34 | dbGetQuery(db, 'CREATE INDEX IF NOT EXISTS ccm_increase_index ON ccm_increase (job_id, cause, effect)') 35 | dbGetQuery(db, 'CREATE INDEX IF NOT EXISTS ccm_correlation_dist_index ON ccm_correlation_dist (job_id, cause, effect, L)') 36 | 37 | dbDisconnect(db) 38 | 39 | invisible() 40 | } 41 | 42 | # Load variable names 43 | load_variable_names <- function() 44 | { 45 | db <- dbConnect(SQLite(), DB_FILENAME) 46 | variable_names <- dbGetQuery(db, 'SELECT DISTINCT cause FROM ccm_increase ORDER BY cause')$cause 47 | dbDisconnect(db) 48 | } 49 | 50 | # Constructs a data frame, one row per simulation, for direction cause -> effect with columns: 51 | # eps 52 | # beta00 53 | # sigma01 54 | # sd_proc 55 | # replicate_id 56 | # Lmin 57 | # Lmax 58 | # delays 59 | # pvalue_positive 60 | # pvalue_increase 61 | # mean 62 | # sd 63 | # q0 64 | # q1 65 | # q2_5 66 | # q5 67 | # q25 68 | # q50 69 | # q75 70 | # q95 71 | # q97_5 72 | # q99 73 | # q100 74 | load_ccm_data <- function() 75 | { 76 | rds_path <- 'ccm_data.Rds' 77 | 78 | if(file.exists(rds_path)) { 79 | return(readRDS(rds_path)) 80 | } 81 | 82 | db <- dbConnect(SQLite(), DB_FILENAME) 83 | 84 | ccm_data <- dbGetQuery(db, 'SELECT * FROM ccm_increase ORDER BY job_id') 85 | 86 | ccm_data$eps <- NA 87 | ccm_data$beta00 <- NA 88 | ccm_data$sigma01 <- NA 89 | ccm_data$sd_proc <- NA 90 | 91 | ccm_data$mean <- NA 92 | ccm_data$sd <- NA 93 | ccm_data$q0 <- NA 94 | ccm_data$q1 <- NA 95 | ccm_data$q2_5 <- NA 96 | ccm_data$q5 <- NA 97 | ccm_data$q25 <- NA 98 | ccm_data$q50 <- NA 99 | ccm_data$q75 <- NA 100 | ccm_data$q95 <- NA 101 | ccm_data$q97_5 <- NA 102 | ccm_data$q99 <- NA 103 | ccm_data$q100 <- NA 104 | 105 | variable_names <- dbGetQuery(db, 'SELECT DISTINCT cause FROM ccm_increase ORDER BY cause')$cause 106 | 107 | for(i in 1:nrow(ccm_data)) { 108 | row_i <- ccm_data[i,] 109 | 110 | job_info <- dbGetPreparedQuery( 111 | db, 'SELECT * FROM job_info WHERE job_id = ?', data.frame(job_id = row_i$job_id) 112 | ) 113 | for(colname in c('eps', 'beta00', 'sigma01', 'sd_proc')) { 114 | ccm_data[i,colname] <- job_info[colname] 115 | } 116 | 117 | ccm_corr_dist <- dbGetPreparedQuery( 118 | db, 'SELECT * FROM ccm_correlation_dist WHERE job_id = ? AND cause = ? AND effect = ? AND L = ?', 119 | data.frame(job_id = row_i$job_id, cause = row_i$cause, effect = row_i$effect, L = row_i$Lmax) 120 | ) 121 | for(colname in c('pvalue_positive', 'mean', 'sd', 'q0', 'q1', 'q2_5', 'q5', 'q25', 'q50', 'q75', 'q95', 'q97_5', 'q99', 'q100')) { 122 | ccm_data[i, colname] <- ccm_corr_dist[colname] 123 | } 124 | } 125 | 126 | dbDisconnect(db) 127 | saveRDS(ccm_data, file = rds_path) 128 | 129 | return(ccm_data) 130 | } 131 | 132 | # Constructs a summarized data frame with columns: 133 | # eps 134 | # beta00 135 | # sigma01 136 | # sd_proc 137 | # pvalue_positive_mean 138 | # pvalue_positive_sd 139 | # positive_fraction 140 | # pvalue_increase_mean 141 | # pvalue_increase_sd 142 | # increase_fraction 143 | # mean_mean 144 | # median_median 145 | summarize_ccm_data <- function(ccm_data, pvalue_threshold = 0.05) 146 | { 147 | ccm_summ <- unique(ccm_data[c('eps', 'beta00', 'sigma01', 'sd_proc', 'cause', 'effect')]) 148 | rownames(ccm_summ) <- NULL 149 | 150 | ccm_summ$pvalue_positive_mean <- NA 151 | ccm_summ$pvalue_positive_sd <- NA 152 | ccm_summ$positive_fraction <- NA 153 | 154 | variable_names <- unique(ccm_data$cause) 155 | level_mat <- outer(variable_names, variable_names, FUN = function(a, b) sprintf('%s causes %s', b, a)) 156 | ccm_summ$direction <- factor(NA, levels = as.character(level_mat)) 157 | print(levels(ccm_summ$direction)) 158 | 159 | for(i in 1:nrow(ccm_summ)) { 160 | summ_row <- ccm_summ[i,] 161 | ccm_data_subset <- ccm_data[ 162 | ccm_data$eps == summ_row$eps & 163 | ccm_data$beta00 == summ_row$beta00 & 164 | ccm_data$sigma01 == summ_row$sigma01 & 165 | ccm_data$sd_proc == summ_row$sd_proc & 166 | ccm_data$cause == summ_row$cause & 167 | ccm_data$effect == summ_row$effect, 168 | ] 169 | 170 | ccm_summ[i, 'pvalue_positive_mean'] <- mean(ccm_data_subset$pvalue_positive, na.rm=T) 171 | ccm_summ[i, 'pvalue_positive_sd'] <- sd(ccm_data_subset$pvalue_positive, na.rm=T) 172 | ccm_summ[i, 'positive_fraction'] <- mean(ccm_data_subset$pvalue_positive < pvalue_threshold, na.rm=T) 173 | 174 | ccm_summ[i, 'pvalue_increase_mean'] <- mean(ccm_data_subset$pvalue_increase, na.rm=T) 175 | ccm_summ[i, 'pvalue_increase_sd'] <- sd(ccm_data_subset$pvalue_increase, na.rm=T) 176 | ccm_summ[i, 'increase_fraction'] <- mean(ccm_data_subset$pvalue_increase < pvalue_threshold, na.rm=T) 177 | 178 | ccm_summ[i, 'mean_mean'] <- mean(ccm_data_subset$mean, na.rm=T) 179 | ccm_summ[i, 'median_median'] <- median(ccm_data_subset$q50, na.rm=T) 180 | 181 | for(v1 in 1:length(variable_names)) { 182 | for(v2 in 1:length(variable_names)) { 183 | if(variable_names[v2] == summ_row$cause && variable_names[v1] == summ_row$effect) { 184 | ccm_summ[i, 'direction'] <- level_mat[v1,v2] 185 | } 186 | } 187 | } 188 | } 189 | 190 | ccm_summ$seasonal <- factor(NA, levels = c('nonseasonal', 'seasonal')) 191 | ccm_summ[ccm_summ$eps == 0.0, 'seasonal'] <- 'nonseasonal' 192 | ccm_summ[ccm_summ$eps == 0.1, 'seasonal'] <- 'seasonal' 193 | 194 | ccm_summ$identical <- factor(NA, levels = c('identical', 'different')) 195 | ccm_summ[ccm_summ$beta00 == 0.25, 'identical'] <- 'identical' 196 | ccm_summ[ccm_summ$beta00 == 0.30, 'identical'] <- 'different' 197 | 198 | return(ccm_summ) 199 | } 200 | 201 | main() 202 | -------------------------------------------------------------------------------- /example/existing_sim_analysis/plot_heatmaps.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 6 | os.chdir(SCRIPT_DIR) 7 | 8 | import sqlite3 9 | import numpy 10 | import matplotlib 11 | matplotlib.use('Agg') 12 | import matplotlib.pyplot as pyplot 13 | 14 | db = sqlite3.connect('results_gathered.sqlite') 15 | db.execute('CREATE INDEX IF NOT EXISTS job_info_index ON job_info (job_id, eps, beta00, sigma01, sd_proc)') 16 | db.execute('CREATE INDEX IF NOT EXISTS ccm_increase_index ON ccm_increase (job_id, cause, effect)') 17 | db.execute('CREATE INDEX IF NOT EXISTS ccm_correlation_dist_index ON ccm_correlation_dist (job_id, cause, effect, L)') 18 | db.commit() 19 | 20 | def get_unique(pname): 21 | return [row[0] for row in db.execute('SELECT DISTINCT {pname} FROM job_info ORDER BY {pname}'.format(pname=pname))] 22 | 23 | eps_vals = get_unique('eps') 24 | assert len(eps_vals) == 2 and eps_vals[0] == 0.0 25 | 26 | beta00_vals = get_unique('beta00') 27 | assert len(beta00_vals) == 2 28 | 29 | sigma01_vals = get_unique('sigma01') 30 | sd_proc_vals = get_unique('sd_proc') 31 | 32 | def get_increase_positive_rate(cause, effect, eps, beta00, sigma01, sd_proc): 33 | job_ids = [row[0] for row in db.execute( 34 | 'SELECT job_id FROM job_info WHERE eps = ? AND beta00 = ? AND sigma01 = ? AND sd_proc = ?', [eps, beta00, sigma01, sd_proc] 35 | )] 36 | pvalues = [] 37 | for job_id in job_ids: 38 | try: 39 | pvalue = db.execute('SELECT pvalue_increase FROM ccm_increase WHERE job_id = ? AND cause = ? AND effect = ?', [job_id, cause, effect]).next()[0] 40 | pvalues.append(pvalue) 41 | except: 42 | pass 43 | 44 | if len(pvalues) > 0: 45 | return (numpy.array(pvalues) < 0.05).sum() / float(len(pvalues)) 46 | else: 47 | return float('nan') 48 | 49 | def get_mean_pvalue(cause, effect, eps, beta00, sigma01, sd_proc): 50 | job_ids = [row[0] for row in db.execute( 51 | 'SELECT job_id FROM job_info WHERE eps = ? AND beta00 = ? AND sigma01 = ? AND sd_proc = ?', [eps, beta00, sigma01, sd_proc] 52 | )] 53 | pvalues = [] 54 | for job_id in job_ids: 55 | try: 56 | pvalue = db.execute('SELECT pvalue_increase FROM ccm_increase WHERE job_id = ? AND cause = ? AND effect = ?', [job_id, cause, effect]).next()[0] 57 | pvalues.append(pvalue) 58 | except: 59 | pass 60 | 61 | if len(pvalues) > 0: 62 | return numpy.mean(pvalues) 63 | else: 64 | return float('nan') 65 | 66 | def get_positive_positive_rate(cause, effect, eps, beta00, sigma01, sd_proc): 67 | job_ids = [row[0] for row in db.execute( 68 | 'SELECT job_id FROM job_info WHERE eps = ? AND beta00 = ? AND sigma01 = ? AND sd_proc = ?', [eps, beta00, sigma01, sd_proc] 69 | )] 70 | pvalues = [] 71 | for job_id in job_ids: 72 | try: 73 | Lmax = db.execute( 74 | 'SELECT MAX(L) FROM ccm_correlation_dist WHERE job_id = ? AND cause = ? AND effect = ?', 75 | [job_id, cause, effect] 76 | ).next()[0] 77 | pvalue = db.execute( 78 | 'SELECT pvalue_positive FROM ccm_correlation_dist WHERE job_id = ? AND cause = ? AND effect = ? AND L = ?', 79 | [job_id, cause, effect, Lmax] 80 | ).next()[0] 81 | pvalues.append(pvalue) 82 | except: 83 | pass 84 | 85 | if len(pvalues) > 0: 86 | return (numpy.array(pvalues) < 0.05).sum() / float(len(pvalues)) 87 | else: 88 | return float('nan') 89 | 90 | def get_mean_rho(cause, effect, eps, beta00, sigma01, sd_proc): 91 | job_ids = [row[0] for row in db.execute( 92 | 'SELECT job_id FROM job_info WHERE eps = ? AND beta00 = ? AND sigma01 = ? AND sd_proc = ?', [eps, beta00, sigma01, sd_proc] 93 | )] 94 | corrs = [] 95 | for job_id in job_ids: 96 | try: 97 | Lmax = db.execute( 98 | 'SELECT MAX(L) FROM ccm_correlation_dist WHERE job_id = ? AND cause = ? AND effect = ?', 99 | [job_id, cause, effect] 100 | ).next()[0] 101 | corr = db.execute( 102 | 'SELECT mean FROM ccm_correlation_dist WHERE job_id = ? AND cause = ? AND effect = ? AND L = ?', 103 | [job_id, cause, effect, Lmax] 104 | ).next()[0] 105 | corrs.append(corr) 106 | except: 107 | pass 108 | 109 | return numpy.mean(corrs) 110 | 111 | def plot_heatmap(mat, xlabel, xticks, ylabel, yticks, vmin=0, vmax=1): 112 | pyplot.imshow(mat, origin='lower', vmin=vmin, vmax=vmax, interpolation='none') 113 | 114 | pyplot.xticks(range(mat.shape[1]), xticks) 115 | pyplot.xlabel(xlabel) 116 | pyplot.yticks(range(mat.shape[0]), yticks) 117 | pyplot.ylabel(ylabel) 118 | 119 | pyplot.colorbar() 120 | 121 | def plot_func(cause, effect, seasonal, different, heatmap_func, title): 122 | heatmap = numpy.zeros((len(sigma01_vals), len(sd_proc_vals))) 123 | 124 | eps = eps_vals[seasonal] 125 | beta00 = beta00_vals[different] 126 | 127 | for i, sigma01 in enumerate(sigma01_vals): 128 | for j, sd_proc in enumerate(sd_proc_vals): 129 | heatmap[i,j] = heatmap_func(cause, effect, eps, beta00, sigma01, sd_proc) 130 | print heatmap 131 | 132 | plot_heatmap(heatmap, 133 | 'sd_proc', ['{0:.2g}'.format(x) for x in sd_proc_vals], 134 | 'sigma01', ['{0:.2g}'.format(y) for y in sigma01_vals], 135 | vmin=0, vmax=1 136 | ) 137 | pyplot.title('{}: {} causes {}'.format(title, cause, effect)) 138 | 139 | def plot_increase_positive_rate(cause, effect, seasonal, different): 140 | plot_func(cause, effect, seasonal, different, get_increase_positive_rate, 'frac(pval increase < 0.05)') 141 | 142 | def plot_mean_pvalue(cause, effect, seasonal, different): 143 | plot_func(cause, effect, seasonal, different, get_mean_pvalue, 'mean(pval increase)') 144 | 145 | def plot_positive_positive_rate(cause, effect, seasonal, different): 146 | plot_func(cause, effect, seasonal, different, get_positive_positive_rate, 'frac(pval pos at Lmax < 0.05)') 147 | 148 | def plot_mean_rho(cause, effect, seasonal, different): 149 | plot_func(cause, effect, seasonal, different, get_mean_rho, 'mean ccm rho at Lmax') 150 | 151 | for seasonal in (0, 1): 152 | for different in (0, 1): 153 | seas_label = 'seasonal' if seasonal else 'nonseasonal' 154 | diff_label = 'different' if different else 'identical' 155 | 156 | fig = pyplot.figure(figsize=(12,21)) 157 | pyplot.subplot(4, 2, 1) 158 | plot_increase_positive_rate('C0', 'C1', seasonal, different) 159 | pyplot.subplot(4, 2, 2) 160 | plot_increase_positive_rate('C1', 'C0', seasonal, different) 161 | 162 | pyplot.subplot(4, 2, 3) 163 | plot_mean_pvalue('C0', 'C1', seasonal, different) 164 | pyplot.subplot(4, 2, 4) 165 | plot_mean_pvalue('C1', 'C0', seasonal, different) 166 | 167 | pyplot.subplot(4, 2, 5) 168 | plot_mean_rho('C0', 'C1', seasonal, different) 169 | pyplot.subplot(4, 2, 6) 170 | plot_mean_rho('C1', 'C0', seasonal, different) 171 | 172 | pyplot.subplot(4, 2, 7) 173 | plot_positive_positive_rate('C0', 'C1', seasonal, different) 174 | pyplot.subplot(4, 2, 8) 175 | plot_positive_positive_rate('C1', 'C0', seasonal, different) 176 | 177 | pyplot.suptitle('{}, {}'.format(seas_label, diff_label)) 178 | pyplot.savefig('{}_{}.png'.format(seas_label, diff_label)) 179 | 180 | db.close() 181 | -------------------------------------------------------------------------------- /example/existing_sim_analysis/plot_lags.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 6 | os.chdir(SCRIPT_DIR) 7 | 8 | import sqlite3 9 | import numpy 10 | import matplotlib 11 | matplotlib.use('Agg') 12 | import matplotlib.pyplot as pyplot 13 | from collections import Counter 14 | 15 | from ast import literal_eval as make_tuple 16 | 17 | db = sqlite3.connect('results_gathered.sqlite') 18 | db.execute('CREATE INDEX IF NOT EXISTS job_info_index ON job_info (job_id, eps, beta00, sigma01, sd_proc)') 19 | db.execute('CREATE INDEX IF NOT EXISTS ccm_increase_index ON ccm_increase (job_id, cause, effect)') 20 | db.execute('CREATE INDEX IF NOT EXISTS ccm_correlation_dist_index ON ccm_correlation_dist (job_id, cause, effect, L)') 21 | db.commit() 22 | 23 | def get_unique(pname): 24 | return [row[0] for row in db.execute('SELECT DISTINCT {pname} FROM job_info ORDER BY {pname}'.format(pname=pname))] 25 | 26 | eps_vals = get_unique('eps') 27 | assert len(eps_vals) == 2 and eps_vals[0] == 0.0 28 | 29 | beta00_vals = get_unique('beta00') 30 | assert len(beta00_vals) == 2 31 | 32 | sigma01_vals = get_unique('sigma01') 33 | sd_proc_vals = get_unique('sd_proc') 34 | 35 | def plot_lags(eps, beta00, sigma01, sd_proc): 36 | job_ids = [row[0] for row in db.execute( 37 | 'SELECT job_id FROM job_info WHERE eps = ? AND beta00 = ? AND sigma01 = ? AND sd_proc = ?', [eps, beta00, sigma01, sd_proc] 38 | )] 39 | 40 | max_delay = 0 41 | for cause, effect in [('C0', 'C1'), ('C1', 'C0')]: 42 | for job_id in job_ids: 43 | try: 44 | delays = make_tuple(db.execute( 45 | 'SELECT delays FROM ccm_increase WHERE job_id = ? AND cause = ? AND effect = ?', [job_id, cause, effect] 46 | ).next()[0]) 47 | this_max_delay = max(delays) 48 | if this_max_delay > max_delay: 49 | max_delay = this_max_delay 50 | except: 51 | pass 52 | 53 | fig = pyplot.figure(figsize=(10, 10)) 54 | subplot_index = 0 55 | for cause, effect in [('C0', 'C1'), ('C1', 'C0')]: 56 | delays_list = [] 57 | E_counter = Counter() 58 | for job_id in job_ids: 59 | try: 60 | delays = make_tuple(db.execute( 61 | 'SELECT delays FROM ccm_increase WHERE job_id = ? AND cause = ? AND effect = ?', [job_id, cause, effect] 62 | ).next()[0]) 63 | print job_id, cause, effect, delays 64 | delays_list.append(delays) 65 | E_counter[len(delays)] += 1 66 | except: 67 | pass 68 | 69 | if len(delays_list) == 0: 70 | sys.stderr.write('no valid jobs for eps={}-beta00={}-sigma01={}-sd_proc={}\n'.format(eps, beta00, sigma01, sd_proc)) 71 | return 72 | 73 | heatmap = numpy.ones((len(delays_list), max_delay + 1), dtype=float) 74 | for i, delays in enumerate(delays_list): 75 | heatmap[i, delays] = 0.0 76 | 77 | pyplot.subplot(2, 2, subplot_index*2+1) 78 | pyplot.imshow(heatmap, origin='upper', vmin=0, vmax=1, interpolation='none', cmap='gray') 79 | pyplot.xlabel('lag') 80 | pyplot.ylabel('replicate') 81 | pyplot.title('{} causes {}'.format(cause, effect)) 82 | 83 | pyplot.subplot(2, 2, subplot_index*2 + 2) 84 | Es = sorted(E_counter.keys()) 85 | counts = [E_counter[E] for E in Es] 86 | pyplot.bar([E - 0.4 for E in Es], counts, width=0.8) 87 | pyplot.xlabel('embedding dimension') 88 | pyplot.ylabel('count') 89 | pyplot.xticks(Es) 90 | pyplot.title('{} causes {}'.format(cause, effect)) 91 | 92 | subplot_index += 1 93 | pyplot.suptitle('eps={}-beta00={}-sigma01={}-sd_proc={}'.format(eps, beta00, sigma01, sd_proc)) 94 | 95 | plot_dir = os.path.join( 96 | 'lag_plots', 97 | 'eps={:0.1f}'.format(eps), 'beta00={:0.2f}'.format(beta00), 'sigma01={:0.2f}'.format(sigma01), 'sd_proc={:0.6f}'.format(sd_proc) 98 | ) 99 | try: 100 | os.makedirs(plot_dir) 101 | except: 102 | pass 103 | pyplot.savefig(os.path.join(plot_dir, 'lag_plot.png')) 104 | pyplot.close(fig) 105 | 106 | try: 107 | os.makedirs('lag_plots') 108 | except: 109 | pass 110 | 111 | for eps in eps_vals: 112 | for beta00 in beta00_vals: 113 | for sigma01 in sigma01_vals: 114 | for sd_proc in sd_proc_vals: 115 | plot_lags(eps, beta00, sigma01, sd_proc) 116 | 117 | db.close() 118 | -------------------------------------------------------------------------------- /example/existing_sim_plots/generate_plot_jobs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | import random 6 | import sqlite3 7 | from collections import OrderedDict 8 | import json 9 | 10 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 11 | 12 | sys.path.append(os.path.join(SCRIPT_DIR, 'pyembedding')) 13 | import uzalcost 14 | 15 | # Simulations database: make sure this is an absolute path 16 | SIM_DB_PATH = '/Users/ebaskerv/uchicago/midway_cobey/ccmproject-storage/2015-10-23-simulations/results_gathered.sqlite' 17 | #SIM_DB_PATH = '/project/cobey/ccmproject-storage/2015-10-23-simulations/results_gathered.sqlite' 18 | 19 | # Must be less than or equal to the number of replicates in the sim db (100). 20 | # If less than 100, will only use the first N_REPLICATES replicates 21 | N_REPLICATES = 1 22 | 23 | def get_plot_settings(): 24 | simulation_samples_per_year = 36 # This is an assumption about the time series being loaded; don't change 25 | # unless a new simulation DB is being used with different settings. 26 | # 36 implies 10-day samples in a 360-day year in the original simulations. 27 | 28 | timeseries_x_label = 'time (years)' # Labels for time-series plot. Rewrite to match settings 29 | timeseries_y_label= 'monthly cases' # below. 30 | 31 | years = 100 # Number of years to use at end of time series 32 | 33 | samples_per_year = 12 # E.g., 12 implies 30-day samples in a 360-day year. 34 | # Must divide evenly into SIMULATION_SAMPLES_PER_YEAR 35 | 36 | variable_name = 'C' # Can also be 'logS' or 'logI'. 37 | 38 | add_samples = True # If True, uses *sum* of original samples for analysis 39 | # rather than throwing out intervening samples. 40 | # For C (cases), this should probably be True, since it's a 41 | # measure of cumulative cases during a time period. 42 | 43 | log_transform = False # If True, takes the natural log of samples. 44 | # If ADD_SAMPLES is True, then this is applied *after* 45 | # adding samples together. 46 | 47 | first_difference = False # If True, first-differences time series. 48 | # This is applied after ADD_SAMPLES and LOG_TRANSFORM. 49 | 50 | standardize = False # If True, each time series is standardized to mean=0, sd=1. 51 | # This is applied after all other transformations. 52 | 53 | return locals() 54 | 55 | RUNMANY_INFO_TEMPLATE = OrderedDict([ 56 | ('executable', os.path.join(SCRIPT_DIR, 'run_plot_job.py')), 57 | ('minutes', 30), 58 | ('megabytes', 2000), 59 | ('simulation_db_path', SIM_DB_PATH), 60 | ('plot_settings', get_plot_settings()) 61 | ]) 62 | 63 | def main(): 64 | jobs_dir = os.path.join(SCRIPT_DIR, 'plots') 65 | seed_rng = random.SystemRandom() 66 | 67 | if os.path.exists(jobs_dir): 68 | sys.stderr.write('{} already exists; aborting.\n'.format(jobs_dir)) 69 | sys.exit(1) 70 | 71 | if not os.path.exists(SIM_DB_PATH): 72 | sys.stderr.write('simulations DB not present; aborting.\n') 73 | sys.exit(1) 74 | 75 | with sqlite3.connect(SIM_DB_PATH) as db: 76 | for eps in get_param_vals(db, 'eps'): 77 | for beta00 in get_param_vals(db, 'beta00'): 78 | for sigma01 in get_param_vals(db, 'sigma01'): 79 | for sd_proc in get_param_vals(db, 'sd_proc'): 80 | job_dir = os.path.join(jobs_dir, 'eps={:.2g}-beta00={:.2g}-sigma01={:.2g}-sd_proc={:.1g}'.format( 81 | eps, beta00, sigma01, sd_proc 82 | )) 83 | os.makedirs(job_dir) 84 | 85 | job_ids = get_job_ids(db, eps=eps, beta00=beta00, sigma01=sigma01, sd_proc=sd_proc)[:N_REPLICATES] 86 | runmany_info = OrderedDict(RUNMANY_INFO_TEMPLATE) 87 | runmany_info['job_ids'] = job_ids 88 | 89 | dump_json(runmany_info, os.path.join(job_dir, 'runmany_info.json')) 90 | 91 | 92 | # with sqlite3.connect(SIM_DB_PATH) as db: 93 | # for job_id, job_subdir, eps, beta00, sigma01, sd_proc, replicate_id, random_seed in db.execute( 94 | # 'SELECT * FROM job_info WHERE replicate_id < ?', [N_REPLICATES] 95 | # ): 96 | # job_dir = os.path.join(SCRIPT_DIR, job_subdir) 97 | # sys.stderr.write('{0}\n'.format(job_dir)) 98 | # os.makedirs(job_dir) 99 | # 100 | # runmany_info = OrderedDict(RUNMANY_INFO_TEMPLATE) 101 | # runmany_info['simulation_job_id'] = job_id 102 | # runmany_info['job_info'] = OrderedDict([ 103 | # ('eps', eps), 104 | # ('beta00', beta00), 105 | # ('sigma01', sigma01), 106 | # ('sd_proc', sd_proc) 107 | # ]) 108 | # 109 | # dump_json(runmany_info, os.path.join(job_dir, 'runmany_info.json')) 110 | 111 | def get_param_vals(db, param_name): 112 | return [row[0] for row in db.execute('SELECT DISTINCT {0} FROM job_info ORDER BY {0}'.format(param_name))] 113 | 114 | def get_job_ids(db, **kwargs): 115 | keys = kwargs.keys() 116 | values = [kwargs[key] for key in keys] 117 | return [row[0] for row in db.execute( 118 | 'SELECT job_id FROM job_info WHERE {} ORDER BY job_id'.format( 119 | ' AND '.join(['{} = ?'.format(key) for key in keys]) 120 | ), 121 | values 122 | )] 123 | 124 | def dump_json(obj, filename): 125 | with open(filename, 'w') as f: 126 | json.dump(obj, f, indent=2) 127 | f.write('\n') 128 | 129 | if __name__ == '__main__': 130 | main() 131 | -------------------------------------------------------------------------------- /example/existing_sim_plots/interactive_plots.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | import random 6 | import sqlite3 7 | from collections import OrderedDict 8 | import json 9 | 10 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 11 | 12 | sys.path.append(os.path.join(SCRIPT_DIR, 'pyembedding')) 13 | import uzalcost 14 | 15 | # Simulations database: make sure this is an absolute path 16 | SIM_DB_PATH = '/Users/ebaskerv/uchicago/midway_cobey/ccmproject-storage/2015-10-23-simulations/results_gathered.sqlite' 17 | #SIM_DB_PATH = '/project/cobey/ccmproject-storage/2015-10-23-simulations/results_gathered.sqlite' 18 | 19 | # Must be less than or equal to the number of replicates in the sim db (100). 20 | # If less than 100, will only use the first N_REPLICATES replicates 21 | N_REPLICATES = 1 22 | 23 | def get_plot_settings(): 24 | simulation_samples_per_year = 36 # This is an assumption about the time series being loaded; don't change 25 | # unless a new simulation DB is being used with different settings. 26 | # 36 implies 10-day samples in a 360-day year in the original simulations. 27 | 28 | timeseries_x_label = 'time (years)' # Labels for time-series plot. Rewrite to match settings 29 | timeseries_y_label= 'monthly cases' # below. 30 | 31 | years = 100 # Number of years to use at end of time series 32 | 33 | samples_per_year = 12 # E.g., 12 implies 30-day samples in a 360-day year. 34 | # Must divide evenly into SIMULATION_SAMPLES_PER_YEAR 35 | 36 | variable_name = 'C' # Can also be 'logS' or 'logI'. 37 | 38 | add_samples = True # If True, uses *sum* of original samples for analysis 39 | # rather than throwing out intervening samples. 40 | # For C (cases), this should probably be True, since it's a 41 | # measure of cumulative cases during a time period. 42 | 43 | log_transform = False # If True, takes the natural log of samples. 44 | # If ADD_SAMPLES is True, then this is applied *after* 45 | # adding samples together. 46 | 47 | first_difference = False # If True, first-differences time series. 48 | # This is applied after ADD_SAMPLES and LOG_TRANSFORM. 49 | 50 | standardize = False # If True, each time series is standardized to mean=0, sd=1. 51 | # This is applied after all other transformations. 52 | 53 | return locals() 54 | 55 | RUNMANY_INFO_TEMPLATE = OrderedDict([ 56 | ('executable', os.path.join(SCRIPT_DIR, 'run_plot_job.py')), 57 | ('minutes', 30), 58 | ('megabytes', 2000), 59 | ('simulation_db_path', SIM_DB_PATH), 60 | ('plot_settings', get_plot_settings()) 61 | ]) 62 | 63 | def main(): 64 | jobs_dir = os.path.join(SCRIPT_DIR, 'plots') 65 | seed_rng = random.SystemRandom() 66 | 67 | if os.path.exists(jobs_dir): 68 | sys.stderr.write('{} already exists; aborting.\n'.format(jobs_dir)) 69 | sys.exit(1) 70 | 71 | if not os.path.exists(SIM_DB_PATH): 72 | sys.stderr.write('simulations DB not present; aborting.\n') 73 | sys.exit(1) 74 | 75 | with sqlite3.connect(SIM_DB_PATH) as db: 76 | for eps in get_param_vals(db, 'eps'): 77 | for beta00 in get_param_vals(db, 'beta00'): 78 | for sigma01 in get_param_vals(db, 'sigma01'): 79 | for sd_proc in get_param_vals(db, 'sd_proc'): 80 | job_dir = os.path.join(jobs_dir, 'eps={:.2g}-beta00={:.2g}-sigma01={:.2g}-sd_proc={:.1g}'.format( 81 | eps, beta00, sigma01, sd_proc 82 | )) 83 | os.makedirs(job_dir) 84 | 85 | job_ids = get_job_ids(db, eps=eps, beta00=beta00, sigma01=sigma01, sd_proc=sd_proc)[:N_REPLICATES] 86 | runmany_info = OrderedDict(RUNMANY_INFO_TEMPLATE) 87 | runmany_info['job_ids'] = job_ids 88 | 89 | dump_json(runmany_info, os.path.join(job_dir, 'runmany_info.json')) 90 | 91 | 92 | # with sqlite3.connect(SIM_DB_PATH) as db: 93 | # for job_id, job_subdir, eps, beta00, sigma01, sd_proc, replicate_id, random_seed in db.execute( 94 | # 'SELECT * FROM job_info WHERE replicate_id < ?', [N_REPLICATES] 95 | # ): 96 | # job_dir = os.path.join(SCRIPT_DIR, job_subdir) 97 | # sys.stderr.write('{0}\n'.format(job_dir)) 98 | # os.makedirs(job_dir) 99 | # 100 | # runmany_info = OrderedDict(RUNMANY_INFO_TEMPLATE) 101 | # runmany_info['simulation_job_id'] = job_id 102 | # runmany_info['job_info'] = OrderedDict([ 103 | # ('eps', eps), 104 | # ('beta00', beta00), 105 | # ('sigma01', sigma01), 106 | # ('sd_proc', sd_proc) 107 | # ]) 108 | # 109 | # dump_json(runmany_info, os.path.join(job_dir, 'runmany_info.json')) 110 | 111 | def get_param_vals(db, param_name): 112 | return [row[0] for row in db.execute('SELECT DISTINCT {0} FROM job_info ORDER BY {0}'.format(param_name))] 113 | 114 | def get_job_ids(db, **kwargs): 115 | keys = kwargs.keys() 116 | values = [kwargs[key] for key in keys] 117 | return [row[0] for row in db.execute( 118 | 'SELECT job_id FROM job_info WHERE {} ORDER BY job_id'.format( 119 | ' AND '.join(['{} = ?'.format(key) for key in keys]) 120 | ), 121 | values 122 | )] 123 | 124 | def dump_json(obj, filename): 125 | with open(filename, 'w') as f: 126 | json.dump(obj, f, indent=2) 127 | f.write('\n') 128 | 129 | if __name__ == '__main__': 130 | main() 131 | -------------------------------------------------------------------------------- /example/existing_sim_plots/plot_timeseries.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | -------------------------------------------------------------------------------- /example/existing_sim_plots/plot_timeseries.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import urllib 4 | import os 5 | import sys 6 | import json 7 | import numpy 8 | import webbrowser 9 | import sqlite3 10 | from cStringIO import StringIO 11 | import twisted 12 | from twisted.web import server, resource 13 | from twisted.internet import reactor 14 | 15 | SIM_DB_PATH = '/Users/ebaskerv/uchicago/midway_cobey/ccmproject-storage/2015-10-23-simulations/results_gathered.sqlite' 16 | 17 | class SQLiteServer(resource.Resource): 18 | def __init__(self, db): 19 | self.db = db 20 | 21 | isLeaf = True 22 | def render_POST(self, request): 23 | request.setHeader('Access-Control-Allow-Origin', 'null') 24 | 25 | request_data = json.loads(request.content.read()) 26 | 27 | query = request_data['query'] 28 | args = request_data['args'] 29 | 30 | rows = [] 31 | try: 32 | if args is None: 33 | c = db.execute(query) 34 | else: 35 | c = db.execute(query, args) 36 | columns = [x[0] for x in c.description] 37 | print columns 38 | for row in c: 39 | rows.append([npy_buffer_to_list(x) if isinstance(x, buffer) else x for x in row]) 40 | 41 | return json.dumps({ 42 | 'exception' : None, 43 | 'columns' : columns, 44 | 'rows' : rows 45 | }) 46 | except Exception as e: 47 | return json.dumps({ 48 | 'exception' : str(e), 49 | 'columns' : None, 50 | 'rows' : None 51 | }) 52 | 53 | def ndarray_to_npy_buffer(x): 54 | f = StringIO() 55 | numpy.save(f, x) 56 | buf = buffer(f.getvalue()) 57 | f.close() 58 | return buf 59 | 60 | def npy_buffer_to_ndarray(x): 61 | f = StringIO(x) 62 | arr = numpy.load(f) 63 | f.close() 64 | return arr 65 | 66 | if __name__ == '__main__': 67 | if len(sys.argv) > 1: 68 | db_filename = os.path.abspath(sys.argv[1]) 69 | else: 70 | db_filename = SIM_DB_PATH 71 | 72 | if not os.path.exists(db_filename): 73 | print('SQLite database {0} does not exist.'.format(db_filename)) 74 | sys.exit(1) 75 | 76 | with sqlite3.connect(db_filename, timeout=60) as db: 77 | site = server.Site(SQLiteServer(db)) 78 | port_obj = reactor.listenTCP(0, site) 79 | port_num = port_obj.getHost().port 80 | 81 | html_path = urllib.pathname2url(os.path.abspath('plot_timeseries.html')) 82 | html_args = urllib.urlencode({'port' : port_num}) 83 | html_url = 'file://{0}?{1}'.format(html_path, html_args) 84 | 85 | print('Running at URL:') 86 | print(html_url) 87 | 88 | webbrowser.open_new(html_url) 89 | reactor.run() 90 | -------------------------------------------------------------------------------- /example/existing_sim_plots/run_plot_job.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 5 | import sys 6 | sys.path.append(os.path.join(SCRIPT_DIR, 'pyembedding')) 7 | import sqlite3 8 | import numpy 9 | import matplotlib 10 | import random 11 | matplotlib.use('Agg') 12 | from matplotlib import pyplot 13 | import json 14 | from collections import OrderedDict 15 | 16 | # Make sure pyembedding is set in $PYTHONPATH so these can be found, or do something like: 17 | # sys.path.append(os.path.join(SCRIPT_DIR), 'pyembedding') 18 | # if that's appropriate 19 | import pyembedding 20 | import uzalcost 21 | import models 22 | import statutils 23 | import npybuffer 24 | 25 | def main(): 26 | '''main(): gets called at the end (after other functions have been defined)''' 27 | 28 | # Load job info and record in database 29 | if not os.path.exists('runmany_info.json'): 30 | sys.stderr.write('runmany_info.json missing. aborting.\n') 31 | sys.exit(1) 32 | runmany_info = load_json('runmany_info.json') 33 | sim_db_path = runmany_info['simulation_db_path'] 34 | 35 | # Make sure simulation database is present 36 | if not os.path.exists(sim_db_path): 37 | sys.stderr.write('Simulation database not present; aborting\n') 38 | sys.exit(1) 39 | job_ids = runmany_info['job_ids'] 40 | plot_settings = runmany_info['plot_settings'] 41 | 42 | variable_name = plot_settings['variable_name'] 43 | x0name = variable_name + '0' 44 | x1name = variable_name + '1' 45 | 46 | fig = pyplot.figure(figsize=(15, 5 * len(job_ids))) 47 | for i, job_id in enumerate(job_ids): 48 | X = load_simulation(sim_db_path, job_id, plot_settings) 49 | x0 = X[:,0] 50 | x1 = X[:,1] 51 | pyplot.subplot(len(job_ids), 1, i+1) 52 | plot_timeseries([x0, x1], [x0name, x1name], plot_settings['timeseries_x_label'], plot_settings['timeseries_y_label']) 53 | pyplot.savefig('{}.png'.format(os.path.basename(os.path.abspath('.')))) 54 | 55 | def plot_timeseries(series, labels, xlabel, ylabel): 56 | for x in series: 57 | pyplot.plot(x) 58 | pyplot.legend(labels) 59 | pyplot.xlabel(xlabel) 60 | pyplot.ylabel(ylabel) 61 | 62 | def load_simulation(sim_db_path, job_id, plot_settings): 63 | '''Loads and processes time series based on settings at top of file.''' 64 | with sqlite3.connect(sim_db_path) as sim_db: 65 | buf = sim_db.execute( 66 | 'SELECT {} FROM timeseries WHERE job_id = ?'.format(plot_settings['variable_name']), 67 | [job_id] 68 | ).next()[0] 69 | assert isinstance(buf, buffer) 70 | arr = npybuffer.npy_buffer_to_ndarray(buf) 71 | assert arr.shape[1] == 2 72 | 73 | years = plot_settings['years'] 74 | simulation_samples_per_year = plot_settings['simulation_samples_per_year'] 75 | samples_per_year = plot_settings['samples_per_year'] 76 | 77 | # Get the unthinned sample from the end of the time series 78 | sim_samps_unthinned = years * simulation_samples_per_year 79 | thin = simulation_samples_per_year / samples_per_year 80 | arr_end_unthinned = arr[-sim_samps_unthinned:, :] 81 | 82 | # Thin the samples, adding in the intervening samples if requested 83 | arr_mod = arr_end_unthinned[::thin, :] 84 | if plot_settings['add_samples']: 85 | for i in range(1, thin): 86 | arr_mod += arr_end_unthinned[i::thin, :] 87 | 88 | if plot_settings['log_transform']: 89 | arr_mod = numpy.log(arr_mod) 90 | 91 | if plot_settings['first_difference']: 92 | arr_mod = arr_mod[1:, :] - arr_mod[:-1, :] 93 | 94 | if plot_settings['standardize']: 95 | for i in range(arr_mod.shape[1]): 96 | arr_mod[:,i] -= numpy.mean(arr_mod[:,i]) 97 | arr_mod[:,i] /= numpy.std(arr_mod[:,i]) 98 | 99 | 100 | if plot_settings['first_difference']: 101 | assert arr_mod.shape[0] == years * samples_per_year - 1 102 | else: 103 | assert arr_mod.shape[0] == years * samples_per_year 104 | assert arr_mod.shape[1] == 2 105 | 106 | return arr_mod 107 | 108 | def load_json(filename): 109 | with open(filename) as f: 110 | return json.load(f, object_pairs_hook=OrderedDict) 111 | 112 | main() 113 | -------------------------------------------------------------------------------- /jsonobject.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import json 3 | import numpy 4 | import cStringIO 5 | from collections import OrderedDict 6 | 7 | class JSONObject(object): 8 | '''Class to improve syntax when working with JSON-loaded objects, and automatically convert lists from/to 9 | numpy arrays. 10 | 11 | >>> x = JSONObject([('foo', 5), ('bar', 7)]) 12 | >>> x.foo == 5 13 | True 14 | >>> x.bar == 7 15 | True 16 | ''' 17 | 18 | def __init__(self, name_value_pairs=None, **kwargs): 19 | '''Initialize object from attribute name-value pairs. 20 | 21 | :param name_value_pairs: Attribute name-value pairs. 22 | ''' 23 | self.odict = OrderedDict() 24 | 25 | if name_value_pairs is not None: 26 | if isinstance(name_value_pairs, dict): 27 | #sys.stderr.write('{0}\n'.format(name_value_pairs)) 28 | name_value_pairs = name_value_pairs.items() 29 | 30 | for name, value in name_value_pairs: 31 | setattr(self, name, value) 32 | 33 | for k, v in kwargs.iteritems(): 34 | setattr(self, k, v) 35 | 36 | def __setitem__(self, key, value): 37 | setattr(self, key, value) 38 | 39 | def __getitem__(self, item): 40 | return getattr(self, item) 41 | 42 | def __setattr__(self, name, value): 43 | if name == 'odict': 44 | return super(JSONObject, self).__setattr__(name, value) 45 | 46 | '''Assigns attribute to object, converting to numpy array if appropriate. 47 | 48 | :param name: Name of attribute. 49 | :param value: Value of attribute. 50 | 51 | >>> x = JSONObject() 52 | >>> x.assign_attribute('foo', 5) 53 | >>> x.foo == 5 54 | True 55 | >>> x.assign_attribute('bar', 7) 56 | >>> x.bar == 7 57 | True 58 | >>> x.assign_attribute('baz', [1,2,3]) 59 | >>> len(x.baz.shape) 60 | 1 61 | >>> x.baz.shape[0] 62 | 3 63 | >>> x.assign_attribute('barf', [[1,2], [2,3,4]]) 64 | >>> isinstance(x.barf, list) 65 | True 66 | ''' 67 | 68 | if isinstance(value, list): 69 | try: 70 | value = numpy.array(value) 71 | except: 72 | pass 73 | elif isinstance(value, dict): 74 | value = JSONObject(value) 75 | 76 | self.odict[name] = value 77 | 78 | def __getattr__(self, item): 79 | if item == 'odict': 80 | return super(JSONObject, self).__getattr__(self, item) 81 | return self.odict[item] 82 | 83 | def __len__(self): 84 | return len(self.odict) 85 | 86 | def keys(self): 87 | return self.odict.keys() 88 | 89 | def iterkeys(self): 90 | return self.odict.iterkeys() 91 | 92 | def values(self): 93 | return self.odict.values() 94 | 95 | def itervalues(self): 96 | return self.odict.itervalues() 97 | 98 | def items(self): 99 | return self.odict.items() 100 | 101 | def iteritems(self): 102 | return self.odict.iteritems() 103 | 104 | def update_from_file(self, f_or_s): 105 | ''' 106 | 107 | :param f: 108 | :return: 109 | 110 | >>> json_obj = JSONObject([('foo', 5), ('bar', 7), ('baz', [1,2,3,4])]) 111 | >>> json_file = cStringIO.StringIO('{"bar" : 8}') 112 | >>> json_obj.update_from_file(json_file) 113 | >>> json_obj.foo 114 | 5 115 | >>> json_obj.bar 116 | 8 117 | >>> json_obj.baz.tolist() 118 | [1, 2, 3, 4] 119 | ''' 120 | json_obj = load_from_file(f_or_s) 121 | self.odict.update(json_obj.odict) 122 | 123 | def update_from_string(self, s): 124 | ''' 125 | 126 | :param f: 127 | :return: 128 | 129 | >>> json_obj = JSONObject([('foo', 5), ('bar', 7), ('baz', [1,2,3,4])]) 130 | >>> json_obj.update_from_string('{"bar" : 8}') 131 | >>> json_obj.foo 132 | 5 133 | >>> json_obj.bar 134 | 8 135 | >>> json_obj.baz.tolist() 136 | [1, 2, 3, 4] 137 | ''' 138 | json_obj = load_from_string(s) 139 | self.odict.update(json_obj.odict) 140 | 141 | def dump_to_file(self, f_or_s, indent=None): 142 | ''' 143 | :return: 144 | 145 | >>> json_obj = JSONObject([('foo', 5), ('bar', 7), ('baz', [1,2,3,4])]) 146 | >>> json_out = cStringIO.StringIO() 147 | >>> json_obj.dump_to_file(json_out) 148 | >>> json_obj_check = json.loads(json_out.getvalue()) 149 | >>> json_obj_check['foo'] 150 | 5 151 | >>> json_obj_check['bar'] 152 | 7 153 | >>> json_obj_check['baz'] 154 | [1, 2, 3, 4] 155 | ''' 156 | if isinstance(f_or_s, basestring): 157 | f = open(f_or_s, 'w') 158 | opened_file = True 159 | else: 160 | f = f_or_s 161 | opened_file = False 162 | json.dump(self, f, cls=JSONObjectEncoder, indent=indent) 163 | f.write('\n') 164 | if opened_file: 165 | f.close() 166 | 167 | def dump_to_string(self, indent=None): 168 | ''' 169 | :return: 170 | 171 | >>> json_obj = JSONObject([('foo', 5), ('bar', 7), ('baz', [1,2,3,4])]) 172 | >>> json_out = cStringIO.StringIO() 173 | >>> json_obj_check = json.loads(json_obj.dump_to_string()) 174 | >>> json_obj_check['foo'] 175 | 5 176 | >>> json_obj_check['bar'] 177 | 7 178 | >>> json_obj_check['baz'] 179 | [1, 2, 3, 4] 180 | ''' 181 | return json.dumps(self, cls=JSONObjectEncoder, indent=indent) 182 | 183 | 184 | class JSONObjectEncoder(json.JSONEncoder): 185 | def default(self, obj): 186 | if isinstance(obj, JSONObject): 187 | return obj.odict 188 | elif isinstance(obj, numpy.ndarray): 189 | return obj.tolist() 190 | return json.JSONEncoder.default(self, obj) 191 | 192 | def load_from_file(f_or_s): 193 | '''Load JSONObject object from JSON file 194 | >>> json_file = cStringIO.StringIO('{"foo" : 5, "bar" : 7}') 195 | >>> json_obj = load_from_file(json_file) 196 | >>> json_obj.foo 197 | 5 198 | >>> json_obj.bar 199 | 7 200 | ''' 201 | if isinstance(f_or_s, basestring): 202 | f = open(f_or_s) 203 | opened_file = True 204 | else: 205 | f = f_or_s 206 | opened_file = False 207 | obj = json.load(f, object_pairs_hook=JSONObject) 208 | if opened_file: 209 | f.close() 210 | return obj 211 | 212 | def load_from_string(s): 213 | '''Load JSONObject object from JSON file 214 | >>> json_str = '{"foo" : 5, "bar" : [7, 8, 9]}' 215 | >>> json_obj = load_from_string(json_str) 216 | >>> json_obj.foo 217 | 5 218 | >>> json_obj.bar.tolist() 219 | [7, 8, 9] 220 | ''' 221 | return json.loads(s, object_pairs_hook=JSONObject) 222 | 223 | if __name__ == '__main__': 224 | import doctest 225 | doctest.testmod(verbose=True) 226 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | import os 2 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 3 | import sys 4 | import json 5 | import random 6 | from math import sin, pi, log, exp, sqrt, floor, ceil, log1p, isnan 7 | from collections import OrderedDict 8 | import numpy 9 | 10 | class ExecutionException(Exception): 11 | def __init__(self, cause, stdout_data, stderr_data): 12 | self.cause = cause 13 | self.stdout_data = stdout_data 14 | self.stderr_data = stderr_data 15 | 16 | def run_via_pypy(model_name, params): 17 | import jsonobject 18 | import subprocess 19 | proc = subprocess.Popen( 20 | ['/usr/bin/env', 'pypy', os.path.join(SCRIPT_DIR, 'models_pypy.py'), model_name], 21 | stdin=subprocess.PIPE, 22 | stdout=subprocess.PIPE, 23 | stderr=subprocess.PIPE, 24 | shell=False 25 | ) 26 | 27 | if isinstance(params, jsonobject.JSONObject): 28 | stdin_data = params.dump_to_string() 29 | else: 30 | stdin_data = json.dumps(params) 31 | stdout_data, stderr_data = proc.communicate(stdin_data) 32 | proc.wait() 33 | 34 | try: 35 | return jsonobject.load_from_string(stdout_data) 36 | except Exception as e: 37 | raise ExecutionException(e, stdout_data, stderr_data) 38 | 39 | def sugihara_mirage_correlation(t_max=200, rx=3.8, ry=3.5, Bxy=0.02, Byx=0.1, x0=0.4, y0=0.2): 40 | '''From Figure 1 in Sugihara et al. Science 2010.''' 41 | x = numpy.zeros(t_max + 1, dtype=float) 42 | x[0] = x0 43 | y = numpy.zeros(t_max + 1, dtype=float) 44 | y[0] = y0 45 | 46 | for t in range(t_max): 47 | x[t + 1] = x[t] * (rx - rx * x[t] - Bxy * y[t]) 48 | y[t + 1] = y[t] * (ry - ry * y[t] - Byx * x[t]) 49 | 50 | return x, y 51 | 52 | def sugihara_example1( 53 | rng, 54 | t_max=1000, burnin=200, r1=3.1, D1=3, Sa1=0.4, r2=2.9, D2=3, Sa2=0.35, 55 | noiseparam=1, psi=0.3 56 | ): 57 | n1series = numpy.zeros(t_max + burnin + 1, dtype=float) 58 | n2series = numpy.zeros(t_max + burnin + 1, dtype=float) 59 | redseries = numpy.zeros(t_max + burnin + 1, dtype=float) 60 | 61 | def schaffer(nt, Tt, r, psi): 62 | return nt * (r * (1.0 - nt)) * numpy.exp(psi * Tt) 63 | 64 | def step_annual(nt0, ntD, TtD, Sa, r, psi): 65 | return nt0 * Sa + max(schaffer(ntD, TtD, r, psi), 0.0) 66 | 67 | n1series[:max(D1, D2)+1] = 0.5 * rng.uniform(0, 1, size=max(D1, D2)+1) 68 | n2series[:max(D1, D2)+1] = 0.5 * rng.uniform(0, 1, size=max(D1, D2)+1) 69 | whiteseries = -rng.uniform(0, 1, size=redseries.shape) + 0.5 70 | 71 | assert numpy.all(n1series >= 0.0) 72 | assert numpy.all(n2series >= 0.0) 73 | 74 | for i in range(redseries.shape[0]): 75 | if i >= noiseparam: 76 | redseries[i] = numpy.mean(whiteseries[i - noiseparam : i]) 77 | else: 78 | redseries[i] = 0.0 79 | 80 | pseries = (redseries - numpy.mean(redseries)) / numpy.std(redseries) 81 | 82 | for i in range(max(D1, D2) + 1, n1series.shape[0]): 83 | n1series[i] = step_annual(n1series[i-1], n1series[i-1-D1], pseries[i-1-D1], Sa1, r1, psi) 84 | n2series[i] = step_annual(n2series[i-1], n2series[i-1-D2], pseries[i-1-D2], Sa2, r2, 1.2 * psi) 85 | 86 | if n1series[i] < 0.0 or n2series[i] < 0.0: 87 | print n1series[i], n2series[i] 88 | 89 | assert n1series[i] > 0.0 90 | assert n2series[i] > 0.0 91 | 92 | return n1series[burnin:], n2series[burnin:], pseries[burnin:] 93 | 94 | def multistrain_sde( 95 | random_seed=None, 96 | dt_euler=None, 97 | adaptive=None, 98 | t_end=None, 99 | dt_output=None, 100 | n_pathogens=None, 101 | S_init=None, 102 | I_init=None, 103 | mu=None, 104 | nu=None, 105 | gamma=None, 106 | beta0=None, 107 | beta_change_start=None, 108 | beta_slope=None, 109 | psi=None, 110 | omega=None, 111 | eps=None, 112 | sigma=None, 113 | 114 | corr_proc=None, 115 | sd_proc=None, 116 | 117 | shared_obs=False, 118 | sd_obs=None, 119 | 120 | shared_obs_C=False, 121 | sd_obs_C=None, 122 | 123 | tol=None 124 | ): 125 | if random_seed is None: 126 | sys_rand = random.SystemRandom() 127 | random_seed = sys_rand.randint(0, 2**31 - 1) 128 | rng = random.Random() 129 | rng.seed(random_seed) 130 | 131 | pathogen_ids = range(n_pathogens) 132 | 133 | stochastic = sum([sd_proc[i] > 0.0 for i in pathogen_ids]) > 0 134 | assert not (adaptive and stochastic) 135 | 136 | has_obs_error = (sd_obs is not None) and (sum([sd_obs[i] > 0.0 for i in pathogen_ids]) > 0) 137 | has_obs_error_C = (sd_obs_C is not None) and (sum([sd_obs_C[i] > 0.0 for i in pathogen_ids]) > 0) 138 | 139 | log_mu = log(mu) 140 | log_gamma = [float('-inf') if gamma[i] == 0.0 else log(gamma[i]) for i in range(n_pathogens)] 141 | 142 | n_output = int(ceil(t_end / dt_output)) 143 | 144 | def beta_t(t, pathogen_id): 145 | return (beta0[pathogen_id] + max(0.0, t - beta_change_start[pathogen_id]) * beta_slope[pathogen_id]) * ( 146 | 1.0 + eps[pathogen_id] * sin( 147 | 2.0 * pi / psi[pathogen_id] * (t - omega[pathogen_id] * psi[pathogen_id]) 148 | ) 149 | ) 150 | 151 | def step(t, h, logS, logI, CC): 152 | neg_inf = float('-inf') 153 | 154 | sqrt_h = sqrt(h) 155 | 156 | log_betas = [log(beta_t(t, i)) for i in pathogen_ids] 157 | try: 158 | logR = [log1p(-(exp(logS[i]) + exp(logI[i]))) for i in pathogen_ids] 159 | except: 160 | R = [max(0.0, 1.0 - exp(logS[i]) - exp(logI[i])) for i in pathogen_ids] 161 | logR = [neg_inf if R[i] == 0 else log(R[i]) for i in pathogen_ids] 162 | 163 | if stochastic: 164 | if corr_proc == 1.0: 165 | noise = [rng.gauss(0.0, 1.0)] * n_pathogens 166 | else: 167 | noise = [rng.gauss(0.0, 1.0) for i in pathogen_ids] 168 | if corr_proc > 0.0: 169 | assert n_pathogens == 2 170 | noise[1] = corr_proc * noise[0] + sqrt(1 - corr_proc*corr_proc) * noise[1] 171 | for i in pathogen_ids: 172 | noise[i] *= sd_proc[i] 173 | 174 | dlogS = [0.0 for i in pathogen_ids] 175 | dlogI = [0.0 for i in pathogen_ids] 176 | dCC = [0.0 for i in pathogen_ids] 177 | 178 | for i in pathogen_ids: 179 | dlogS[i] += (exp(log_mu - logS[i]) - mu) * h 180 | if gamma[i] > 0.0 and logR[i] > neg_inf: 181 | dlogS[i] += exp(log_gamma[i] + logR[i] - logS[i]) * h 182 | for j in pathogen_ids: 183 | if i != j: 184 | dlogSRij = sigma[i][j] * exp(log_betas[j] + logI[j]) 185 | dlogS[i] -= dlogSRij * h 186 | if stochastic: 187 | dlogS[i] -= dlogSRij * noise[j] * sqrt_h 188 | dlogS[i] -= exp(log_betas[i] + logI[i]) * h 189 | dlogI[i] += exp(log_betas[i] + logS[i]) * h 190 | dCC[i] += exp(log_betas[i] + logS[i] + logI[i]) * h 191 | if stochastic: 192 | dlogS[i] -= exp(log_betas[i] + logI[i]) * noise[i] * sqrt_h 193 | dlogI[i] += exp(log_betas[i] + logS[i]) * noise[i] * sqrt_h 194 | dCC[i] += exp(log_betas[i] + logS[i] + logI[i]) * noise[i] * sqrt_h 195 | dlogI[i] -= (nu[i] + mu) * h 196 | 197 | return [logS[i] + dlogS[i] for i in pathogen_ids], \ 198 | [logI[i] + dlogI[i] for i in pathogen_ids], \ 199 | [CC[i] + dCC[i] for i in pathogen_ids] 200 | 201 | logS = [log(S_init[i]) for i in pathogen_ids] 202 | logI = [log(I_init[i]) for i in pathogen_ids] 203 | CC = [0.0 for i in pathogen_ids] 204 | h = dt_euler 205 | 206 | 207 | ts = [0.0] 208 | logSs = [logS] 209 | logIs = [logI] 210 | CCs = [CC] 211 | Cs = [CC] 212 | 213 | if adaptive: 214 | sum_log_h_dt = 0.0 215 | for output_iter in range(n_output): 216 | min_h = h 217 | 218 | t = output_iter * dt_output 219 | t_next_output = (output_iter + 1) * dt_output 220 | 221 | while t < t_next_output: 222 | if h < min_h: 223 | min_h = h 224 | 225 | t_next = t + h 226 | if t_next > t_next_output: 227 | t_next = t_next_output 228 | logS_full, logI_full, CC_full = step(t, t_next - t, logS, logI, CC) 229 | if adaptive: 230 | t_half = t + (t_next - t)/2.0 231 | logS_half, logI_half, CC_half = step(t, t_half - t, logS, logI, CC) 232 | logS_half2, logI_half2, CC_half2 = step(t_half, t_next - t_half, logS_half, logI_half, CC_half) 233 | 234 | errorS = [logS_half2[i] - logS_full[i] for i in pathogen_ids] 235 | errorI = [logI_half2[i] - logI_full[i] for i in pathogen_ids] 236 | errorCC = [CC_half2[i] - CC_full[i] for i in pathogen_ids] 237 | max_error = max([abs(x) for x in (errorS + errorI + errorCC)]) 238 | 239 | if max_error > 0.0: 240 | h = 0.9 * (t_next - t) * tol / max_error 241 | else: 242 | h *= 2.0 243 | 244 | if max_error < tol: 245 | sum_log_h_dt += (t_next - t) * log(t_next - t) 246 | 247 | logS = [logS_full[i] + errorS[i] for i in pathogen_ids] 248 | logI = [logI_full[i] + errorI[i] for i in pathogen_ids] 249 | CC = [CC_full[i] + errorCC[i] for i in pathogen_ids] 250 | t = t_next 251 | else: 252 | logS = logS_full 253 | logI = logI_full 254 | CC = CC_full 255 | t = t_next 256 | ts.append(t) 257 | logSs.append(logS) 258 | if not has_obs_error: 259 | logIs.append(logI) 260 | else: 261 | if shared_obs: 262 | obs_err = rng.gauss(0.0, 1.0) 263 | obs_errs = [obs_err * sd_obs[i] for i in pathogen_ids] 264 | else: 265 | obs_errs = [rng.gauss(0.0, sd_obs[i]) for i in pathogen_ids] 266 | logIs.append([logI[i] + obs_errs[i] for i in pathogen_ids]) 267 | CCs.append(CC) 268 | if has_obs_error_C: 269 | if shared_obs_C: 270 | obs_err = rng.gauss(0.0, 1.0) 271 | obs_errs = [obs_err * sd_obs_C[i] for i in pathogen_ids] 272 | else: 273 | obs_errs = [rng.gauss(0.0, sd_obs_C[i]) for i in pathogen_ids] 274 | else: 275 | obs_errs = [0.0 for i in pathogen_ids] 276 | Cs.append([max(0.0, CCs[-1][i] - CCs[-2][i] + obs_errs[i]) for i in pathogen_ids]) 277 | 278 | result = OrderedDict([ 279 | ('t', ts), 280 | ('logS', logSs), 281 | ('logI', logIs), 282 | ('C', Cs), 283 | ('random_seed', random_seed) 284 | ]) 285 | if adaptive: 286 | result.dt_euler_harmonic_mean = exp(sum_log_h_dt / t) 287 | return result 288 | 289 | if __name__ == '__main__': 290 | stdin_data = sys.stdin.read() 291 | sys.stderr.write(stdin_data) 292 | params = json.loads(stdin_data) 293 | result = globals()[sys.argv[1]](**params) 294 | sys.stderr.write('{0}'.format(result)) 295 | json.dump(result, sys.stdout) 296 | 297 | 298 | 299 | -------------------------------------------------------------------------------- /models_pypy.py: -------------------------------------------------------------------------------- 1 | models.py -------------------------------------------------------------------------------- /npybuffer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | import numpy 6 | from cStringIO import StringIO 7 | 8 | def ndarray_to_npy_buffer(x): 9 | f = StringIO() 10 | numpy.save(f, x) 11 | buf = buffer(f.getvalue()) 12 | f.close() 13 | return buf 14 | 15 | def npy_buffer_to_ndarray(x): 16 | f = StringIO(x) 17 | arr = numpy.load(f) 18 | f.close() 19 | return arr 20 | -------------------------------------------------------------------------------- /optimal_embedding/INSTALL: -------------------------------------------------------------------------------- 1 | To install type 2 | 3 | ./configure 4 | make 5 | make install 6 | 7 | and observe the warnings :-) 8 | 9 | -------------------------------------------------------------------------------- /optimal_embedding/Makefile: -------------------------------------------------------------------------------- 1 | SHELL = /bin/sh 2 | 3 | prefix = /Users/ebaskerv 4 | exec_prefix = ${prefix} 5 | BINDIR = ${exec_prefix}/bin 6 | CC = cc 7 | FC = 8 | HAVE_NR = @HAVE_NR@ 9 | 10 | all: 11 | @head -20 README 12 | -if test -n "${CC}"; then (cd source_c && $(MAKE) $@); fi 13 | 14 | install: do_install missing 15 | @echo "******************************************************************" 16 | @echo "the following programs have been installed in" ${BINDIR} 17 | @echo "type" 18 | @echo " $$ progname -h" 19 | @echo "for individual options" 20 | @echo "" 21 | @grep Usage install.log | sed "s/ *Usage./ /" 22 | @echo " (written to install.log)" 23 | @echo "" 24 | -@if test -s missing.log; then \ 25 | echo "the following programs could not be made/installed"; \ 26 | sed "s/^/ /" missing.log; \ 27 | echo " (written to missing.log)"; \ 28 | echo ""; \ 29 | fi 30 | @echo "browse index.html for documentation" 31 | 32 | do_install: 33 | @rm -f install.log 34 | @test -d ${BINDIR} || (echo "${BINDIR} does not exist") 35 | @test -d ${BINDIR} -a -n "${CC}" && (cd source_c && $(MAKE) install) 36 | 37 | missing: 38 | @rm -f missing.log 39 | -if test -n "${CC}"; then (cd source_c && $(MAKE) $@); fi 40 | 41 | uninstall: 42 | -if test -n "${CC}"; then (cd source_c && $(MAKE) $@); fi 43 | 44 | clean: 45 | -(cd source_c && $(MAKE) $@) 46 | -@rm -f install.log missing.log config.* 47 | -find . \( -name "*~" -o -name "#*#" -o -name "*.o" \ 48 | -o -name "lib*.a" \) -exec rm -f {} \; 49 | 50 | mproper: clean 51 | -rm -f *.zip *.tar.gz *.tar.bz2 *.ZIP 52 | -find . \( -name "Makefile" -o -name "stdin_*" -o -name tr \ 53 | \) -exec rm -f {} \; 54 | 55 | package: zip gz bzip2 56 | 57 | zip: mproper 58 | -(file=`basename $$PWD`; \ 59 | cd `dirname $$PWD`; \ 60 | rm -f $$file.zip; \ 61 | zip -r $$file.zip $$file; \ 62 | cd $$file; \ 63 | ls -l `dirname $$PWD`/$$file.zip ) 64 | 65 | gz: mproper 66 | -(file=`basename $$PWD`; \ 67 | cd `dirname $$PWD`; \ 68 | tar -vchf $$file.tar $$file; \ 69 | gzip -vf $$file.tar; \ 70 | cd $$file; \ 71 | ls -l `dirname $$PWD`/$$file.tar.gz ) 72 | 73 | bzip2: mproper 74 | -(file=`basename $$PWD`; \ 75 | cd `dirname $$PWD`; \ 76 | tar -vchf $$file.tar $$file; \ 77 | bzip2 -vf $$file.tar; \ 78 | cd $$file; \ 79 | ls -l `dirname $$PWD`/$$file.tar.bz2 ) 80 | -------------------------------------------------------------------------------- /optimal_embedding/Makefile.in: -------------------------------------------------------------------------------- 1 | SHELL = /bin/sh 2 | 3 | prefix = @prefix@ 4 | exec_prefix = @exec_prefix@ 5 | BINDIR = @bindir@ 6 | CC = @CC@ 7 | FC = @FC@ 8 | HAVE_NR = @HAVE_NR@ 9 | 10 | all: 11 | @head -20 README 12 | -if test -n "${CC}"; then (cd source_c && $(MAKE) $@); fi 13 | 14 | install: do_install missing 15 | @echo "******************************************************************" 16 | @echo "the following programs have been installed in" ${BINDIR} 17 | @echo "type" 18 | @echo " $$ progname -h" 19 | @echo "for individual options" 20 | @echo "" 21 | @grep Usage install.log | sed "s/ *Usage./ /" 22 | @echo " (written to install.log)" 23 | @echo "" 24 | -@if test -s missing.log; then \ 25 | echo "the following programs could not be made/installed"; \ 26 | sed "s/^/ /" missing.log; \ 27 | echo " (written to missing.log)"; \ 28 | echo ""; \ 29 | fi 30 | @echo "browse index.html for documentation" 31 | 32 | do_install: 33 | @rm -f install.log 34 | @test -d ${BINDIR} || (echo "${BINDIR} does not exist") 35 | @test -d ${BINDIR} -a -n "${CC}" && (cd source_c && $(MAKE) install) 36 | 37 | missing: 38 | @rm -f missing.log 39 | -if test -n "${CC}"; then (cd source_c && $(MAKE) $@); fi 40 | 41 | uninstall: 42 | -if test -n "${CC}"; then (cd source_c && $(MAKE) $@); fi 43 | 44 | clean: 45 | -(cd source_c && $(MAKE) $@) 46 | -@rm -f install.log missing.log config.* 47 | -find . \( -name "*~" -o -name "#*#" -o -name "*.o" \ 48 | -o -name "lib*.a" \) -exec rm -f {} \; 49 | 50 | mproper: clean 51 | -rm -f *.zip *.tar.gz *.tar.bz2 *.ZIP 52 | -find . \( -name "Makefile" -o -name "stdin_*" -o -name tr \ 53 | \) -exec rm -f {} \; 54 | 55 | package: zip gz bzip2 56 | 57 | zip: mproper 58 | -(file=`basename $$PWD`; \ 59 | cd `dirname $$PWD`; \ 60 | rm -f $$file.zip; \ 61 | zip -r $$file.zip $$file; \ 62 | cd $$file; \ 63 | ls -l `dirname $$PWD`/$$file.zip ) 64 | 65 | gz: mproper 66 | -(file=`basename $$PWD`; \ 67 | cd `dirname $$PWD`; \ 68 | tar -vchf $$file.tar $$file; \ 69 | gzip -vf $$file.tar; \ 70 | cd $$file; \ 71 | ls -l `dirname $$PWD`/$$file.tar.gz ) 72 | 73 | bzip2: mproper 74 | -(file=`basename $$PWD`; \ 75 | cd `dirname $$PWD`; \ 76 | tar -vchf $$file.tar $$file; \ 77 | bzip2 -vf $$file.tar; \ 78 | cd $$file; \ 79 | ls -l `dirname $$PWD`/$$file.tar.bz2 ) 80 | -------------------------------------------------------------------------------- /optimal_embedding/README: -------------------------------------------------------------------------------- 1 | costfunc: computes a cost function for evaluating attractor reconstructions 2 | author: Lucas C. Uzal 3 | 4 | For details see: 5 | L.C. Uzal, G.L. Grinblat and P.F. Verdes 6 | "Optimal reconstruction of dynamical systems: A noise amplification approach" 7 | (to be published) 8 | 9 | This program is based on TISEAN - Nonlinear time series project 10 | _______________________________________________________________________________ 11 | 12 | _/_/_/_/_/ _/ _/_/_/ _/_/_/_/ _/_/ _/ _/ 13 | _/ _/ _/ _/ _/ _/ _/ _/ _/ 14 | _/ _/ _/ _/ _/ _/ _/_/ _/ 15 | _/ _/ _/_/_/ _/_/_/_/ _/_/_/_/ _/ _/ _/ 16 | _/ _/ _/ _/ _/ _/ _/ _/_/ 17 | _/ _/ _/ _/ _/ _/ _/ _/ _/ 18 | _/ _/ _/_/_/ _/_/_/_/ _/ _/ _/ _/ 19 | 20 | Nonlinear time series project 21 | Copyright (C) Rainer Hegger & Thomas Schreiber (1998-2007) 22 | _______________________________________________________________________________ 23 | 24 | All programs are given WITHOUT ANY WARRANTY; without even the implied 25 | warranty of merchantability or fitness for a particular purpose. If you decide 26 | to use them, you do so AT YOUR OWN RISK. 27 | 28 | The copyright to each program is held by the person named in the source code. 29 | You may use and refer to them as you do with any scientific publication. 30 | 31 | ** To install type 32 | 33 | > ./configure 34 | > make 35 | > make install 36 | 37 | and observe the warnings :-) 38 | 39 | Have fun. 40 | -------------------------------------------------------------------------------- /optimal_embedding/autoscan.log: -------------------------------------------------------------------------------- 1 | autoscan: warning: missing AC_CHECK_FUNCS([pow]) wanted by: 2 | source_c/lyap_k.c:292 3 | source_c/lyap_k.c:298 4 | source_c/sav_gol.c:94 5 | source_c/sav_gol.c:103 6 | source_c/d2.c:381 7 | source_c/polynom.c:282 8 | source_c/resample.c:113 9 | source_c/resample.c:144 10 | source_c/boxcount.c:138 11 | source_c/boxcount.c:187 12 | source_c/boxcount.c:286 13 | unsupported/d2.c:307 14 | unsupported/lyap_k.cc:268 15 | unsupported/lyap_k.cc:272 16 | autoscan: warning: missing AC_CHECK_FUNCS([sqrt]) wanted by: 17 | source_c/ghkss.c:193 18 | source_c/ghkss.c:268 19 | source_c/fsle.c:228 20 | source_c/mem_spec.c:187 21 | source_c/onestep.c:225 22 | source_c/onestep.c:232 23 | source_c/ll-ar.c:341 24 | source_c/ll-ar.c:342 25 | source_c/false_nearest.c:273 26 | source_c/false_nearest.c:285 27 | source_c/false_nearest.c:290 28 | source_c/polyback.c:147 29 | source_c/nstat_z.c:431 30 | source_c/nstat_z.c:434 31 | source_c/rbf.c:97 32 | source_c/rbf.c:134 33 | source_c/rbf.c:206 34 | source_c/rbf.c:331 35 | source_c/rbf.c:344 36 | source_c/lm-ga.c:234 37 | source_c/lm-ga.c:235 38 | source_c/lyap_spec.c:309 39 | source_c/lyap_spec.c:526 40 | source_c/lyap_spec.c:530 41 | source_c/lyap_spec.c:539 42 | source_c/lyap_spec.c:543 43 | source_c/xzero.c:205 44 | source_c/xzero.c:213 45 | source_c/ar-model.c:171 46 | source_c/ar-model.c:293 47 | source_c/ar-model.c:327 48 | source_c/zeroth.c:264 49 | source_c/zeroth.c:286 50 | source_c/polynom.c:288 51 | source_c/polynom.c:292 52 | source_c/polynomp.c:146 53 | source_c/makenoise.c:109 54 | source_c/arima-model.c:236 55 | source_c/arima-model.c:489 56 | source_c/arima-model.c:515 57 | source_c/arima-model.c:578 58 | source_c/routines/eigen.c:17 59 | source_c/routines/eigen.c:19 60 | source_c/routines/eigen.c:41 61 | source_c/routines/eigen.c:41 62 | source_c/routines/variance.c:20 63 | source_c/routines/rand.c:123 64 | unsupported/eigen.c:35 65 | unsupported/eigen.c:37 66 | unsupported/eigen.c:59 67 | unsupported/eigen.c:59 68 | unsupported/dft.c:36 69 | unsupported/dft.c:65 70 | unsupported/noise.c:109 71 | unsupported/sing.c:641 72 | unsupported/rand.c:139 73 | unsupported/surrogates.c:121 74 | unsupported/surrogates.c:122 75 | autoscan: warning: missing AC_CHECK_FUNCS([strrchr]) wanted by: 76 | unsupported/arguments.c:176 77 | unsupported/arguments.c:179 78 | autoscan: warning: missing AC_CHECK_FUNCS([strstr]) wanted by: 79 | source_c/av-d2.c:117 80 | autoscan: warning: missing AC_CHECK_HEADERS([stddef.h]) wanted by: 81 | source_c/routines/eigen.c:4 82 | unsupported/eigen.c:3 83 | unsupported/clean.c:3 84 | unsupported/dft.c:5 85 | unsupported/surro.c:5 86 | unsupported/noise.c:8 87 | unsupported/timerev.c:10 88 | unsupported/sing.c:42 89 | unsupported/arguments.c:6 90 | unsupported/autocor3.c:10 91 | unsupported/surrogates.c:11 92 | autoscan: warning: missing AC_FUNC_ERROR_AT_LINE wanted by: 93 | unsupported/make_ps.cc:29 94 | unsupported/make_ps.cc:151 95 | autoscan: warning: missing AC_FUNC_MALLOC wanted by: 96 | source_c/polypar.c:91 97 | source_c/recurr.c:197 98 | source_c/recurr.c:198 99 | source_c/recurr.c:200 100 | source_c/ghkss.c:168 101 | source_c/ghkss.c:270 102 | source_c/ghkss.c:272 103 | source_c/ghkss.c:274 104 | source_c/ghkss.c:275 105 | source_c/ghkss.c:277 106 | source_c/ghkss.c:289 107 | source_c/ghkss.c:291 108 | source_c/ghkss.c:292 109 | source_c/ghkss.c:293 110 | source_c/ghkss.c:295 111 | source_c/ghkss.c:296 112 | source_c/ghkss.c:297 113 | source_c/ghkss.c:298 114 | source_c/ghkss.c:299 115 | source_c/ghkss.c:301 116 | source_c/fsle.c:231 117 | source_c/fsle.c:239 118 | source_c/fsle.c:240 119 | source_c/mem_spec.c:78 120 | source_c/mem_spec.c:79 121 | source_c/mem_spec.c:171 122 | source_c/onestep.c:99 123 | source_c/onestep.c:100 124 | source_c/onestep.c:102 125 | source_c/onestep.c:178 126 | source_c/onestep.c:183 127 | source_c/onestep.c:184 128 | source_c/onestep.c:185 129 | source_c/onestep.c:186 130 | source_c/onestep.c:187 131 | source_c/onestep.c:189 132 | source_c/ll-ar.c:273 133 | source_c/ll-ar.c:274 134 | source_c/ll-ar.c:275 135 | source_c/ll-ar.c:276 136 | source_c/ll-ar.c:278 137 | source_c/ll-ar.c:279 138 | source_c/ll-ar.c:280 139 | source_c/ll-ar.c:281 140 | source_c/ll-ar.c:283 141 | source_c/ll-ar.c:284 142 | source_c/ll-ar.c:285 143 | source_c/ll-ar.c:286 144 | source_c/ll-ar.c:287 145 | source_c/ll-ar.c:288 146 | source_c/ll-ar.c:289 147 | source_c/false_nearest.c:223 148 | source_c/false_nearest.c:224 149 | source_c/false_nearest.c:225 150 | source_c/false_nearest.c:227 151 | source_c/false_nearest.c:238 152 | source_c/false_nearest.c:239 153 | source_c/lyap_k.c:170 154 | source_c/lyap_k.c:171 155 | source_c/lyap_k.c:173 156 | source_c/lyap_k.c:174 157 | source_c/lyap_k.c:176 158 | source_c/lyap_k.c:277 159 | source_c/lyap_k.c:278 160 | source_c/lyap_k.c:279 161 | source_c/lyap_k.c:281 162 | source_c/lyap_k.c:282 163 | source_c/lyap_k.c:284 164 | source_c/lyap_k.c:285 165 | source_c/lyap_k.c:287 166 | source_c/polyback.c:99 167 | source_c/polyback.c:100 168 | source_c/polyback.c:102 169 | source_c/polyback.c:205 170 | source_c/polyback.c:207 171 | source_c/polyback.c:211 172 | source_c/polyback.c:221 173 | source_c/polyback.c:222 174 | source_c/polyback.c:225 175 | source_c/polyback.c:258 176 | source_c/polyback.c:259 177 | source_c/polyback.c:261 178 | source_c/lyap_r.c:198 179 | source_c/lyap_r.c:199 180 | source_c/lyap_r.c:200 181 | source_c/lyap_r.c:201 182 | source_c/nstat_z.c:139 183 | source_c/nstat_z.c:234 184 | source_c/nstat_z.c:235 185 | source_c/nstat_z.c:238 186 | source_c/nstat_z.c:240 187 | source_c/nstat_z.c:340 188 | source_c/nstat_z.c:341 189 | source_c/nstat_z.c:342 190 | source_c/nstat_z.c:343 191 | source_c/nstat_z.c:344 192 | source_c/nstat_z.c:347 193 | source_c/nstat_z.c:358 194 | source_c/nrlazy.c:192 195 | source_c/nrlazy.c:193 196 | source_c/nrlazy.c:204 197 | source_c/nrlazy.c:205 198 | source_c/nrlazy.c:206 199 | source_c/nrlazy.c:208 200 | source_c/nrlazy.c:210 201 | source_c/nrlazy.c:211 202 | source_c/nrlazy.c:213 203 | source_c/nrlazy.c:214 204 | source_c/nrlazy.c:237 205 | source_c/rbf.c:119 206 | source_c/rbf.c:151 207 | source_c/rbf.c:153 208 | source_c/rbf.c:154 209 | source_c/rbf.c:215 210 | source_c/rbf.c:277 211 | source_c/rbf.c:278 212 | source_c/rbf.c:280 213 | source_c/low121.c:102 214 | source_c/sav_gol.c:83 215 | source_c/sav_gol.c:85 216 | source_c/sav_gol.c:86 217 | source_c/sav_gol.c:88 218 | source_c/lm-ga.c:176 219 | source_c/lm-ga.c:177 220 | source_c/lm-ga.c:178 221 | source_c/lm-ga.c:179 222 | source_c/lm-ga.c:181 223 | source_c/lm-ga.c:182 224 | source_c/lm-ga.c:183 225 | source_c/lm-ga.c:184 226 | source_c/lm-ga.c:185 227 | source_c/pca.c:119 228 | source_c/pca.c:120 229 | source_c/pca.c:121 230 | source_c/pca.c:122 231 | source_c/pca.c:124 232 | source_c/pca.c:208 233 | source_c/pca.c:301 234 | source_c/mutual.c:145 235 | source_c/mutual.c:146 236 | source_c/mutual.c:147 237 | source_c/mutual.c:149 238 | source_c/mutual.c:150 239 | source_c/d2.c:135 240 | source_c/d2.c:136 241 | source_c/d2.c:137 242 | source_c/d2.c:138 243 | source_c/d2.c:185 244 | source_c/d2.c:364 245 | source_c/d2.c:365 246 | source_c/d2.c:372 247 | source_c/d2.c:373 248 | source_c/d2.c:374 249 | source_c/d2.c:376 250 | source_c/d2.c:377 251 | source_c/d2.c:378 252 | source_c/av-d2.c:94 253 | source_c/av-d2.c:95 254 | source_c/lyap_spec.c:197 255 | source_c/lyap_spec.c:291 256 | source_c/lyap_spec.c:292 257 | source_c/lyap_spec.c:294 258 | source_c/lyap_spec.c:329 259 | source_c/lyap_spec.c:331 260 | source_c/lyap_spec.c:407 261 | source_c/lyap_spec.c:408 262 | source_c/lyap_spec.c:409 263 | source_c/lyap_spec.c:410 264 | source_c/lyap_spec.c:411 265 | source_c/lyap_spec.c:422 266 | source_c/lyap_spec.c:437 267 | source_c/lyap_spec.c:439 268 | source_c/lyap_spec.c:441 269 | source_c/lyap_spec.c:442 270 | source_c/lyap_spec.c:444 271 | source_c/lyap_spec.c:446 272 | source_c/lyap_spec.c:447 273 | source_c/lyap_spec.c:448 274 | source_c/lyap_spec.c:449 275 | source_c/lyap_spec.c:451 276 | source_c/lyap_spec.c:453 277 | source_c/lyap_spec.c:454 278 | source_c/lyap_spec.c:456 279 | source_c/lyap_spec.c:484 280 | source_c/nstep.c:162 281 | source_c/nstep.c:324 282 | source_c/nstep.c:325 283 | source_c/nstep.c:334 284 | source_c/nstep.c:336 285 | source_c/nstep.c:337 286 | source_c/nstep.c:339 287 | source_c/nstep.c:340 288 | source_c/nstep.c:341 289 | source_c/nstep.c:343 290 | source_c/nstep.c:345 291 | source_c/nstep.c:346 292 | source_c/nstep.c:347 293 | source_c/nstep.c:348 294 | source_c/nstep.c:350 295 | source_c/xzero.c:163 296 | source_c/xzero.c:164 297 | source_c/xzero.c:165 298 | source_c/xzero.c:166 299 | source_c/xzero.c:167 300 | source_c/xzero.c:172 301 | source_c/ar-model.c:142 302 | source_c/ar-model.c:157 303 | source_c/ar-model.c:181 304 | source_c/ar-model.c:183 305 | source_c/ar-model.c:262 306 | source_c/ar-model.c:271 307 | source_c/ar-model.c:272 308 | source_c/ar-model.c:274 309 | source_c/ar-model.c:276 310 | source_c/ar-model.c:283 311 | source_c/ar-model.c:285 312 | source_c/histogram.c:111 313 | source_c/zeroth.c:187 314 | source_c/zeroth.c:188 315 | source_c/zeroth.c:189 316 | source_c/zeroth.c:190 317 | source_c/zeroth.c:199 318 | source_c/zeroth.c:200 319 | source_c/zeroth.c:201 320 | source_c/zeroth.c:202 321 | source_c/zeroth.c:203 322 | source_c/zeroth.c:204 323 | source_c/zeroth.c:205 324 | source_c/zeroth.c:207 325 | source_c/zeroth.c:208 326 | source_c/zeroth.c:214 327 | source_c/polynom.c:127 328 | source_c/polynom.c:128 329 | source_c/polynom.c:130 330 | source_c/polynom.c:264 331 | source_c/polynom.c:268 332 | source_c/polynom.c:271 333 | source_c/polynomp.c:97 334 | source_c/polynomp.c:98 335 | source_c/polynomp.c:100 336 | source_c/polynomp.c:225 337 | source_c/polynomp.c:227 338 | source_c/polynomp.c:240 339 | source_c/delay.c:108 340 | source_c/delay.c:154 341 | source_c/delay.c:225 342 | source_c/delay.c:239 343 | source_c/resample.c:105 344 | source_c/resample.c:107 345 | source_c/resample.c:108 346 | source_c/resample.c:109 347 | source_c/makenoise.c:176 348 | source_c/makenoise.c:178 349 | source_c/makenoise.c:184 350 | source_c/boxcount.c:94 351 | source_c/boxcount.c:96 352 | source_c/boxcount.c:116 353 | source_c/boxcount.c:117 354 | source_c/boxcount.c:165 355 | source_c/boxcount.c:166 356 | source_c/boxcount.c:270 357 | source_c/boxcount.c:271 358 | source_c/boxcount.c:272 359 | source_c/boxcount.c:275 360 | source_c/arima-model.c:110 361 | source_c/arima-model.c:113 362 | source_c/arima-model.c:128 363 | source_c/arima-model.c:131 364 | source_c/arima-model.c:203 365 | source_c/arima-model.c:218 366 | source_c/arima-model.c:246 367 | source_c/arima-model.c:248 368 | source_c/arima-model.c:290 369 | source_c/arima-model.c:292 370 | source_c/arima-model.c:381 371 | source_c/arima-model.c:401 372 | source_c/arima-model.c:402 373 | source_c/arima-model.c:404 374 | source_c/arima-model.c:406 375 | source_c/arima-model.c:413 376 | source_c/arima-model.c:415 377 | source_c/arima-model.c:437 378 | source_c/arima-model.c:439 379 | source_c/arima-model.c:445 380 | source_c/arima-model.c:447 381 | source_c/arima-model.c:448 382 | source_c/arima-model.c:462 383 | source_c/arima-model.c:463 384 | source_c/arima-model.c:465 385 | source_c/arima-model.c:467 386 | source_c/routines/get_multi_series.c:49 387 | source_c/routines/get_multi_series.c:80 388 | source_c/routines/get_multi_series.c:90 389 | source_c/routines/get_multi_series.c:92 390 | source_c/routines/rand.c:45 391 | source_c/routines/rand.c:46 392 | source_c/routines/rand.c:47 393 | source_c/routines/rand.c:48 394 | source_c/routines/get_series.c:28 395 | source_c/routines/invert_matrix.c:17 396 | source_c/routines/invert_matrix.c:19 397 | source_c/routines/invert_matrix.c:22 398 | source_c/routines/invert_matrix.c:24 399 | source_c/routines/invert_matrix.c:27 400 | source_c/routines/make_multi_index.c:21 401 | source_c/routines/make_multi_index.c:23 402 | unsupported/histogram_tisean2.1.c:157 403 | unsupported/histogram_tisean2.1.c:158 404 | unsupported/rank.c:26 405 | unsupported/rank.c:127 406 | unsupported/svd.c:99 407 | unsupported/svd.c:100 408 | unsupported/svd.c:101 409 | unsupported/svd.c:102 410 | unsupported/svd.c:103 411 | unsupported/svd.c:105 412 | unsupported/clean.c:15 413 | unsupported/clean.c:17 414 | unsupported/clean.c:45 415 | unsupported/clean.c:56 416 | unsupported/clean.c:57 417 | unsupported/clean.c:92 418 | unsupported/dft.c:22 419 | unsupported/dft.c:53 420 | unsupported/dft.c:84 421 | unsupported/dft.c:108 422 | unsupported/surro.c:40 423 | unsupported/surro.c:41 424 | unsupported/surro.c:42 425 | unsupported/noise.c:87 426 | unsupported/d2.c:115 427 | unsupported/d2.c:116 428 | unsupported/d2.c:117 429 | unsupported/d2.c:118 430 | unsupported/d2.c:164 431 | unsupported/d2.c:296 432 | unsupported/d2.c:297 433 | unsupported/d2.c:298 434 | unsupported/d2.c:299 435 | unsupported/d2.c:300 436 | unsupported/d2.c:302 437 | unsupported/d2.c:303 438 | unsupported/d2.c:304 439 | unsupported/make_ps.cc:128 440 | unsupported/make_ps.cc:129 441 | unsupported/make_ps.cc:130 442 | unsupported/rand.c:37 443 | unsupported/rand.c:38 444 | unsupported/rand.c:39 445 | unsupported/rand.c:40 446 | unsupported/rand.c:41 447 | unsupported/surrogates.c:91 448 | unsupported/surrogates.c:92 449 | unsupported/surrogates.c:93 450 | autoscan: warning: missing AC_FUNC_REALLOC wanted by: 451 | source_c/av-d2.c:134 452 | source_c/av-d2.c:135 453 | source_c/boxcount.c:128 454 | source_c/boxcount.c:177 455 | source_c/routines/get_multi_series.c:106 456 | source_c/routines/get_multi_series.c:129 457 | source_c/routines/get_multi_series.c:167 458 | source_c/routines/myfgets.c:22 459 | source_c/routines/get_series.c:41 460 | source_c/routines/get_series.c:63 461 | source_c/routines/get_series.c:87 462 | unsupported/eigen.c:164 463 | unsupported/eigen.c:165 464 | unsupported/clean.c:91 465 | unsupported/noise.c:93 466 | unsupported/noise.c:94 467 | unsupported/timerev.c:79 468 | unsupported/autocor3.c:86 469 | unsupported/surrogates.c:83 470 | autoscan: warning: missing AC_PREREQ wanted by: 471 | autoscan 472 | autoscan: warning: missing AC_PROG_CXX wanted by: 473 | bins.sh:10 474 | bins.sh:13 475 | bins.sh:15 476 | bins.sh:26 477 | bins.sh:29 478 | bins.sh:37 479 | bins.sh:40 480 | unsupported/delay.cc 481 | unsupported/histogram.cc 482 | unsupported/lyap_k.cc 483 | unsupported/make_ps.cc 484 | -------------------------------------------------------------------------------- /optimal_embedding/bins.sh: -------------------------------------------------------------------------------- 1 | #! /bin/csh -f 2 | 3 | echo "This directory contains binary executables" >& RTMP 4 | 5 | switch ($OSTYPE) 6 | 7 | case linux: 8 | echo "making statically linked ELF excutables for linux" 9 | echo "meant for the LINUX operating system\n" >& RTMP 10 | setenv CC "gcc -static -O" 11 | setenv FC "g77 -static -O" 12 | setenv OS "linux" 13 | echo "C compiler used: " $CC >>& RTMP 14 | echo "version:" >>& RTMP 15 | $CC -v >>& RTMP 16 | echo "" >>& RTMP 17 | echo "Fortran compiler used: " $FC >>& RTMP 18 | echo "version:" >>& RTMP 19 | $FC -v >>& RTMP 20 | echo "" >>& RTMP 21 | breaksw 22 | 23 | case osf1: 24 | echo "making statically linked excutables for osf1" 25 | echo "meant for compaq/digital operating systems\n" >& RTMP 26 | setenv CC "cc -non_shared -O" 27 | setenv FC "f77 -non_shared -O" 28 | setenv OS "osf1" 29 | echo "C compiler used: " $CC >>& RTMP 30 | echo "Fortran compiler used: " $FC >>& RTMP 31 | echo "" >>& RTMP 32 | breaksw 33 | 34 | case solaris: 35 | echo "making statically linked ELF excutables for solaris" 36 | echo "meant for solaris/SPARC operating systems\n" >& RTMP 37 | setenv CC "cc -non_shared -O" 38 | setenv FC "g77 -static -O" 39 | setenv OS "osf1-g77" 40 | echo "C compiler used: " $CC >>& RTMP 41 | echo "Fortran compiler used: " $FC >>& RTMP 42 | echo "version:" >>& RTMP 43 | g77 -v >>& RTMP 44 | echo "" >>& RTMP 45 | breaksw 46 | 47 | default: 48 | echo "cannot make " $OSTYPE " executables" 49 | exit 50 | breaksw 51 | 52 | endsw 53 | 54 | make mproper 55 | ./configure --prefix={$PWD}/bin-{$OS} 56 | make install 57 | 58 | file bin-{$OS}/delay && \ 59 | (echo "The executables are in the following format:" >>& RTMP) 60 | file bin-{$OS}/delay | sed "s/.*://" >>& RTMP 61 | mv RTMP bin-{$OS}/README 62 | tar -vcf `basename $PWD`-{$OS}.tar bin-{$OS} 63 | gzip -vf `basename $PWD`-{$OS}.tar 64 | #rm -Rf bin-{$OS} 65 | -------------------------------------------------------------------------------- /optimal_embedding/configure.in: -------------------------------------------------------------------------------- 1 | dnl Process this file with autoconf to produce a configure script. 2 | AC_INIT(source_c/costfunc.c) 3 | 4 | AC_PREFIX_DEFAULT(${HOME}) 5 | 6 | dnl Check for prfix directory and create it if necessary 7 | test "x$prefix" = xNONE && prefix=$ac_default_prefix 8 | 9 | AC_MSG_CHECKING([whether $prefix is a directory and writeable]) 10 | mkdir -p $prefix 2>&5 11 | if test -d $prefix && echo "" > $prefix/test_conf_write \ 12 | && rm -f $prefix/test_conf_write; then 13 | AC_MSG_RESULT(yes) 14 | else 15 | AC_MSG_RESULT(no) 16 | AC_MSG_WARN([ 17 | *** $prefix must be a writeable directory for installation 18 | *** either you provide that or give another one, say mydir, by calling 19 | *** $ ./configure --prefix=mydir 20 | ]) 21 | fi 22 | 23 | dnl Checks for programs. 24 | 25 | for ccc in "$CC" cc gcc acc "cc -Aa"; do 26 | if test -z "$ccc"; then 27 | continue 28 | fi 29 | CC=$ccc 30 | AC_MSG_CHECKING([whether ($CC $CFLAGS $LDFLAGS) works]) 31 | ac_cpp='$CPP $CPPFLAGS' 32 | ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.c 1>&5' 33 | ac_link='$CC -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.c $LIBS 1>&5' 34 | echo '#include "confdefs.h"' > conftest.c 35 | echo 'main(int argc,char **argv){return(0);}' >> conftest.c 36 | if { (eval $ac_link) 2>&5; } && test -s conftest; then 37 | rm -fr conftest* 38 | AC_MSG_RESULT(yes) 39 | break 40 | else 41 | rm -fr conftest* 42 | AC_MSG_RESULT(no) 43 | CC= 44 | fi 45 | done 46 | 47 | if test -z "$CC"; then 48 | AC_MSG_WARN([ 49 | *** No valid ANSI C compiler found 50 | *** You will not be able to use some of the routines 51 | *** If you do have a C compiler called by, say, mycc -ANSI, do: 52 | *** $ setenv CC "mycc -ANSI" 53 | *** and rerun 54 | ]) 55 | fi 56 | 57 | if test -n "$CC" && test -z "$CFLAGS"; then 58 | echo 'void f(){}' > conftest.c 59 | for cflags in -O3 -O2 -O +O3 +O -xO3; do 60 | AC_MSG_CHECKING([whether $CC accepts $cflags]) 61 | if test -z "`$CC $cflags -c conftest.c 2>&1`"; then 62 | AC_MSG_RESULT(yes) 63 | CFLAGS=$cflags 64 | break 65 | else 66 | AC_MSG_RESULT(no) 67 | fi 68 | done 69 | if test -z "$CFLAGS"; then 70 | AC_MSG_WARN([ 71 | *** no valid optimisation flags for $CC found 72 | ]) 73 | fi 74 | rm -f conftest* 75 | fi 76 | 77 | if test -n "$CC"; then 78 | AC_CHECK_LIB(m, main) 79 | 80 | dnl Checks for header files. 81 | AC_HEADER_STDC 82 | AC_CHECK_HEADERS(limits.h malloc.h) 83 | 84 | dnl Checks for typedefs, structures, and compiler characteristics. 85 | AC_C_CONST 86 | if test $ac_cv_c_const = no; then 87 | CC="$CC -Dconst=" 88 | fi 89 | 90 | AC_TYPE_SIZE_T 91 | 92 | dnl Checks for library functions. 93 | AC_FUNC_MEMCMP 94 | fi 95 | 96 | AC_SUBST(CC) 97 | 98 | AC_SUBST(FC) 99 | AC_SUBST(FFLAGS) 100 | 101 | if test -n "$FC"; then 102 | ERRUNIT="" 103 | for iu in 0 1 2 3 4 6 7 8 9; do 104 | AC_MSG_CHECKING([whether Fortran unit $iu is stderr]) 105 | rm -Rf ./config_test_dir 106 | mkdir ./config_test_dir 107 | cd ./config_test_dir 108 | echo " write($iu,'(1ht)')" > test.f 109 | echo " end" >> test.f 110 | (eval $FC $FFLAGS test.f -o test.out) 1>&5 2>&5 111 | if test -z "`./test.out 2>&1 1>/dev/null`"; then 112 | cd .. 113 | rm -Rf ./config_test_dir 114 | AC_MSG_RESULT(no) 115 | else 116 | cd .. 117 | rm -Rf ./config_test_dir 118 | AC_MSG_RESULT(yes) 119 | ERRUNIT=$iu 120 | break 121 | fi 122 | done 123 | if test -z $ERRUNIT; then 124 | ERRUNIT=0 125 | AC_MSG_WARN([ 126 | *** Couldn't determine Fortran stderr unit, assuming unit 0, fingers crossed 127 | ]) 128 | fi 129 | AC_SUBST(ERRUNIT) 130 | fi 131 | 132 | AC_CHECK_PROG(AR,ar,ar,ar) 133 | ARFLAGS=r 134 | AC_MSG_CHECKING([whether ${AR} accepts ${ARFLAGS}]) 135 | if test -n "$CC"; then 136 | echo 'void f(){}' > libtest.c 137 | ${CC} -c libtest.c 138 | else 139 | echo ' end' > libtest.f 140 | ${FC} -c libtest.f 141 | fi 142 | ${AR} ${ARFLAGS} libtest.a libtest.o 1>&5 2>&5 143 | if test -s libtest.a; then 144 | AC_MSG_RESULT(yes) 145 | else 146 | ARFLAGS=-r 147 | AC_MSG_RESULT([no, using ${ARFLAGS} instead]) 148 | fi 149 | rm -f libtest.* 150 | AC_SUBST(ARFLAGS) 151 | 152 | AC_PROG_INSTALL 153 | AC_PROG_MAKE_SET 154 | AC_PROG_RANLIB 155 | 156 | AC_CHECK_PROGS(GP,gnuplot) 157 | if test -n "$GP"; then 158 | AC_MSG_CHECKING(if gnuplot can read from a pipe) 159 | cat > conftest.gnu <&5 1>&5; then 165 | rm -f conftest.gnu 166 | AC_MSG_RESULT([yes 167 | :-) you may try to run $GP on the following files 168 | after you installed everything:]) 169 | find examples -name "*.gnu" -print | sed "s%\./% %" 170 | echo "" 171 | else 172 | rm -f conftest.gnu 173 | AC_MSG_RESULT([no 174 | :-( you may not be able to run $GP on the examples 175 | docs_f/docs/*.gnu without changes]) 176 | fi 177 | fi 178 | 179 | AC_OUTPUT(Makefile source_c/Makefile source_c/routines/Makefile) 180 | -------------------------------------------------------------------------------- /optimal_embedding/configure.scan: -------------------------------------------------------------------------------- 1 | # -*- Autoconf -*- 2 | # Process this file with autoconf to produce a configure script. 3 | 4 | AC_PREREQ(2.59) 5 | AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS) 6 | AC_CONFIG_SRCDIR([source_c/polypar.c]) 7 | AC_CONFIG_HEADER([config.h]) 8 | 9 | # Checks for programs. 10 | AC_PROG_CXX 11 | AC_PROG_CC 12 | AC_PROG_INSTALL 13 | AC_PROG_MAKE_SET 14 | AC_PROG_RANLIB 15 | 16 | # Checks for libraries. 17 | # FIXME: Replace `main' with a function in `-lm': 18 | AC_CHECK_LIB([m], [main]) 19 | 20 | # Checks for header files. 21 | AC_HEADER_STDC 22 | AC_CHECK_HEADERS([limits.h malloc.h stddef.h stdlib.h string.h]) 23 | 24 | # Checks for typedefs, structures, and compiler characteristics. 25 | AC_C_CONST 26 | AC_TYPE_SIZE_T 27 | 28 | # Checks for library functions. 29 | AC_FUNC_ERROR_AT_LINE 30 | AC_FUNC_MALLOC 31 | AC_FUNC_MEMCMP 32 | AC_FUNC_REALLOC 33 | AC_CHECK_FUNCS([pow sqrt strrchr strstr]) 34 | 35 | AC_CONFIG_FILES([Makefile 36 | source_c/Makefile 37 | source_c/routines/Makefile 38 | source_f/Makefile 39 | source_f/randomize/Makefile 40 | source_f/slatec/Makefile]) 41 | AC_OUTPUT 42 | -------------------------------------------------------------------------------- /optimal_embedding/examples/chua_1.gnu: -------------------------------------------------------------------------------- 1 | ! echo "" 2 | ! echo "****************************************************************" 3 | ! echo "* Cost Function for Legendre coordinate reconstruction *" 4 | ! echo "* of Chua's circuit time series *" 5 | ! echo "****************************************************************" 6 | ! echo "" 7 | ! costfunc chua.dat -W1000 -e3 -N8000 -ochua_lc 8 | # ! costfunc chua.dat -W1000 -e2 -N8000 -ochua_fdc 9 | pause 1 10 | 11 | set style data lines 12 | set style line 2 lt 1 lc rgb "red" lw 4 13 | set style line 10 lt 2 lw 10 lc rgb "grey" 14 | 15 | set logscale x 16 | set ylabel "Cost Function" 17 | set xlabel "t_w" offset 0.00,0.5 18 | set tics front 19 | 20 | set key left reverse 21 | #set key bottom 22 | 23 | plot [1:1000][-1.5:0] "chua_fdc.amp" u 1:2 t "fdc" ls 10, \ 24 | "chua_lc.amp" u 1:2 t "m = 2" ls 1, \ 25 | "chua_lc.amp" u 1:3 t "m = 3" ls 2, \ 26 | "chua_lc.amp" u 1:4 t "m = 4" ls 3, \ 27 | "chua_lc.amp" u 1:5 t "m = 5" ls 4, \ 28 | "chua_lc.amp" u 1:6 t "m = 6" ls 5, \ 29 | "chua_lc.amp" u 1:3 not ls 2 30 | pause -1 "Press when finished" 31 | 32 | -------------------------------------------------------------------------------- /optimal_embedding/examples/chua_2.gnu: -------------------------------------------------------------------------------- 1 | ! echo "" 2 | ! echo "*****************************************************************" 3 | ! echo "* Local Cost Function for Legendre coordinate reconstruction *" 4 | ! echo "* of Chua's circuit time series *" 5 | ! echo "*****************************************************************" 6 | ! echo "" 7 | pause 1 8 | 9 | set style data lines 10 | set palette defined ( 0 "black", 2 "blue", 4 "red", 6 "orange", 8 "yellow", 10 "white" ) 11 | set hidden3d nooffset 12 | # 13 | rgb(r,g,b) = int(r)*65536 + int(g)*256 + int(b) 14 | norma(x)=log(sqrt(x))/log(10) 15 | # 16 | unset tics 17 | set cbrange [-2.25:0] 18 | set xlabel "y0" 19 | set ylabel "y1" 20 | set zlabel "y2" 21 | 22 | unset key 23 | ! costfunc chua.dat -L -e3 -w81 -m3 -ochua.leg 24 | set label 10 "m=3" at screen 0.1,0.9 25 | splot 'chua.leg.loc' u 3:4:5:(norma($1)) lw .5 lc palette 26 | pause -1 "Press when finished" 27 | 28 | 29 | ! rm chua.leg.loc 30 | -------------------------------------------------------------------------------- /optimal_embedding/examples/chua_fdc.amp: -------------------------------------------------------------------------------- 1 | # tw L 2 | 1 -3.598218e-01 3 | 2 -4.290199e-01 4 | 3 -4.279303e-01 5 | 4 -4.483230e-01 6 | 5 -4.651492e-01 7 | 6 -4.788166e-01 8 | 7 -5.111275e-01 9 | 8 -5.365044e-01 10 | 9 -5.952283e-01 11 | 10 -6.214430e-01 12 | 11 -6.955374e-01 13 | 12 -7.715284e-01 14 | 13 -8.369201e-01 15 | 14 -8.871111e-01 16 | 15 -9.155998e-01 17 | 16 -9.806092e-01 18 | 17 -1.007265e+00 19 | 18 -1.040179e+00 20 | 19 -1.075045e+00 21 | 20 -1.076339e+00 22 | 21 -1.085520e+00 23 | 22 -1.112777e+00 24 | 23 -1.135174e+00 25 | 24 -1.155546e+00 26 | 25 -1.158400e+00 27 | 26 -1.193775e+00 28 | 27 -1.205467e+00 29 | 28 -1.220295e+00 30 | 29 -1.209094e+00 31 | 30 -1.213158e+00 32 | 31 -1.235329e+00 33 | 32 -1.240545e+00 34 | 33 -1.244663e+00 35 | 34 -1.236518e+00 36 | 35 -1.261109e+00 37 | 36 -1.250743e+00 38 | 37 -1.243787e+00 39 | 38 -1.231276e+00 40 | 39 -1.235586e+00 41 | 40 -1.225384e+00 42 | 42 -1.223474e+00 43 | 44 -1.212614e+00 44 | 46 -1.214086e+00 45 | 48 -1.230616e+00 46 | 50 -1.230864e+00 47 | 52 -1.235249e+00 48 | 54 -1.245175e+00 49 | 56 -1.230147e+00 50 | 58 -1.226418e+00 51 | 60 -1.271368e+00 52 | 63 -1.252563e+00 53 | 66 -1.258354e+00 54 | 69 -1.264827e+00 55 | 72 -1.259934e+00 56 | 75 -1.291049e+00 57 | 78 -1.304423e+00 58 | 81 -1.314229e+00 59 | 85 -1.313581e+00 60 | 89 -1.310459e+00 61 | 93 -1.308809e+00 62 | 97 -1.307823e+00 63 | 101 -1.304839e+00 64 | 106 -1.293166e+00 65 | 111 -1.300932e+00 66 | 116 -1.297281e+00 67 | 121 -1.292381e+00 68 | 127 -1.291090e+00 69 | 133 -1.285052e+00 70 | 139 -1.280268e+00 71 | 145 -1.275080e+00 72 | 152 -1.274442e+00 73 | 159 -1.261484e+00 74 | 166 -1.256140e+00 75 | 174 -1.252042e+00 76 | 182 -1.245120e+00 77 | 191 -1.232265e+00 78 | 200 -1.223058e+00 79 | 210 -1.198918e+00 80 | 220 -1.153467e+00 81 | 231 -1.066654e+00 82 | 242 -9.881083e-01 83 | 254 -9.227519e-01 84 | 266 -9.159563e-01 85 | 279 -8.813758e-01 86 | 292 -8.784480e-01 87 | 306 -8.722695e-01 88 | 321 -8.590198e-01 89 | 337 -8.484728e-01 90 | 353 -8.352400e-01 91 | 370 -8.202238e-01 92 | 388 -8.031186e-01 93 | 407 -7.694693e-01 94 | 427 -7.792949e-01 95 | 448 -7.604442e-01 96 | 470 -7.358430e-01 97 | 493 -7.095562e-01 98 | 517 -6.943402e-01 99 | 542 -6.709231e-01 100 | 569 -6.641243e-01 101 | 597 -6.370101e-01 102 | 626 -6.151087e-01 103 | 657 -5.849596e-01 104 | 689 -5.455973e-01 105 | 723 -5.305509e-01 106 | 759 -5.068405e-01 107 | 796 -4.710970e-01 108 | 835 -4.509730e-01 109 | 876 -4.226307e-01 110 | 919 -4.231807e-01 111 | 964 -4.104907e-01 112 | -------------------------------------------------------------------------------- /optimal_embedding/examples/mcgl_1.gnu: -------------------------------------------------------------------------------- 1 | ! echo "" 2 | ! echo "****************************************************************" 3 | ! echo "* Cost Function for delay coordinate reconstruction *" 4 | ! echo "* of Mackey-Glass time series *" 5 | ! echo "****************************************************************" 6 | ! echo "" 7 | ! costfunc mcgl17.dat -W1000 -omcgl17_dc 8 | ! costfunc mcgl17.dat -W1000 -e2 -omcgl17_fdc 9 | pause 1 10 | 11 | set style data lines 12 | set style line 3 lt 1 lc rgb "blue" lw 4 13 | set style line 10 lt 2 lw 10 lc rgb "grey" 14 | 15 | set logscale x 16 | set ylabel "Cost Function" 17 | set xlabel "t_w" offset 0.00,0.5 18 | set tics front 19 | 20 | set key left reverse 21 | #set key bottom 22 | 23 | plot [1:1000][-2:0] "mcgl17_fdc.amp" u 1:2 t "fdc" ls 10, \ 24 | "mcgl17_dc.amp" u 1:2 t "m = 2" ls 1, \ 25 | "mcgl17_dc.amp" u ($1*2):3 t "m = 3" ls 2, \ 26 | "mcgl17_dc.amp" u ($1*3):4 t "m = 4" ls 3, \ 27 | "mcgl17_dc.amp" u ($1*4):5 t "m = 5" ls 4, \ 28 | "mcgl17_dc.amp" u ($1*5):6 t "m = 6" ls 5, \ 29 | "mcgl17_dc.amp" u ($1*3):4 not ls 3 30 | pause -1 "Press when finished" 31 | 32 | -------------------------------------------------------------------------------- /optimal_embedding/examples/mcgl_2.gnu: -------------------------------------------------------------------------------- 1 | ! echo "" 2 | ! echo "**************************************************************" 3 | ! echo "* Local Cost Function for delay coordinate reconstruction *" 4 | ! echo "* of Mackey-Glass time series *" 5 | ! echo "**************************************************************" 6 | ! echo "" 7 | pause 1 8 | 9 | set style data lines 10 | set palette defined ( 0 "black", 2 "blue", 4 "red", 6 "orange", 8 "yellow", 10 "white" ) 11 | set hidden3d nooffset 12 | # 13 | rgb(r,g,b) = int(r)*65536 + int(g)*256 + int(b) 14 | norma(x)=log(sqrt(x))/log(10) 15 | # 16 | unset xtics 17 | unset ytics 18 | set cbrange [-2.25:0] 19 | 20 | set xlabel "x(t)" 21 | set ylabel "x(t+tw)" 22 | unset key 23 | ! costfunc mcgl17.dat -L -w30 -m2 -omcgl17.del 24 | set label 10 "m=2" at screen 0.1,0.9 25 | plot [-0.05:1.05][-0.05:1.05] 'mcgl17.del.loc' u 4:3:(norma($1)) lw .5 lc palette 26 | pause -1 "Press when finished" 27 | 28 | ! costfunc mcgl17.dat -L -w30 -m3 -omcgl17.del 29 | set label 10 "m=3" 30 | plot [-0.05:1.05][-0.05:1.05] 'mcgl17.del.loc' u 5:3:(norma($1)) lw .5 lc palette 31 | pause -1 "Press when finished" 32 | 33 | ! costfunc mcgl17.dat -L -w30 -m4 -omcgl17.del 34 | set label 10 "m=4" 35 | plot [-0.05:1.05][-0.05:1.05] 'mcgl17.del.loc' u 6:3:(norma($1)) lw .5 lc palette 36 | pause -1 "Press when finished" 37 | 38 | ! rm mcgl17.del.loc 39 | -------------------------------------------------------------------------------- /optimal_embedding/index.html: -------------------------------------------------------------------------------- 1 | 2 | Nonlinear Time Series Routines 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /optimal_embedding/install-sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | # 3 | # install - install a program, script, or datafile 4 | # This comes from X11R5. 5 | # 6 | # Calling this script install-sh is preferred over install.sh, to prevent 7 | # `make' implicit rules from creating a file called install from it 8 | # when there is no Makefile. 9 | # 10 | # This script is compatible with the BSD install script, but was written 11 | # from scratch. 12 | # 13 | 14 | 15 | # set DOITPROG to echo to test this script 16 | 17 | # Don't use :- since 4.3BSD and earlier shells don't like it. 18 | doit="${DOITPROG-}" 19 | 20 | 21 | # put in absolute paths if you don't have them in your path; or use env. vars. 22 | 23 | mvprog="${MVPROG-mv}" 24 | cpprog="${CPPROG-cp}" 25 | chmodprog="${CHMODPROG-chmod}" 26 | chownprog="${CHOWNPROG-chown}" 27 | chgrpprog="${CHGRPPROG-chgrp}" 28 | stripprog="${STRIPPROG-strip}" 29 | rmprog="${RMPROG-rm}" 30 | mkdirprog="${MKDIRPROG-mkdir}" 31 | 32 | tranformbasename="" 33 | transform_arg="" 34 | instcmd="$mvprog" 35 | chmodcmd="$chmodprog 0755" 36 | chowncmd="" 37 | chgrpcmd="" 38 | stripcmd="" 39 | rmcmd="$rmprog -f" 40 | mvcmd="$mvprog" 41 | src="" 42 | dst="" 43 | dir_arg="" 44 | 45 | while [ x"$1" != x ]; do 46 | case $1 in 47 | -c) instcmd="$cpprog" 48 | shift 49 | continue;; 50 | 51 | -d) dir_arg=true 52 | shift 53 | continue;; 54 | 55 | -m) chmodcmd="$chmodprog $2" 56 | shift 57 | shift 58 | continue;; 59 | 60 | -o) chowncmd="$chownprog $2" 61 | shift 62 | shift 63 | continue;; 64 | 65 | -g) chgrpcmd="$chgrpprog $2" 66 | shift 67 | shift 68 | continue;; 69 | 70 | -s) stripcmd="$stripprog" 71 | shift 72 | continue;; 73 | 74 | -t=*) transformarg=`echo $1 | sed 's/-t=//'` 75 | shift 76 | continue;; 77 | 78 | -b=*) transformbasename=`echo $1 | sed 's/-b=//'` 79 | shift 80 | continue;; 81 | 82 | *) if [ x"$src" = x ] 83 | then 84 | src=$1 85 | else 86 | # this colon is to work around a 386BSD /bin/sh bug 87 | : 88 | dst=$1 89 | fi 90 | shift 91 | continue;; 92 | esac 93 | done 94 | 95 | if [ x"$src" = x ] 96 | then 97 | echo "install: no input file specified" 98 | exit 1 99 | else 100 | true 101 | fi 102 | 103 | if [ x"$dir_arg" != x ]; then 104 | dst=$src 105 | src="" 106 | 107 | if [ -d $dst ]; then 108 | instcmd=: 109 | else 110 | instcmd=mkdir 111 | fi 112 | else 113 | 114 | # Waiting for this to be detected by the "$instcmd $src $dsttmp" command 115 | # might cause directories to be created, which would be especially bad 116 | # if $src (and thus $dsttmp) contains '*'. 117 | 118 | if [ -f $src -o -d $src ] 119 | then 120 | true 121 | else 122 | echo "install: $src does not exist" 123 | exit 1 124 | fi 125 | 126 | if [ x"$dst" = x ] 127 | then 128 | echo "install: no destination specified" 129 | exit 1 130 | else 131 | true 132 | fi 133 | 134 | # If destination is a directory, append the input filename; if your system 135 | # does not like double slashes in filenames, you may need to add some logic 136 | 137 | if [ -d $dst ] 138 | then 139 | dst="$dst"/`basename $src` 140 | else 141 | true 142 | fi 143 | fi 144 | 145 | ## this sed command emulates the dirname command 146 | dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` 147 | 148 | # Make sure that the destination directory exists. 149 | # this part is taken from Noah Friedman's mkinstalldirs script 150 | 151 | # Skip lots of stat calls in the usual case. 152 | if [ ! -d "$dstdir" ]; then 153 | defaultIFS=' 154 | ' 155 | IFS="${IFS-${defaultIFS}}" 156 | 157 | oIFS="${IFS}" 158 | # Some sh's can't handle IFS=/ for some reason. 159 | IFS='%' 160 | set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` 161 | IFS="${oIFS}" 162 | 163 | pathcomp='' 164 | 165 | while [ $# -ne 0 ] ; do 166 | pathcomp="${pathcomp}${1}" 167 | shift 168 | 169 | if [ ! -d "${pathcomp}" ] ; 170 | then 171 | $mkdirprog "${pathcomp}" 172 | else 173 | true 174 | fi 175 | 176 | pathcomp="${pathcomp}/" 177 | done 178 | fi 179 | 180 | if [ x"$dir_arg" != x ] 181 | then 182 | $doit $instcmd $dst && 183 | 184 | if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && 185 | if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && 186 | if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && 187 | if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi 188 | else 189 | 190 | # If we're going to rename the final executable, determine the name now. 191 | 192 | if [ x"$transformarg" = x ] 193 | then 194 | dstfile=`basename $dst` 195 | else 196 | dstfile=`basename $dst $transformbasename | 197 | sed $transformarg`$transformbasename 198 | fi 199 | 200 | # don't allow the sed command to completely eliminate the filename 201 | 202 | if [ x"$dstfile" = x ] 203 | then 204 | dstfile=`basename $dst` 205 | else 206 | true 207 | fi 208 | 209 | # Make a temp file name in the proper directory. 210 | 211 | dsttmp=$dstdir/#inst.$$# 212 | 213 | # Move or copy the file name to the temp name 214 | 215 | $doit $instcmd $src $dsttmp && 216 | 217 | trap "rm -f ${dsttmp}" 0 && 218 | 219 | # and set any options; do chmod last to preserve setuid bits 220 | 221 | # If any of these fail, we abort the whole thing. If we want to 222 | # ignore errors from any of these, just make sure not to ignore 223 | # errors from the above "$doit $instcmd $src $dsttmp" command. 224 | 225 | if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && 226 | if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && 227 | if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && 228 | if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && 229 | 230 | # Now rename the file to the real destination. 231 | 232 | $doit $rmcmd -f $dstdir/$dstfile && 233 | $doit $mvcmd $dsttmp $dstdir/$dstfile 234 | 235 | fi && 236 | 237 | 238 | exit 0 239 | -------------------------------------------------------------------------------- /optimal_embedding/logo: -------------------------------------------------------------------------------- 1 | _______________________________________________________________________________ 2 | 3 | _/_/_/_/_/ _/ _/_/_/ _/_/_/_/ _/_/ _/ _/ 4 | _/ _/ _/ _/ _/ _/ _/ _/ _/ 5 | _/ _/ _/ _/ _/ _/ _/_/ _/ 6 | _/ _/ _/_/_/ _/_/_/_/ _/_/_/_/ _/ _/ _/ 7 | _/ _/ _/ _/ _/ _/ _/ _/_/ 8 | _/ _/ _/ _/ _/ _/ _/ _/ _/ 9 | _/ _/ _/_/_/ _/_/_/_/ _/ _/ _/ _/ 10 | 11 | Nonlinear time series pproject 12 | Copyright (C) Rainer Hegger & Thomas Schreiber (1998-2007) 13 | _______________________________________________________________________________ 14 | 15 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/Makefile: -------------------------------------------------------------------------------- 1 | SHELL = /bin/sh 2 | 3 | prefix = /Users/ebaskerv 4 | exec_prefix = ${prefix} 5 | BINDIR = ${exec_prefix}/bin 6 | 7 | CC = cc 8 | CFLAGS = -O3 9 | AR = ar 10 | ARFLAGS = r 11 | INSTALL = /usr/bin/install -c 12 | 13 | LOADLIBS = routines/libddtsa.a -lm 14 | 15 | # list of executables we want to produce 16 | ALL = costfunc 17 | 18 | all: $(ALL) 19 | 20 | routines/libddtsa.a: 21 | (cd routines && $(MAKE)) 22 | 23 | $(ALL): routines/libddtsa.a *.c 24 | -$(CC) $(CFLAGS) $(COPTS) -o $@ $@.c $(LOADLIBS) 25 | 26 | install: all 27 | -for bin in $(ALL); do $(INSTALL) $$bin $(BINDIR); done 28 | 29 | clean: 30 | @rm -f *.o *~ #*# 31 | @rm -f $(ALL) 32 | -(cd routines && $(MAKE) clean) 33 | 34 | missing: 35 | -@for bin in $(ALL); do \ 36 | test -z "`$$bin -h 2>&1 | grep Usage`" \ 37 | && echo $$bin "(Uzal, L.C.)" >> ../missing.log; \ 38 | $$bin -h 2>&1 | cat >> ../install.log; \ 39 | done; : 40 | 41 | uninstall: 42 | -@for bin in $(ALL); do rm -f $(BINDIR)/$$bin; done 43 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/Makefile.in: -------------------------------------------------------------------------------- 1 | SHELL = /bin/sh 2 | 3 | prefix = @prefix@ 4 | exec_prefix = @exec_prefix@ 5 | BINDIR = @bindir@ 6 | 7 | CC = @CC@ 8 | CFLAGS = @CFLAGS@ 9 | AR = @AR@ 10 | ARFLAGS = @ARFLAGS@ 11 | INSTALL = @INSTALL@ 12 | 13 | LOADLIBS = routines/libddtsa.a -lm 14 | 15 | # list of executables we want to produce 16 | ALL = costfunc 17 | 18 | all: $(ALL) 19 | 20 | routines/libddtsa.a: 21 | (cd routines && $(MAKE)) 22 | 23 | $(ALL): routines/libddtsa.a *.c 24 | -$(CC) $(CFLAGS) $(COPTS) -o $@ $@.c $(LOADLIBS) 25 | 26 | install: all 27 | -for bin in $(ALL); do $(INSTALL) $$bin $(BINDIR); done 28 | 29 | clean: 30 | @rm -f *.o *~ #*# 31 | @rm -f $(ALL) 32 | -(cd routines && $(MAKE) clean) 33 | 34 | missing: 35 | -@for bin in $(ALL); do \ 36 | test -z "`$$bin -h 2>&1 | grep Usage`" \ 37 | && echo $$bin "(Uzal, L.C.)" >> ../missing.log; \ 38 | $$bin -h 2>&1 | cat >> ../install.log; \ 39 | done; : 40 | 41 | uninstall: 42 | -@for bin in $(ALL); do rm -f $(BINDIR)/$$bin; done 43 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/Makefile: -------------------------------------------------------------------------------- 1 | SHELL = /bin/sh 2 | 3 | AR = ar 4 | ARFLAGS = r 5 | CC = cc 6 | CFLAGS = -O3 7 | RANLIB = ranlib 8 | 9 | ALL = get_series.o rescale_data.o make_box.o\ 10 | find_neighbors.o scan_help.o variance.o get_multi_series.o\ 11 | search_datafile.o check_option.o solvele.o rand.o eigen.o\ 12 | test_outfile.o invert_matrix.o exclude_interval.o make_multi_box.o\ 13 | find_multi_neighbors.o check_alloc.o myfgets.o what_i_do.o\ 14 | make_multi_index.o make_multi_box2.o rand_arb_dist.o 15 | 16 | libddtsa.a: $(ALL) 17 | $(AR) $(ARFLAGS) libddtsa.a $? 18 | $(RANLIB) libddtsa.a 19 | 20 | clean: 21 | @rm -f *.a *.o *~ #*# 22 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/Makefile.in: -------------------------------------------------------------------------------- 1 | SHELL = /bin/sh 2 | 3 | AR = @AR@ 4 | ARFLAGS = @ARFLAGS@ 5 | CC = @CC@ 6 | CFLAGS = @CFLAGS@ 7 | RANLIB = @RANLIB@ 8 | 9 | ALL = get_series.o rescale_data.o make_box.o\ 10 | find_neighbors.o scan_help.o variance.o get_multi_series.o\ 11 | search_datafile.o check_option.o solvele.o rand.o eigen.o\ 12 | test_outfile.o invert_matrix.o exclude_interval.o make_multi_box.o\ 13 | find_multi_neighbors.o check_alloc.o myfgets.o what_i_do.o\ 14 | make_multi_index.o make_multi_box2.o rand_arb_dist.o 15 | 16 | libddtsa.a: $(ALL) 17 | $(AR) $(ARFLAGS) libddtsa.a $? 18 | $(RANLIB) libddtsa.a 19 | 20 | clean: 21 | @rm -f *.a *.o *~ #*# 22 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/arima.tgz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobeylab/pyembedding/8113d0550e42db586974f33d92a43b6b53a04fb9/optimal_embedding/source_c/routines/arima.tgz -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/check_alloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /* Author: Rainer Hegger Last modified: Jul 15, 1999 */ 21 | #include 22 | #include 23 | #include "tisean_cec.h" 24 | 25 | void check_alloc(void *pnt) 26 | { 27 | if (pnt == NULL) { 28 | fprintf(stderr,"check_alloc: Couldn't allocate enough memory. Exiting\n"); 29 | exit(CHECK_ALLOC_NOT_ENOUGH_MEMORY); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/check_option.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Aug 19, 1999 */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include "tisean_cec.h" 26 | 27 | extern void check_alloc(void*); 28 | /* possible types are 29 | 'd' (long) integer 30 | 'u' unsigned (long) 31 | '1' one or two unsigned (long) numbers, separated by comma, if two 32 | '2' two unsigned (long) numbers separated by a comma 33 | '3' three unsigned (long) numbers separated by commas 34 | 'f' float 35 | 's' string 36 | 'o' optional string (must only begin with a minus if there is no space) 37 | 'n' no parameter 38 | */ 39 | 40 | void check_unsigned(char *tocheck,int which) 41 | { 42 | int i,n; 43 | char ok=1; 44 | 45 | n=strlen(tocheck); 46 | for (i=0;i= (len-1)) { 102 | fprintf(stderr,"Wrong type of parameter for flag -%c. Has to be" 103 | " unsigned,unsigned\n",which); 104 | exit(CHECK_OPTION_NOT_TWO); 105 | } 106 | for (j=0;j= (len-1)) { 131 | fprintf(stderr,"Wrong type of parameter for flag -%c. Has to be" 132 | " unsigned,unsigned,unsigned\n",which); 133 | exit(CHECK_OPTION_NOT_THREE); 134 | } 135 | 136 | for (j=i+1;j= (len-1)) { 141 | fprintf(stderr,"Wrong type of parameter for flag -%c. Has to be" 142 | " unsigned,unsigned,unsigned\n",which); 143 | exit(CHECK_OPTION_NOT_THREE); 144 | } 145 | 146 | for (k=0;k 2) { 188 | switch(type) { 189 | case 'u': check_unsigned(in[i]+2,which);break; 190 | case 'd': check_integer(in[i]+2,which);break; 191 | case 'f': check_float(in[i]+2,which);break; 192 | case '2': check_two(in[i]+2,which);break; 193 | case '3': check_three(in[i]+2,which);break; 194 | } 195 | if (ret != NULL) 196 | free(ret); 197 | check_alloc(ret=(char*)calloc(strlen(in[i]+2)+1,(size_t)1)); 198 | strcpy(ret,in[i]+2); 199 | in[i]=NULL; 200 | } 201 | else { 202 | in[i]=NULL; 203 | i++; 204 | if (i < n) { 205 | if (in[i] != NULL) { 206 | switch(type) { 207 | case 'u': check_unsigned(in[i],which);break; 208 | case 'd': check_integer(in[i],which);break; 209 | case 'f': check_float(in[i],which);break; 210 | case '2': check_two(in[i],which);break; 211 | case '3': check_three(in[i]+2,which);break; 212 | case 'o': ok=check_optional(in[i],which);break; 213 | } 214 | if (ok) { 215 | if (ret != NULL) 216 | free(ret); 217 | check_alloc(ret=(char*)calloc(strlen(in[i])+1,(size_t)1)); 218 | strcpy(ret,in[i]); 219 | in[i]=NULL; 220 | } 221 | else { 222 | i--; 223 | if (ret != NULL) 224 | free(ret); 225 | ret=NULL; 226 | } 227 | } 228 | } 229 | else { 230 | if (ret != NULL) { 231 | free(ret); 232 | ret=NULL; 233 | } 234 | } 235 | } 236 | } 237 | else { 238 | in[i]=NULL; 239 | } 240 | } 241 | } 242 | } 243 | 244 | if (((type == 'o') || (type == 'n')) && (ret == NULL) && wasfound) 245 | return ""; 246 | 247 | if (wasfound && (ret == NULL)) { 248 | fprintf(stderr,"The option -%c needs some value. Exiting!\n",which); 249 | exit(CHECK_OPTION_C_NO_VALUE); 250 | } 251 | return ret; 252 | } 253 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/diffc.log: -------------------------------------------------------------------------------- 1 | --- get_multi_series.c 2004-07-23 10:01:25.000000000 +0200 2 | +++ /home/hegger/TISEAN_2.1/source_c/routines/get_multi_series.c 2000-05-26 08:24:44.000000000 +0200 3 | @@ -135,7 +135,7 @@ 4 | fprintf(stderr,"Line %lu ignored: %s",allcount,input); 5 | break; 6 | } 7 | - if ((count == 0) && (i == *col) && (verbosity&VER_FIRST_LINE)) { 8 | + if ((verbosity&VER_FIRST_LINE) && (count == 0)) { 9 | fprintf(stderr,"get_multi_series: first data item(s) used:\n"); 10 | for (i=0;i< *col;i++) 11 | fprintf(stderr,"%lf ",x[i][0]); 12 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/diffh.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cobeylab/pyembedding/8113d0550e42db586974f33d92a43b6b53a04fb9/optimal_embedding/source_c/routines/diffh.log -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/eigen.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "tisean_cec.h" 5 | 6 | typedef double doublereal; 7 | typedef int integer; 8 | 9 | #define abs(x) (((x)>=0.0)?(x):-(x)) 10 | #define min(x,y) (((x)<=(y))?(x):(y)) 11 | #define max(x,y) (((x)>=(y))?(x):(y)) 12 | 13 | static doublereal c_b10 = 1.; 14 | 15 | extern void check_alloc(void*); 16 | 17 | double d_sign(double *a,double *b) 18 | { 19 | double x; 20 | x = (*a >= 0 ? *a : - *a); 21 | return ( *b >= 0 ? x : -x); 22 | } 23 | 24 | doublereal pythag(doublereal *a, doublereal *b) 25 | { 26 | doublereal ret_val, d__1, d__2, d__3; 27 | static doublereal p, r__, s, t, u; 28 | 29 | d__1 = abs(*a), d__2 = abs(*b); 30 | p = max(d__1,d__2); 31 | if (p == 0.) { 32 | goto L20; 33 | } 34 | d__2 = abs(*a), d__3 = abs(*b); 35 | d__1 = min(d__2,d__3) / p; 36 | r__ = d__1 * d__1; 37 | L10: 38 | t = r__ + 4.; 39 | if (t == 4.) { 40 | goto L20; 41 | } 42 | s = r__ / t; 43 | u = s * 2. + 1.; 44 | p = u * p; 45 | d__1 = s / u; 46 | r__ = d__1 * d__1 * r__; 47 | goto L10; 48 | L20: 49 | ret_val = p; 50 | return ret_val; 51 | } 52 | 53 | 54 | int tred2(integer *nm, integer *n, doublereal *a, 55 | doublereal *d__, doublereal *e, doublereal *z__) 56 | { 57 | integer a_dim1, a_offset, z_dim1, z_offset, i__1, i__2, i__3; 58 | doublereal d__1; 59 | 60 | double sqrt(doublereal), d_sign(doublereal *, doublereal *); 61 | 62 | static doublereal f, g, h__; 63 | static integer i__, j, k, l; 64 | static doublereal hh; 65 | static integer ii, jp1; 66 | static doublereal scale; 67 | 68 | 69 | 70 | /* this subroutine is a translation of the algol procedure tred2, */ 71 | /* num. math. 11, 181-195(1968) by martin, reinsch, and wilkinson. */ 72 | /* handbook for auto. comp., vol.ii-linear algebra, 212-226(1971). */ 73 | 74 | /* this subroutine reduces a real symmetric matrix to a */ 75 | /* symmetric tridiagonal matrix using and accumulating */ 76 | /* orthogonal similarity transformations. */ 77 | 78 | /* on input */ 79 | 80 | /* nm must be set to the row dimension of two-dimensional */ 81 | /* array parameters as declared in the calling program */ 82 | /* dimension statement. */ 83 | 84 | /* n is the order of the matrix. */ 85 | 86 | /* a contains the real symmetric input matrix. only the */ 87 | /* lower triangle of the matrix need be supplied. */ 88 | 89 | /* on output */ 90 | 91 | /* d contains the diagonal elements of the tridiagonal matrix. */ 92 | 93 | /* e contains the subdiagonal elements of the tridiagonal */ 94 | /* matrix in its last n-1 positions. e(1) is set to zero. */ 95 | 96 | /* z contains the orthogonal transformation matrix */ 97 | /* produced in the reduction. */ 98 | 99 | /* a and z may coincide. if distinct, a is unaltered. */ 100 | 101 | /* questions and comments should be directed to burton s. garbow, */ 102 | /* mathematics and computer science div, argonne national laboratory */ 103 | 104 | /* this version dated august 1983. */ 105 | 106 | /* ------------------------------------------------------------------ */ 107 | 108 | z_dim1 = *nm; 109 | z_offset = 1 + z_dim1 * 1; 110 | z__ -= z_offset; 111 | --e; 112 | --d__; 113 | a_dim1 = *nm; 114 | a_offset = 1 + a_dim1 * 1; 115 | a -= a_offset; 116 | 117 | i__1 = *n; 118 | for (i__ = 1; i__ <= i__1; ++i__) { 119 | 120 | i__2 = *n; 121 | for (j = i__; j <= i__2; ++j) { 122 | z__[j + i__ * z_dim1] = a[j + i__ * a_dim1]; 123 | } 124 | 125 | d__[i__] = a[*n + i__ * a_dim1]; 126 | } 127 | 128 | if (*n == 1) { 129 | goto L510; 130 | } 131 | i__1 = *n; 132 | for (ii = 2; ii <= i__1; ++ii) { 133 | i__ = *n + 2 - ii; 134 | l = i__ - 1; 135 | h__ = 0.; 136 | scale = 0.; 137 | if (l < 2) { 138 | goto L130; 139 | } 140 | i__2 = l; 141 | for (k = 1; k <= i__2; ++k) { 142 | scale += (d__1 = d__[k], abs(d__1)); 143 | } 144 | 145 | if (scale != 0.) { 146 | goto L140; 147 | } 148 | L130: 149 | e[i__] = d__[l]; 150 | 151 | i__2 = l; 152 | for (j = 1; j <= i__2; ++j) { 153 | d__[j] = z__[l + j * z_dim1]; 154 | z__[i__ + j * z_dim1] = 0.; 155 | z__[j + i__ * z_dim1] = 0.; 156 | } 157 | 158 | goto L290; 159 | 160 | L140: 161 | i__2 = l; 162 | for (k = 1; k <= i__2; ++k) { 163 | d__[k] /= scale; 164 | h__ += d__[k] * d__[k]; 165 | } 166 | 167 | f = d__[l]; 168 | d__1 = sqrt(h__); 169 | g = -d_sign(&d__1, &f); 170 | e[i__] = scale * g; 171 | h__ -= f * g; 172 | d__[l] = f - g; 173 | i__2 = l; 174 | for (j = 1; j <= i__2; ++j) { 175 | e[j] = 0.; 176 | } 177 | 178 | i__2 = l; 179 | for (j = 1; j <= i__2; ++j) { 180 | f = d__[j]; 181 | z__[j + i__ * z_dim1] = f; 182 | g = e[j] + z__[j + j * z_dim1] * f; 183 | jp1 = j + 1; 184 | if (l < jp1) { 185 | goto L220; 186 | } 187 | 188 | i__3 = l; 189 | for (k = jp1; k <= i__3; ++k) { 190 | g += z__[k + j * z_dim1] * d__[k]; 191 | e[k] += z__[k + j * z_dim1] * f; 192 | } 193 | 194 | L220: 195 | e[j] = g; 196 | } 197 | f = 0.; 198 | 199 | i__2 = l; 200 | for (j = 1; j <= i__2; ++j) { 201 | e[j] /= h__; 202 | f += e[j] * d__[j]; 203 | } 204 | 205 | hh = f / (h__ + h__); 206 | i__2 = l; 207 | for (j = 1; j <= i__2; ++j) { 208 | e[j] -= hh * d__[j]; 209 | } 210 | i__2 = l; 211 | for (j = 1; j <= i__2; ++j) { 212 | f = d__[j]; 213 | g = e[j]; 214 | 215 | i__3 = l; 216 | for (k = j; k <= i__3; ++k) { 217 | z__[k + j * z_dim1] = z__[k + j * z_dim1] - f * e[k] - g * 218 | d__[k]; 219 | } 220 | 221 | d__[j] = z__[l + j * z_dim1]; 222 | z__[i__ + j * z_dim1] = 0.; 223 | } 224 | 225 | L290: 226 | d__[i__] = h__; 227 | } 228 | i__1 = *n; 229 | for (i__ = 2; i__ <= i__1; ++i__) { 230 | l = i__ - 1; 231 | z__[*n + l * z_dim1] = z__[l + l * z_dim1]; 232 | z__[l + l * z_dim1] = 1.; 233 | h__ = d__[i__]; 234 | if (h__ == 0.) { 235 | goto L380; 236 | } 237 | 238 | i__2 = l; 239 | for (k = 1; k <= i__2; ++k) { 240 | d__[k] = z__[k + i__ * z_dim1] / h__; 241 | } 242 | 243 | i__2 = l; 244 | for (j = 1; j <= i__2; ++j) { 245 | g = 0.; 246 | 247 | i__3 = l; 248 | for (k = 1; k <= i__3; ++k) { 249 | g += z__[k + i__ * z_dim1] * z__[k + j * z_dim1]; 250 | } 251 | 252 | i__3 = l; 253 | for (k = 1; k <= i__3; ++k) { 254 | z__[k + j * z_dim1] -= g * d__[k]; 255 | } 256 | } 257 | 258 | L380: 259 | i__3 = l; 260 | for (k = 1; k <= i__3; ++k) { 261 | z__[k + i__ * z_dim1] = 0.; 262 | } 263 | 264 | } 265 | 266 | L510: 267 | i__1 = *n; 268 | for (i__ = 1; i__ <= i__1; ++i__) { 269 | d__[i__] = z__[*n + i__ * z_dim1]; 270 | z__[*n + i__ * z_dim1] = 0.; 271 | } 272 | 273 | z__[*n + *n * z_dim1] = 1.; 274 | e[1] = 0.; 275 | return 0; 276 | } 277 | 278 | int tql2(integer *nm, integer *n, doublereal *d__, 279 | doublereal *e, doublereal *z__, integer *ierr) 280 | { 281 | integer z_dim1, z_offset, i__1, i__2, i__3; 282 | doublereal d__1, d__2; 283 | 284 | double d_sign(doublereal *, doublereal *); 285 | 286 | static doublereal c__, f, g, h__; 287 | static integer i__, j, k, l, m; 288 | static doublereal p, r__, s, c2, c3; 289 | static integer l1, l2; 290 | static doublereal s2; 291 | static integer ii; 292 | static doublereal dl1, el1; 293 | static integer mml; 294 | static doublereal tst1, tst2; 295 | extern doublereal pythag_(doublereal *, doublereal *); 296 | 297 | 298 | 299 | /* this subroutine is a translation of the algol procedure tql2, */ 300 | /* num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and */ 301 | /* wilkinson. */ 302 | /* handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). */ 303 | 304 | /* this subroutine finds the eigenvalues and eigenvectors */ 305 | /* of a symmetric tridiagonal matrix by the ql method. */ 306 | /* the eigenvectors of a full symmetric matrix can also */ 307 | /* be found if tred2 has been used to reduce this */ 308 | /* full matrix to tridiagonal form. */ 309 | 310 | /* on input */ 311 | 312 | /* nm must be set to the row dimension of two-dimensional */ 313 | /* array parameters as declared in the calling program */ 314 | /* dimension statement. */ 315 | 316 | /* n is the order of the matrix. */ 317 | 318 | /* d contains the diagonal elements of the input matrix. */ 319 | 320 | /* e contains the subdiagonal elements of the input matrix */ 321 | /* in its last n-1 positions. e(1) is arbitrary. */ 322 | 323 | /* z contains the transformation matrix produced in the */ 324 | /* reduction by tred2, if performed. if the eigenvectors */ 325 | /* of the tridiagonal matrix are desired, z must contain */ 326 | /* the identity matrix. */ 327 | 328 | /* on output */ 329 | 330 | /* d contains the eigenvalues in ascending order. if an */ 331 | /* error exit is made, the eigenvalues are correct but */ 332 | /* unordered for indices 1,2,...,ierr-1. */ 333 | 334 | /* e has been destroyed. */ 335 | 336 | /* z contains orthonormal eigenvectors of the symmetric */ 337 | /* tridiagonal (or full) matrix. if an error exit is made, */ 338 | /* z contains the eigenvectors associated with the stored */ 339 | /* eigenvalues. */ 340 | 341 | /* ierr is set to */ 342 | /* zero for normal return, */ 343 | /* j if the j-th eigenvalue has not been */ 344 | /* determined after 30 iterations. */ 345 | 346 | /* calls pythag for dsqrt(a*a + b*b) . */ 347 | 348 | /* questions and comments should be directed to burton s. garbow, */ 349 | /* mathematics and computer science div, argonne national laboratory */ 350 | 351 | /* this version dated august 1983. */ 352 | 353 | /* ------------------------------------------------------------------ */ 354 | 355 | z_dim1 = *nm; 356 | z_offset = 1 + z_dim1 * 1; 357 | z__ -= z_offset; 358 | --e; 359 | --d__; 360 | 361 | *ierr = 0; 362 | if (*n == 1) { 363 | goto L1001; 364 | } 365 | 366 | i__1 = *n; 367 | for (i__ = 2; i__ <= i__1; ++i__) { 368 | e[i__ - 1] = e[i__]; 369 | } 370 | 371 | f = 0.; 372 | tst1 = 0.; 373 | e[*n] = 0.; 374 | 375 | i__1 = *n; 376 | for (l = 1; l <= i__1; ++l) { 377 | j = 0; 378 | h__ = (d__1 = d__[l], abs(d__1)) + (d__2 = e[l], abs(d__2)); 379 | if (tst1 < h__) { 380 | tst1 = h__; 381 | } 382 | i__2 = *n; 383 | for (m = l; m <= i__2; ++m) { 384 | tst2 = tst1 + (d__1 = e[m], abs(d__1)); 385 | if (tst2 == tst1) { 386 | goto L120; 387 | } 388 | } 389 | 390 | L120: 391 | if (m == l) { 392 | goto L220; 393 | } 394 | L130: 395 | if (j == 30) { 396 | goto L1000; 397 | } 398 | ++j; 399 | l1 = l + 1; 400 | l2 = l1 + 1; 401 | g = d__[l]; 402 | p = (d__[l1] - g) / (e[l] * 2.); 403 | r__ = pythag(&p, &c_b10); 404 | d__[l] = e[l] / (p + d_sign(&r__, &p)); 405 | d__[l1] = e[l] * (p + d_sign(&r__, &p)); 406 | dl1 = d__[l1]; 407 | h__ = g - d__[l]; 408 | if (l2 > *n) { 409 | goto L145; 410 | } 411 | 412 | i__2 = *n; 413 | for (i__ = l2; i__ <= i__2; ++i__) { 414 | d__[i__] -= h__; 415 | } 416 | 417 | L145: 418 | f += h__; 419 | p = d__[m]; 420 | c__ = 1.; 421 | c2 = c__; 422 | el1 = e[l1]; 423 | s = 0.; 424 | mml = m - l; 425 | i__2 = mml; 426 | for (ii = 1; ii <= i__2; ++ii) { 427 | c3 = c2; 428 | c2 = c__; 429 | s2 = s; 430 | i__ = m - ii; 431 | g = c__ * e[i__]; 432 | h__ = c__ * p; 433 | r__ = pythag(&p, &e[i__]); 434 | e[i__ + 1] = s * r__; 435 | s = e[i__] / r__; 436 | c__ = p / r__; 437 | p = c__ * d__[i__] - s * g; 438 | d__[i__ + 1] = h__ + s * (c__ * g + s * d__[i__]); 439 | i__3 = *n; 440 | for (k = 1; k <= i__3; ++k) { 441 | h__ = z__[k + (i__ + 1) * z_dim1]; 442 | z__[k + (i__ + 1) * z_dim1] = s * z__[k + i__ * z_dim1] + c__ 443 | * h__; 444 | z__[k + i__ * z_dim1] = c__ * z__[k + i__ * z_dim1] - s * h__; 445 | } 446 | 447 | } 448 | 449 | p = -s * s2 * c3 * el1 * e[l] / dl1; 450 | e[l] = s * p; 451 | d__[l] = c__ * p; 452 | tst2 = tst1 + (d__1 = e[l], abs(d__1)); 453 | if (tst2 > tst1) { 454 | goto L130; 455 | } 456 | L220: 457 | d__[l] += f; 458 | } 459 | i__1 = *n; 460 | for (ii = 2; ii <= i__1; ++ii) { 461 | i__ = ii - 1; 462 | k = i__; 463 | p = d__[i__]; 464 | 465 | i__2 = *n; 466 | for (j = ii; j <= i__2; ++j) { 467 | if (d__[j] >= p) { 468 | goto L260; 469 | } 470 | k = j; 471 | p = d__[j]; 472 | L260: 473 | ; 474 | } 475 | 476 | if (k == i__) { 477 | goto L300; 478 | } 479 | d__[k] = d__[i__]; 480 | d__[i__] = p; 481 | 482 | i__2 = *n; 483 | for (j = 1; j <= i__2; ++j) { 484 | p = z__[j + i__ * z_dim1]; 485 | z__[j + i__ * z_dim1] = z__[j + k * z_dim1]; 486 | z__[j + k * z_dim1] = p; 487 | } 488 | 489 | L300: 490 | ; 491 | } 492 | 493 | goto L1001; 494 | L1000: 495 | *ierr = l; 496 | L1001: 497 | return 0; 498 | } 499 | 500 | void eigen(double **mat,unsigned long n,double *eig) 501 | { 502 | double *trans,*off; 503 | int ierr,i,j,nm=(int)n; 504 | 505 | check_alloc(trans=(double*)malloc(sizeof(double)*nm*nm)); 506 | check_alloc(off=(double*)malloc(sizeof(double)*nm)); 507 | 508 | tred2(&nm,&nm,&mat[0][0],eig,off,trans); 509 | tql2(&nm,&nm,eig,off,trans,&ierr); 510 | 511 | if (ierr != 0) { 512 | fprintf(stderr,"Non converging eigenvalues! Exiting\n"); 513 | exit(EIG2_TOO_MANY_ITERATIONS); 514 | } 515 | 516 | for (i=0;i 22 | #include 23 | #ifndef _MATH_H 24 | #include 25 | #endif 26 | 27 | unsigned long exclude_interval(unsigned long n,long ex0,long ex1, 28 | unsigned long *hf,unsigned long *found) 29 | { 30 | long i,help; 31 | long lf=0; 32 | 33 | for (i=0;i ex1)) 36 | found[lf++]=help; 37 | } 38 | return lf; 39 | } 40 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/find_multi_neighbors.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Jul 9, 1999 */ 21 | #include 22 | 23 | unsigned long find_multi_neighbors(double **s,long **box,long *list,double **x, 24 | unsigned long l,unsigned int bs,unsigned int dim, 25 | unsigned int emb,unsigned int del,double eps, 26 | unsigned long *flist) 27 | { 28 | unsigned long nf=0; 29 | int i,i1,i2,j,j1,k,k1,li; 30 | int ib=bs-1; 31 | long element; 32 | double dx=0.0; 33 | 34 | i=(int)(x[0][0]/eps)&ib; 35 | j=(int)(x[dim-1][0]/eps)&ib; 36 | 37 | for (i1=i-1;i1<=i+1;i1++) { 38 | i2=i1&ib; 39 | for (j1=j-1;j1<=j+1;j1++) { 40 | element=box[i2][j1&ib]; 41 | while (element != -1) { 42 | for (k=0;k eps) 47 | break; 48 | } 49 | if (dx > eps) 50 | break; 51 | } 52 | if (dx <= eps) 53 | flist[nf++]=element; 54 | element=list[element]; 55 | } 56 | } 57 | } 58 | return nf; 59 | } 60 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/find_neighbors.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: March 1st, 1998 */ 21 | #include 22 | 23 | unsigned long find_neighbors(double *s,long **box,long *list,double *x, 24 | unsigned long l,unsigned int bs,unsigned int dim, 25 | unsigned int del,double eps,unsigned long *flist) 26 | { 27 | unsigned long nf=0; 28 | int i,i1,i2,j,j1,k,k1; 29 | int ib=bs-1; 30 | long element; 31 | double dx; 32 | 33 | k=(int)((dim-1)*del); 34 | i=(int)(x[-k]/eps)&ib; 35 | j=(int)(x[0]/eps)&ib; 36 | 37 | for (i1=i-1;i1<=i+1;i1++) { 38 | i2=i1&ib; 39 | for (j1=j-1;j1<=j+1;j1++) { 40 | element=box[i2][j1&ib]; 41 | while (element != -1) { 42 | for (k=0;k eps) 46 | break; 47 | } 48 | if (k == dim) 49 | flist[nf++]=element; 50 | element=list[element]; 51 | } 52 | } 53 | } 54 | return nf; 55 | } 56 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/get_multi_series.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Sep 3, 1999 */ 21 | /*Note: Keep in mind that the first index runs the dimension, 22 | the second the time series index */ 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "tsa.h" 28 | #include "tisean_cec.h" 29 | 30 | #define SIZE_STEP 1000 31 | extern void check_alloc(void*); 32 | 33 | double **get_multi_series(char *name,unsigned long *l,unsigned long ex, 34 | unsigned int *col,char *which,char colfix, 35 | unsigned int verbosity) 36 | { 37 | char *input,**format; 38 | int i,j; 39 | unsigned int *hcol,maxcol=0,colcount=0; 40 | unsigned long count,max_size=SIZE_STEP,hl,allcount; 41 | int input_size=INPUT_SIZE; 42 | double **x; 43 | FILE *fin; 44 | 45 | if (strlen(which) > 0) { 46 | colcount=1; 47 | for (i=0;i maxcol) 75 | maxcol=hcol[i]; 76 | while ((int)(*which) && !isspace((unsigned int)(*which))) 77 | which++; 78 | while ((int)(*which) && isspace((unsigned int)(*which))) 79 | which++; 80 | if (!((int)(*which))) 81 | break; 82 | } 83 | else 84 | i= -1; 85 | 86 | if (*which) 87 | sscanf(which,"%u",&hcol[i]); 88 | else 89 | for (j=i+1;j< *col;j++) 90 | hcol[j]= ++maxcol; 91 | 92 | if (verbosity&VER_INPUT) { 93 | fprintf(stderr,"Using columns: "); 94 | for (i=0;i< *col;i++) 95 | fprintf(stderr,"%d ",hcol[i]); 96 | fprintf(stderr,"\n"); 97 | } 98 | 99 | check_alloc(format=(char**)malloc(sizeof(char*)* *col)); 100 | for (i=0;i< *col;i++) { 101 | check_alloc(format[i]=(char*)calloc((size_t)(4*hcol[i]),(size_t)1)); 102 | strcpy(format[i],""); 103 | for (j=1;j count) 185 | for (i=0;i< *col;i++) 186 | check_alloc(x[i]=(double*)realloc(x[i],sizeof(double)*count)); 187 | 188 | return x; 189 | } 190 | #undef SIZE_STEP 191 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/get_series.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Sep 3, 1999 */ 21 | #include 22 | #include 23 | #include 24 | #include "tsa.h" 25 | #include "tisean_cec.h" 26 | 27 | #define SIZE_STEP 1000 28 | extern void check_alloc(void*); 29 | 30 | double *get_series(char *name,unsigned long *l,unsigned long ex, 31 | unsigned int col,unsigned int verbosity) 32 | { 33 | char *input,*format; 34 | int i; 35 | unsigned long count,allcount,max_size=SIZE_STEP,hl; 36 | int input_size=INPUT_SIZE; 37 | double *x; 38 | FILE *fin; 39 | 40 | check_alloc(input=(char*)calloc((size_t)input_size,(size_t)1)); 41 | check_alloc(format=(char*)calloc((size_t)(4*col),(size_t)1)); 42 | strcpy(format,""); 43 | for (i=1;i count) 106 | check_alloc(x=(double*)realloc(x,sizeof(double)*count)); 107 | 108 | return x; 109 | } 110 | #undef SIZE_STEP 111 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/invert_matrix.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /* Author: Rainer Hegger Last modified: Sep 5, 2004*/ 21 | /* Changes: 22 | * Sep 5, 2004: added the extern check_alloc line 23 | */ 24 | #include 25 | #include 26 | #include 27 | 28 | extern void check_alloc(void*); 29 | 30 | double **invert_matrix(double **mat,unsigned int size) 31 | { 32 | int i,j,k; 33 | double **hmat,**imat,*vec; 34 | extern void solvele(double**,double*,unsigned int); 35 | 36 | check_alloc(hmat=(double**)malloc(sizeof(double*)*size)); 37 | for (i=0;i 30 | 31 | extern void check_alloc(void *); 32 | 33 | unsigned int **make_multi_index(unsigned int comps,unsigned int emb, 34 | unsigned int del) 35 | { 36 | unsigned long i,alldim; 37 | unsigned int **mmi; 38 | 39 | alldim=comps*emb; 40 | check_alloc(mmi=(unsigned int**)malloc(sizeof(unsigned int*)*2)); 41 | for (i=0;i<2;i++) 42 | check_alloc(mmi[i]=(unsigned int*)malloc(sizeof(unsigned int)*alldim)); 43 | 44 | for (i=0;i 22 | #include 23 | #include 24 | #include "tsa.h" 25 | 26 | char* myfgets(char *str,int *size,FILE *fin,unsigned int verbosity) 27 | { 28 | char *ret; 29 | char *hstr=NULL; 30 | char last; 31 | 32 | ret=fgets(str,*size,fin); 33 | if (ret == NULL) 34 | return NULL; 35 | 36 | last=str[strlen(str)-1]; 37 | 38 | while (last != '\n') { 39 | *size += INPUT_SIZE; 40 | check_alloc(hstr=(char*)calloc((size_t)INPUT_SIZE,(size_t)1)); 41 | check_alloc(str=realloc(str,(size_t)*size)); 42 | ret=fgets(hstr,INPUT_SIZE,fin); 43 | strcat(str,hstr); 44 | if (verbosity&VER_INPUT) 45 | fprintf(stderr,"Line in file too long. Increasing input size\n"); 46 | last=str[strlen(str)-1]; 47 | free(hstr); 48 | } 49 | 50 | if (ret == NULL) 51 | return NULL; 52 | else 53 | return str; 54 | } 55 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/rand.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger. Last modified: Feb 12, 2006 */ 21 | /* Changes: 22 | Sep 5, 2004 : add extern definition of check_alloc 23 | Feb 12, 2006: add was_set to avoid multiple initialisations 24 | */ 25 | 26 | #define __RANDOM 27 | 28 | #ifndef _STDLIB_H 29 | #include 30 | #endif 31 | 32 | #ifndef _LIMITS_H 33 | #include 34 | #endif 35 | 36 | #ifndef _MATH_H 37 | #include 38 | #endif 39 | 40 | 41 | #ifndef M_PI 42 | #define M_PI 3.1415926535897932385E0 43 | #endif 44 | 45 | extern void check_alloc(void*); 46 | 47 | static unsigned long *rnd_array,rnd69,*rnd1279,factor; 48 | static unsigned long *nexti,rndtime,rndtime1,rndtime2,rndtime3,*next1279; 49 | static unsigned long t1279,t1279_1,t1279_2,t1279_3; 50 | static double lo_limit; 51 | static char rnd_init_was_set=0; 52 | 53 | void rnd_init(unsigned long iseed) 54 | { 55 | int i; 56 | unsigned long z,index; 57 | 58 | if (rnd_init_was_set == 1) 59 | return ; 60 | 61 | rnd_init_was_set=1; 62 | 63 | if (sizeof(long) == 8) { 64 | factor=13*13*13*13; 65 | factor=factor*factor*factor*13; 66 | } 67 | else 68 | factor=69069; 69 | lo_limit=(double)ULONG_MAX; 70 | 71 | check_alloc(rnd_array=(unsigned long *)malloc(9689*sizeof(unsigned long))); 72 | check_alloc(nexti=(unsigned long *)malloc(9689*sizeof(long))); 73 | check_alloc(rnd1279=(unsigned long *)malloc(1279*sizeof(unsigned long))); 74 | check_alloc(next1279=(unsigned long *)malloc(1279*sizeof(long))); 75 | 76 | rnd_array[0]=rnd1279[0]=iseed; 77 | rnd69=iseed; 78 | index=iseed; 79 | nexti[0]=next1279[0]=1; 80 | 81 | for (i=1;i<9689;i++) { 82 | rnd_array[i]=factor*rnd_array[i-1]+1; 83 | nexti[i]=i+1; 84 | } 85 | 86 | for (i=1;i<1279;i++) { 87 | rnd1279[i]=factor*rnd1279[i-1]+1; 88 | next1279[i]=i+1; 89 | } 90 | nexti[9688]=next1279[1278]=0; 91 | 92 | for (i=1;i<2000;i++) { 93 | index=factor*index+1; 94 | z=rnd1279[((index>>10)%1279)]; 95 | z=(z<<10)+(z>>10); 96 | index=factor*index+1; 97 | rnd1279[((index>>10)%1279)] += z; 98 | } 99 | 100 | nexti[9688]=next1279[1278]=0; 101 | rndtime=9688; 102 | rndtime1=9688-157; 103 | rndtime2=9688-314; 104 | rndtime3=9688-471; 105 | t1279=1278; 106 | t1279_1=1278-216; 107 | t1279_2=1278-299; 108 | t1279_3=1278-598; 109 | } 110 | 111 | unsigned long rnd_long(void) 112 | { 113 | rndtime=nexti[rndtime]; 114 | rndtime1=nexti[rndtime1]; 115 | rndtime2=nexti[rndtime2]; 116 | rndtime3=nexti[rndtime3]; 117 | rnd_array[rndtime] ^= rnd_array[rndtime1] 118 | ^rnd_array[rndtime2]^rnd_array[rndtime3]; 119 | 120 | return rnd_array[rndtime]; 121 | } 122 | 123 | unsigned long rnd_1279(void) 124 | { 125 | t1279=next1279[t1279]; 126 | t1279_1=next1279[t1279_1]; 127 | t1279_2=next1279[t1279_2]; 128 | t1279_3=next1279[t1279_3]; 129 | 130 | rnd1279[t1279] += (rnd1279[t1279_1] + rnd1279[t1279_2] 131 | + rnd1279[t1279_3]); 132 | return rnd1279[t1279]; 133 | } 134 | 135 | unsigned long rnd69069(void) 136 | { 137 | return (rnd69=rnd69*factor+1); 138 | } 139 | 140 | double gaussian(double sigma) 141 | { 142 | static unsigned long gausscount=0; 143 | double x,r,u,phi; 144 | static double y; 145 | 146 | if (!(gausscount++ & 0x1)) { 147 | phi=2.0*M_PI*(double)rnd_1279()/lo_limit; 148 | u=(double)rnd_1279()/lo_limit; 149 | r=sqrt(-2.0*sigma*sigma*log(u)); 150 | x=r*cos(phi); 151 | y=r*sin(phi); 152 | 153 | return x; 154 | } 155 | else 156 | return y; 157 | } 158 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/rand_arb_dist.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Feb 11, 2006 */ 21 | /*Changes: 22 | Feb 11, 2006: First version 23 | */ 24 | /*Comment: 25 | Creates a sequence of random numbers with arbitrary distribution 26 | Input Paramters: x=original data defining the distribution 27 | nx= length of x 28 | nc= number of random numbers to create 29 | nb= number of bins for the distribution 30 | iseed = seed for the random number generator 31 | Return: rand = array containing the nc random numbers 32 | */ 33 | 34 | #ifndef _STDLIB_H 35 | #include 36 | #endif 37 | 38 | #ifndef _LIMITS_H 39 | #include 40 | #endif 41 | 42 | #ifndef _TIME_H 43 | #include 44 | #endif 45 | 46 | extern void rescale_data(double*,unsigned long,double*,double*); 47 | extern void check_alloc(void*); 48 | extern unsigned long rnd_long(void); 49 | extern void rnd_init(unsigned long); 50 | 51 | double *rand_arb_dist(double *x,unsigned long nx,unsigned long nc, 52 | unsigned int nb,unsigned long iseed) 53 | { 54 | double h,min,inter,*randarb,drnd,epsinv=1.0/(double)nb; 55 | unsigned long i,j,*box,hrnd,nall=nx+nb; 56 | 57 | rescale_data(x,nx,&min,&inter); 58 | 59 | check_alloc(box=(unsigned long*)malloc(sizeof(unsigned long)*nb)); 60 | for (i=0;i= 1.0) 66 | h -= epsinv/2.0; 67 | j=(unsigned int)(h*nb); 68 | box[j]++; 69 | } 70 | for (i=1;i= hrnd) 86 | break; 87 | drnd=(double)rnd_long()/(double)ULONG_MAX*epsinv; 88 | randarb[i]=min+((double)j*epsinv+drnd)*inter; 89 | } 90 | 91 | free(box); 92 | 93 | return randarb; 94 | } 95 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/rescale_data.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Sep 5, 2004*/ 21 | /* Changes: 22 | * Sep 5 2004: + include 23 | */ 24 | 25 | #include 26 | #include "tisean_cec.h" 27 | #include 28 | 29 | void rescale_data(double *x,unsigned long l,double *min,double *interval) 30 | { 31 | int i; 32 | 33 | *min=*interval=x[0]; 34 | 35 | for (i=1;i *interval) *interval=x[i]; 38 | } 39 | *interval -= *min; 40 | 41 | if (*interval != 0.0) { 42 | for (i=0;i 22 | #include 23 | #include 24 | 25 | int scan_help(int n,char **in) 26 | { 27 | int i; 28 | 29 | for (i=1;i 22 | #include 23 | #include 24 | #include 25 | #include "tsa.h" 26 | 27 | char check_col(char *col) 28 | { 29 | int i; 30 | 31 | for (i=0;i 0) 52 | vcol=check_col(hcol); 53 | *(name+j)='\0'; 54 | break; 55 | } 56 | *(hname+j)=*(name+j); 57 | j++; 58 | } 59 | *col=(unsigned int)atoi(hcol); 60 | free(hname); 61 | free(hcol); 62 | 63 | return vcol; 64 | } 65 | 66 | char* search_datafile(int n,char **names,unsigned int *col, 67 | unsigned int verbosity) 68 | { 69 | char valid=0,validcol=0; 70 | char *retname=NULL; 71 | int i; 72 | unsigned int hcol; 73 | FILE *test; 74 | 75 | for (i=n-1;i>0;i--) { 76 | if (names[i] != NULL) { 77 | valid=0; 78 | if (strcmp(names[i],"-")) { 79 | if (col != 0) 80 | validcol=look_for_column(names[i],&hcol); 81 | test=fopen(names[i],"r"); 82 | if (test == NULL) { 83 | fprintf(stderr,"File %s not found!\n",names[i]); 84 | } 85 | else { 86 | fclose(test); 87 | if ((col != 0) && (validcol == 1)) 88 | *col=hcol; 89 | if (col != 0) { 90 | if (verbosity&VER_INPUT) 91 | fprintf(stderr,"Using %s as datafile, reading column %u\n", 92 | names[i],*col); 93 | } 94 | else { 95 | if (verbosity&VER_INPUT) 96 | fprintf(stderr,"Using %s as datafile!\n",names[i]); 97 | } 98 | check_alloc(retname=(char*)calloc(strlen(names[i])+1,(size_t)1)); 99 | strcpy(retname,names[i]); 100 | names[i]=NULL; 101 | return retname; 102 | } 103 | } 104 | else { 105 | valid=1; 106 | break; 107 | } 108 | } 109 | } 110 | 111 | if (valid == 1) { 112 | if (verbosity&VER_INPUT) 113 | fprintf(stderr,"Reading input from stdin!\n"); 114 | return NULL; 115 | } 116 | 117 | if (verbosity&VER_INPUT) { 118 | if ((col != 0) && (validcol == 1)) 119 | fprintf(stderr,"Reading input from stdin, using column %u!\n",*col); 120 | else 121 | fprintf(stderr,"Reading input from stdin!\n"); 122 | } 123 | 124 | return NULL; 125 | } 126 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/solvele.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /* Author: Rainer Hegger Last modified: Aug 14th, 1998 */ 21 | #include 22 | #include 23 | #include 24 | #include "tisean_cec.h" 25 | 26 | void solvele(double **mat,double *vec,unsigned int n) 27 | { 28 | double vswap,*mswap,*hvec,max,h,pivot,q; 29 | int i,j,k,maxi; 30 | 31 | for (i=0;i max) { 36 | max=h; 37 | maxi=j; 38 | } 39 | if (maxi != i) { 40 | mswap=mat[i]; 41 | mat[i]=mat[maxi]; 42 | mat[maxi]=mswap; 43 | vswap=vec[i]; 44 | vec[i]=vec[maxi]; 45 | vec[maxi]=vswap; 46 | } 47 | 48 | hvec=mat[i]; 49 | pivot=hvec[i]; 50 | if (fabs(pivot) == 0.0) { 51 | fprintf(stderr,"Singular matrix! Exiting!\n"); 52 | exit(SOLVELE_SINGULAR_MATRIX); 53 | } 54 | for (j=i+1;j=0;i--) { 64 | hvec=mat[i]; 65 | for (j=n-1;j>i;j--) 66 | vec[i] -= hvec[j]*vec[j]; 67 | vec[i] /= hvec[i]; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/test_outfile.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Mar 20, 1999 */ 21 | #include 22 | #include 23 | #include "tisean_cec.h" 24 | 25 | void test_outfile(char *name) 26 | { 27 | FILE *file; 28 | 29 | file=fopen(name,"a"); 30 | if (file == NULL) { 31 | fprintf(stderr,"Couldn't open %s for writing. Exiting\n",name); 32 | exit(TEST_OUTFILE_NO_WRITE_ACCESS); 33 | } 34 | fclose(file); 35 | } 36 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/tisean_cec.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: May 26, 2000*/ 21 | 22 | /* These definitions give the exit codes for the C part of the Tisean package. 23 | Typically the name is build up of, first, the name of the routine creating 24 | the exception, secondly, sort of an description of the exception. 25 | */ 26 | 27 | #ifndef _TISEAN_CEC_H 28 | #define _TISEAN_CEC_H 29 | 30 | /* These are the codes for the routines subtree */ 31 | #define RESCALE_DATA_ZERO_INTERVAL 11 32 | #define CHECK_ALLOC_NOT_ENOUGH_MEMORY 12 33 | #define CHECK_OPTION_NOT_UNSIGNED 13 34 | #define CHECK_OPTION_NOT_INTEGER 14 35 | #define CHECK_OPTION_NOT_FLOAT 15 36 | #define CHECK_OPTION_NOT_TWO 16 37 | #define CHECK_OPTION_C_NO_VALUE 17 38 | #define TEST_OUTFILE_NO_WRITE_ACCESS 18 39 | #define SOLVELE_SINGULAR_MATRIX 19 40 | #define GET_SERIES_NO_LINES 20 41 | #define GET_MULTI_SERIES_WRONG_TYPE_OF_C 21 42 | #define GET_MULTI_SERIES_NO_LINES 22 43 | #define VARIANCE_VAR_EQ_ZERO 23 44 | #define EIG2_TOO_MANY_ITERATIONS 24 45 | #define CHECK_OPTION_NOT_THREE 25 46 | 47 | /* These are the codes for the main routines */ 48 | #define LYAP_SPEC_NOT_ENOUGH_NEIGHBORS 50 49 | #define LYAP_SPEC_DATA_TOO_SHORT 51 50 | #define AR_MODEL_TOO_MANY_POLES 52 51 | #define EXTREMA_STRANGE_COMPONENT 53 52 | #define FALSE_NEAREST_NOT_ENOUGH_POINTS 54 53 | #define FSLE__TOO_LARGE_MINEPS 55 54 | #define GHKSS__TOO_MANY_NEIGHBORS 56 55 | #define NSTAT_Z__INVALID_STRING_FOR_OPTION 57 56 | #define NSTAT_Z__NOT_UNSIGNED_FOR_OPTION 58 57 | #define NSTAT_Z__TOO_LARGE_FOR_OPTION 59 58 | #define NSTAT_Z__OPTION_NOT_SET 60 59 | #define NSTAT_Z__TOO_MANY_PIECES 61 60 | #define NSTEP__ESCAPE_REGION 62 61 | #define POINCARE__WRONG_COMPONENT 63 62 | #define POINCARE__OUTSIDE_REGION 64 63 | #define POLYBACK__WRONG_PARAMETER_FILE 65 64 | #define POLYNOMP__WRONG_PARAMETER_FILE 66 65 | #define RESCALE__WRONG_INTERVAL 67 66 | #define SAV_GOL__UNDERDETERMINED 68 67 | #define SAV_GOL__TOO_LARGE_DERIVATIVE 69 68 | #define MAKENOISE__FLAGS_REQUIRED 70 69 | #define ZEROTH__STEP_TOO_LARGE 71 70 | #define LYAP_K__MAXITER_TOO_LARGE 72 71 | #define DELAY_WRONG_FORMAT_F 73 72 | #define DELAY_DIM_NOT_EQUAL_F_M 74 73 | #define DELAY_DIM_NOT_EQUAL_F_m 75 74 | #define DELAY_WRONG_FORMAT_D 76 75 | #define DELAY_WRONG_NUM_D 77 76 | #define DELAY_INCONS_d_D 78 77 | #define DELAY_SMALL_ZERO 79 78 | #define DELAY_INCONS_m_M 80 79 | #define ONESTEP_TOO_FEW_POINTS 81 80 | #define MEM_SPEC_TOO_MANY_POLES 82 81 | 82 | /* Global stuff */ 83 | #define VECTOR_TOO_LARGE_FOR_LENGTH 100 84 | 85 | #endif 86 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/tsa.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: Sep 3, 1999 */ 21 | 22 | #ifndef _TSA_ROUTINES_H 23 | #define _TSA_ROUTINES_H 24 | 25 | #ifndef _TISEAN_CEC_H 26 | #include "tisean_cec.h" 27 | #endif 28 | 29 | /* size of the string which reads the input data 30 | if your lines are longer than some 500 reals, increase the value 31 | */ 32 | #define INPUT_SIZE 1024 33 | 34 | /* The possible names of the verbosity levels */ 35 | #define VER_INPUT 0x1 36 | #define VER_USR1 0x2 37 | #define VER_USR2 0x4 38 | #define VER_USR3 0x8 39 | #define VER_USR4 0x10 40 | #define VER_USR5 0x20 41 | #define VER_USR6 0x40 42 | #define VER_FIRST_LINE 0x80 43 | 44 | /* Uncomment the variable to get rid of the initial Version message */ 45 | /*#define OMIT_WHAT_I_DO*/ 46 | 47 | #define sqr(x) ((x)*(x)) 48 | 49 | #ifdef __cplusplus 50 | extern "C" { 51 | #endif 52 | 53 | extern int scan_help(int,char**); 54 | extern double *get_series(char *,unsigned long *,unsigned long, 55 | unsigned int,unsigned int); 56 | extern double **get_multi_series(char *,unsigned long *,unsigned long, 57 | unsigned int *,char *,char,unsigned int); 58 | extern void rescale_data(double *,unsigned long,double *,double *); 59 | extern void variance(double *,unsigned long,double *,double *); 60 | extern void make_box(double *,long **,long *,unsigned long, 61 | unsigned int,unsigned int,unsigned int,double); 62 | extern unsigned long find_neighbors(double *,long **,long *,double *, 63 | unsigned long,unsigned int,unsigned int, 64 | unsigned int,double,unsigned long *); 65 | extern char* search_datafile(int, char**,unsigned int*,unsigned int); 66 | extern char* check_option(char**,int,int,int); 67 | extern void solvele(double**,double *,unsigned int); 68 | extern void test_outfile(char*); 69 | extern double** invert_matrix(double**,unsigned int); 70 | extern unsigned long exclude_interval(unsigned long,long,long, 71 | unsigned long*,unsigned long*); 72 | extern void make_multi_box(double **,long **,long *,unsigned long, 73 | unsigned int,unsigned int,unsigned int, 74 | unsigned int,double); 75 | /*only used for nrlazy. Will be removed with nrlazy */ 76 | extern void make_multi_box2(double **,long **,long *,unsigned long, 77 | unsigned int,unsigned int,unsigned int, 78 | unsigned int,double); 79 | extern unsigned long find_multi_neighbors(double **,long **,long *,double **, 80 | unsigned long,unsigned int, 81 | unsigned int,unsigned int, 82 | unsigned int,double,unsigned long *); 83 | extern unsigned int** make_multi_index(unsigned int,unsigned int,unsigned int); 84 | 85 | extern void check_alloc(void *); 86 | extern char* myfgets(char *,int *,FILE *,unsigned int); 87 | extern void what_i_do(char *, char *); 88 | extern double* rand_arb_dist(double *,unsigned long,unsigned long, 89 | unsigned int,unsigned long); 90 | 91 | /* routines from rand.c */ 92 | extern void rnd_init(unsigned long); 93 | extern unsigned long rnd_long(); 94 | extern unsigned long rnd_1279(); 95 | extern unsigned long rnd69069(); 96 | extern double gaussian(double); 97 | 98 | /* routines from eigen.c */ 99 | extern void eigen(double**,unsigned long,double*); 100 | 101 | #ifdef __cplusplus 102 | } 103 | #endif 104 | 105 | #endif 106 | -------------------------------------------------------------------------------- /optimal_embedding/source_c/routines/variance.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of TISEAN 3 | * 4 | * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber 5 | * 6 | * TISEAN is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * TISEAN is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with TISEAN; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | /*Author: Rainer Hegger Last modified: May 23th, 1998 */ 21 | #include 22 | #include 23 | #include 24 | #include "tisean_cec.h" 25 | 26 | void variance(double *s,unsigned long l,double *av,double *var) 27 | { 28 | unsigned long i; 29 | double h; 30 | 31 | *av= *var=0.0; 32 | 33 | for (i=0;i 22 | #include 23 | #include 24 | #include 25 | 26 | void what_i_do(char *name,char *text) 27 | { 28 | fprintf(stderr, "\nTISEAN 3.0.1 (C) R. Hegger, H. Kantz," 29 | " T. Schreiber (1998-2007)\n\n" 30 | "%s: %s\n\n",name,text); 31 | } 32 | -------------------------------------------------------------------------------- /statutils.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy 3 | from scipy.interpolate import interp1d 4 | 5 | def bootstrap(vec, func, n_bootstraps): 6 | results = list() 7 | for i in xrange(n_bootstraps): 8 | vec_bs = numpy.random.choice(vec, replace=True) 9 | results.append(func(vec_bs)) 10 | return results 11 | 12 | 13 | def inverse_quantile(x, y): 14 | '''Calculates the location of each member of y in x 15 | 16 | :param x: 17 | :param y: 18 | :return: 19 | 20 | >>> inverse_quantile([1,2,3], 2.5).tolist() 21 | 0.75 22 | >>> inverse_quantile([1,2,3], [2.5]).tolist() 23 | [0.75] 24 | >>> inverse_quantile([1,1,1], [0.99, 1, 1.01]).tolist() 25 | [0.0, 0.5, 1.0] 26 | >>> inverse_quantile([1], [0.5, 1.0, 1.5]).tolist() 27 | [0.0, 0.5, 1.0] 28 | >>> inverse_quantile([1, 2, 3], [[0.5, 1.0], [1.5, 2.5]]).tolist() 29 | [[0.0, 0.0], [0.25, 0.75]] 30 | ''' 31 | x = numpy.sort(x) 32 | if not isinstance(y, numpy.ndarray): 33 | y = numpy.array(y) 34 | 35 | assert len(x.shape) == 1 36 | 37 | if x[0] == x[-1]: 38 | inv_q_y = numpy.ones_like(y) * float('nan') 39 | if len(y.shape) == 0: 40 | if inv_q_y == x[0]: 41 | inv_q_y = 0.5 42 | else: 43 | inv_q_y[y == x[0]] = 0.5 44 | else: 45 | quantiles = numpy.linspace(0.0, 1.0, num=len(x), endpoint=True) 46 | interp_func = interp1d(x, quantiles, bounds_error=False) 47 | inv_q_y = interp_func(y) 48 | if len(y.shape) == 0: 49 | if y < x[0]: 50 | inv_q_y = 0.0 51 | elif y > x[-1]: 52 | inv_q_y = 1.0 53 | else: 54 | inv_q_y[y < x[0]] = 0.0 55 | inv_q_y[y > x[-1]] = 1.0 56 | assert numpy.all(numpy.logical_not(numpy.isnan(y))) 57 | 58 | return numpy.array(inv_q_y) 59 | 60 | -------------------------------------------------------------------------------- /uzalcost.py: -------------------------------------------------------------------------------- 1 | import os 2 | SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) 3 | import sys 4 | import tempfile 5 | import subprocess 6 | import numpy 7 | from collections import OrderedDict 8 | import shutil 9 | 10 | def configure(dir): 11 | cwd = os.getcwd() 12 | 13 | os.chdir(dir) 14 | proc = subprocess.Popen(['./configure']) 15 | result = proc.wait() 16 | if result != 0: 17 | raise Exception('configure returned nonzero status') 18 | 19 | os.chdir(cwd) 20 | 21 | def make(dir): 22 | proc = subprocess.Popen(['make'], cwd=dir) 23 | result = proc.wait() 24 | if result != 0: 25 | raise Exception('make returned nonzero status') 26 | 27 | def run_and_load_files(args, stdin_data, filenames): 28 | tmp_dir = tempfile.mkdtemp() 29 | 30 | proc = subprocess.Popen( 31 | args, 32 | stdout=subprocess.PIPE, 33 | stderr=subprocess.PIPE, 34 | stdin=subprocess.PIPE, 35 | cwd=tmp_dir 36 | ) 37 | stdout_data, stderr_data = proc.communicate(stdin_data) 38 | 39 | file_data_dict = OrderedDict() 40 | for filename in filenames: 41 | filepath = os.path.join(tmp_dir, filename) 42 | if os.path.exists(filepath): 43 | with open(filepath) as f: 44 | file_data = f.read() 45 | file_data_dict[filename] = file_data 46 | 47 | shutil.rmtree(tmp_dir) 48 | 49 | return stdout_data, stderr_data, file_data_dict 50 | 51 | def parse_results(file_data): 52 | ms = [] 53 | Lks = [] 54 | for line in file_data.split('\n'): 55 | if not line.startswith('#') and len(line) > 0: 56 | try: 57 | pieces = line.split(' ') 58 | m = int(pieces[0]) + 1 59 | Lk = float(pieces[1]) 60 | ms.append(m) 61 | Lks.append(Lk) 62 | except: 63 | pass 64 | 65 | return ms, Lks 66 | 67 | def parse_params(stderr_data): 68 | params = {} 69 | for line in stderr_data.split('\n'): 70 | if line.startswith('Using T_M='): 71 | pieces = line.split('=') 72 | params['tw_max'] = int(pieces[1]) 73 | elif line.startswith('Using ThW='): 74 | pieces = line.split('=') 75 | params['theiler_window'] = int(pieces[1]) 76 | elif line.startswith('Using k='): 77 | pieces = line.split('=') 78 | params['n_neighbors'] = int(pieces[1].split(' ')[0]) 79 | return params 80 | 81 | def set_up_uzal_costfunc(): 82 | uzal_dir = os.path.join(SCRIPT_DIR, 'optimal_embedding') 83 | costfunc_path = os.path.join(uzal_dir, 'source_c', 'costfunc') 84 | if not os.path.exists(costfunc_path): 85 | configure(uzal_dir) 86 | make(uzal_dir) 87 | 88 | return costfunc_path 89 | 90 | 91 | def run_uzal_costfunc(x, neighbor_count=None, theiler_window=None, max_prediction_horizon=None, max_window=None): 92 | r'''Runs the Uzal et al. cost function for full embeddings. 93 | >>> ms, Lks, params = run_uzal_costfunc(numpy.random.normal(0, 1, size=1000)) 94 | 95 | >>> sys.stderr.write('ms = {0}\n'.format(ms)) 96 | >>> sys.stderr.write("Lks = {0}\n".format(Lks)) 97 | >>> sys.stderr.write("params = {0}\n".format(params)) 98 | ''' 99 | costfunc_path = set_up_uzal_costfunc() 100 | 101 | stdin_data = '\n'.join(['{0}'.format(xi) for xi in x]) 102 | stdin_data += '\n' 103 | 104 | args = [costfunc_path, '-e', '2'] 105 | if neighbor_count is not None: 106 | args += ['-k', str(neighbor_count)] 107 | if theiler_window is not None: 108 | args += ['-t', str(theiler_window)] 109 | if max_prediction_horizon is not None: 110 | args += ['-s', str(max_prediction_horizon)] 111 | if max_window is not None: 112 | args += ['-W', str(max_window)] 113 | 114 | stdout_data, stderr_data, file_data_dict = run_and_load_files( 115 | args, stdin_data, 116 | ['stdin.amp'] 117 | ) 118 | 119 | sys.stderr.write(stdout_data) 120 | sys.stderr.write(stderr_data) 121 | 122 | ms, Lks = parse_results(file_data_dict['stdin.amp']) 123 | params = parse_params(stderr_data) 124 | 125 | return ms, Lks, params 126 | --------------------------------------------------------------------------------