%Simulation unit test cases
%
% Author: Jonathan Karr, jkarr@stanford.edu
% Author: Jared Jacobs, jmjacobs@stanford.edu
% Affiliation: Covert Lab, Department of Bioengineering, Stanford University
% Last updated: 9/14/2010
classdef Simulation_Test < TestCase
    properties
        simulation
        outputDir
    end

    methods
        function this = Simulation_Test(name)
            this = this@TestCase(name);
        end

        function setUp(this)
            this.simulation = this.newSimulation();
            this.outputDir = '';
        end

        function tearDown(this)
            if ~isempty(this.outputDir) && exist(this.outputDir, 'dir')
                rmdir(this.outputDir, 's');
            end
        end
    end

    %tests
    methods
        function testConstants(this)
            sim = this.simulation;

            assertAllEqual(false, isnan(sim.state('Metabolite').molecularWeights));
            assertEqual(1, sim.compartment.cytosolIndexs);
        end

        function testAllocateMemoryForState(this)
            this.simulation.allocateMemoryForState(1);  %no run-time errors
        end

        function testApplyPerturbations(this)
            sim = this.simulation;
            g =  sim.gene;

            % 1 mRNA genes
            this.helper_testApplyPerturbations(g.mRNAIndexs(1));

            % 2 mRNA genes
            this.helper_testApplyPerturbations(g.mRNAIndexs([1 101]));

            % mRNA genes
            this.helper_testApplyPerturbations(g.mRNAIndexs);

            % rRNA genes
            this.helper_testApplyPerturbations(g.rRNAIndexs);

            % sRNA genes
            this.helper_testApplyPerturbations(g.sRNAIndexs);

            % tRNA genes
            this.helper_testApplyPerturbations(g.tRNAIndexs);

            % all genes
            this.helper_testApplyPerturbations((1:numel(g.wholeCellModelIDs))');
        end

        function helper_testApplyPerturbations(this, geneIdxs)
            %% references
            sim = this.simulation;
            g =  sim.gene;
            r = sim.state('Rna');
            pm = sim.state('ProteinMonomer');
            pc = sim.state('ProteinComplex');
            ftsZRing = sim.state('FtsZRing');
            c = sim.state('Chromosome');
            rnaPol = sim.state('RNAPolymerase');
            rib = sim.state('Ribosome');
            pol = sim.state('Polypeptide');
            transcript = sim.state('Transcript');

            %% initialize state
            r.decayRates(:) = 0;
            pm.decayRates(:) = 0;
            pc.decayRates(:) = 0;
            r.counts(:) = 1;
            pm.counts(:) = 1;
            pc.counts(:) = 1;

            r.counts(r.boundIndexs(r.matureSRNAIndexs), :) = 0;

            c.initialize();
            vals = setdiff((1:numel(pm.boundIndexs))', pm.translationFactorIndexs);
            monPosStrnds = [100 * (1:numel(vals))'  ones(size(vals))];
            c.monomerBoundSites(monPosStrnds) = vals;
            vals = setdiff((1:numel(pc.boundIndexs))', [
                pc.ribosome70SIndexs
                pc.translationFactorIndexs
                pc.ftsZGTPIndexs
                pc.ftsZGDPIndexs
                pc.dnaAPolymerIndexs
                pc.replisomeIndexs
                ]);
            cpxPosStrnds = [1000 * (1:numel(vals))' + monPosStrnds(end, 1)  ones(size(vals))];
            c.complexBoundSites(cpxPosStrnds) = vals;
            assertIn(cpxPosStrnds(end, 1), [1 c.sequenceLen-1000]);
            pc.counts(pc.boundIndexs([pc.dnaAPolymerIndexs; pc.replisomeIndexs]), :) = 0;

            rnaPol.states = [
                rnaPol.nonSpecificallyBoundValue
                rnaPol.specificallyBoundValue
                ];
            rnaPol.positionStrands = [
                find(c.complexBoundSites == pc.rnaPolymeraseIndexs(1))
                find(c.complexBoundSites == pc.rnaPolymeraseIndexs(2))
                ];
            transcript.boundTranscriptionUnits = [0; 1];
            transcript.boundTranscriptProgress = [0; 0];
            transcript.boundTranscriptChromosome = [0; 0];

            rib.states = rib.activeValue;
            rib.boundMRNAs = 1;
            rib.mRNAPositions = 1;
            rib.tmRNAPositions = 0;
            pol.boundMRNAs = rib.boundMRNAs;
            pol.nascentMonomerLengths = rib.mRNAPositions;
            pol.proteolysisTagLengths = rib.tmRNAPositions;

            pc.counts(pc.boundIndexs([pc.ftsZGTPIndexs; pc.ftsZGDPIndexs]), :) = 0;
            ftsZRing.numEdgesOneStraight = 0;
            ftsZRing.numEdgesTwoStraight = 0;
            ftsZRing.numEdgesTwoBent = 0;
            ftsZRing.numResidualBent = 0;

            %% apply perturbations
            monIdxs = find(ismember(g.mRNAIndexs, geneIdxs));
            matRnaIdxs = find(any(r.matureRNAGeneComposition(setdiff(geneIdxs, g.mRNAIndexs), :), 1));
            cpxIdxs = find(any(any(pc.proteinComplexComposition(geneIdxs, :, :), 3), 1));

            otherMatRnaIdxs = setdiff(1:numel(r.matureIndexs), matRnaIdxs);
            otherMonIdxs = setdiff(1:numel(pm.matureIndexs), monIdxs);
            otherCpxIdxs = setdiff(1:numel(pc.matureIndexs), cpxIdxs);

            rnaDecayRates = r.decayRates;
            monDecayRates = pm.decayRates;
            cpxDecayRates = pc.decayRates;

            rnaCounts = r.counts;
            monCounts = pm.counts;
            cpxCounts = pc.counts;

            sim.applyOptions('geneticKnockouts', g.wholeCellModelIDs(geneIdxs));
            sim.applyPerturbations();

            %% assertions
            %decay rates
            decayRate = log(2)/(log(2)/1e6);

            assertAllEqual(0, r.decayRates(r.nascentIndexs));
            assertAllEqual(0, r.decayRates(r.intergenicIndexs));
            if ~isempty(matRnaIdxs)
                assertAllEqual(decayRate, r.decayRates(r.processedIndexs(matRnaIdxs)));
                assertAllEqual(decayRate, r.decayRates(r.matureIndexs(matRnaIdxs)));
                assertAllEqual(decayRate, r.decayRates(r.boundIndexs(matRnaIdxs)));
                assertAllEqual(decayRate, r.decayRates(r.misfoldedIndexs(matRnaIdxs)));
                assertAllEqual(decayRate, r.decayRates(r.damagedIndexs(matRnaIdxs)));
                assertAllEqual(decayRate, r.decayRates(r.aminoacylatedIndexs(matRnaIdxs)));
            end
            assertEqual(rnaDecayRates(r.processedIndexs(otherMatRnaIdxs)), r.decayRates(r.processedIndexs(otherMatRnaIdxs)));
            assertEqual(rnaDecayRates(r.matureIndexs(otherMatRnaIdxs)), r.decayRates(r.matureIndexs(otherMatRnaIdxs)));
            assertEqual(rnaDecayRates(r.boundIndexs(otherMatRnaIdxs)), r.decayRates(r.boundIndexs(otherMatRnaIdxs)));
            assertEqual(rnaDecayRates(r.misfoldedIndexs(otherMatRnaIdxs)), r.decayRates(r.misfoldedIndexs(otherMatRnaIdxs)));
            assertEqual(rnaDecayRates(r.damagedIndexs(otherMatRnaIdxs)), r.decayRates(r.damagedIndexs(otherMatRnaIdxs)));
            assertEqual(rnaDecayRates(r.aminoacylatedIndexs(otherMatRnaIdxs)), r.decayRates(r.aminoacylatedIndexs(otherMatRnaIdxs)));

            if ~isempty(monIdxs)
                assertAllEqual(decayRate, pm.decayRates(pm.nascentIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.signalSequenceIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.processedIIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.processedIIIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.foldedIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.matureIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.inactivatedIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.boundIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.misfoldedIndexs(monIdxs)));
                assertAllEqual(decayRate, pm.decayRates(pm.damagedIndexs(monIdxs)));
            end
            assertEqual(monDecayRates(pm.nascentIndexs(otherMonIdxs)), pm.decayRates(pm.nascentIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.signalSequenceIndexs(otherMonIdxs)), pm.decayRates(pm.signalSequenceIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.processedIIndexs(otherMonIdxs)), pm.decayRates(pm.processedIIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.processedIIIndexs(otherMonIdxs)), pm.decayRates(pm.processedIIIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.foldedIndexs(otherMonIdxs)), pm.decayRates(pm.foldedIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.matureIndexs(otherMonIdxs)), pm.decayRates(pm.matureIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.inactivatedIndexs(otherMonIdxs)), pm.decayRates(pm.inactivatedIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.boundIndexs(otherMonIdxs)), pm.decayRates(pm.boundIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.misfoldedIndexs(otherMonIdxs)), pm.decayRates(pm.misfoldedIndexs(otherMonIdxs)));
            assertEqual(monDecayRates(pm.damagedIndexs(otherMonIdxs)), pm.decayRates(pm.damagedIndexs(otherMonIdxs)));

            if ~isempty(cpxIdxs)
                assertAllEqual(decayRate, pc.decayRates(pc.nascentIndexs(cpxIdxs)));
                assertAllEqual(decayRate, pc.decayRates(pc.matureIndexs(cpxIdxs)));
                assertAllEqual(decayRate, pc.decayRates(pc.inactivatedIndexs(cpxIdxs)));
                assertAllEqual(decayRate, pc.decayRates(pc.boundIndexs(cpxIdxs)));
                assertAllEqual(decayRate, pc.decayRates(pc.misfoldedIndexs(cpxIdxs)));
                assertAllEqual(decayRate, pc.decayRates(pc.damagedIndexs(cpxIdxs)));
            end
            assertEqual(cpxDecayRates(pc.nascentIndexs(otherCpxIdxs)), pc.decayRates(pc.nascentIndexs(otherCpxIdxs)));
            assertEqual(cpxDecayRates(pc.matureIndexs(otherCpxIdxs)), pc.decayRates(pc.matureIndexs(otherCpxIdxs)));
            assertEqual(cpxDecayRates(pc.inactivatedIndexs(otherCpxIdxs)), pc.decayRates(pc.inactivatedIndexs(otherCpxIdxs)));
            assertEqual(cpxDecayRates(pc.boundIndexs(otherCpxIdxs)), pc.decayRates(pc.boundIndexs(otherCpxIdxs)));
            assertEqual(cpxDecayRates(pc.misfoldedIndexs(otherCpxIdxs)), pc.decayRates(pc.misfoldedIndexs(otherCpxIdxs)));
            assertEqual(cpxDecayRates(pc.damagedIndexs(otherCpxIdxs)), pc.decayRates(pc.damagedIndexs(otherCpxIdxs)));

            %counts
            assertAllEqual(1, r.counts(r.nascentIndexs, :));
            assertAllEqual(1, r.counts(r.intergenicIndexs, :));
            if ~isempty(matRnaIdxs)
                assertAllEqual(0, r.counts(r.processedIndexs(matRnaIdxs), :));
                assertAllEqual(0, r.counts(r.matureIndexs(matRnaIdxs), :));
                assertAllEqual(0, r.counts(r.boundIndexs(matRnaIdxs), :));
                assertAllEqual(0, r.counts(r.misfoldedIndexs(matRnaIdxs), :));
                assertAllEqual(0, r.counts(r.damagedIndexs(matRnaIdxs), :));
                assertAllEqual(0, r.counts(r.aminoacylatedIndexs(matRnaIdxs), :));
            end
            assertEqual(rnaCounts(r.processedIndexs(otherMatRnaIdxs, :)), r.counts(r.processedIndexs(otherMatRnaIdxs, :)));
            assertEqual(rnaCounts(r.matureIndexs(otherMatRnaIdxs, :)), r.counts(r.matureIndexs(otherMatRnaIdxs, :)));
            assertEqual(rnaCounts(r.boundIndexs(otherMatRnaIdxs, :)), r.counts(r.boundIndexs(otherMatRnaIdxs, :)));
            assertEqual(rnaCounts(r.misfoldedIndexs(otherMatRnaIdxs, :)), r.counts(r.misfoldedIndexs(otherMatRnaIdxs, :)));
            assertEqual(rnaCounts(r.damagedIndexs(otherMatRnaIdxs, :)), r.counts(r.damagedIndexs(otherMatRnaIdxs, :)));
            assertEqual(rnaCounts(r.aminoacylatedIndexs(otherMatRnaIdxs, :)), r.counts(r.aminoacylatedIndexs(otherMatRnaIdxs, :)));

            if ~isempty(monIdxs)
                assertAllEqual(0, pm.counts(pm.nascentIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.signalSequenceIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.processedIIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.processedIIIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.foldedIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.matureIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.inactivatedIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.boundIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.misfoldedIndexs(monIdxs), :));
                assertAllEqual(0, pm.counts(pm.damagedIndexs(monIdxs), :));
            end
            assertEqual(monCounts(pm.nascentIndexs(otherMonIdxs, :)), pm.counts(pm.nascentIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.signalSequenceIndexs(otherMonIdxs, :)), pm.counts(pm.signalSequenceIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.processedIIndexs(otherMonIdxs, :)), pm.counts(pm.processedIIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.processedIIIndexs(otherMonIdxs, :)), pm.counts(pm.processedIIIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.foldedIndexs(otherMonIdxs, :)), pm.counts(pm.foldedIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.matureIndexs(otherMonIdxs, :)), pm.counts(pm.matureIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.inactivatedIndexs(otherMonIdxs, :)), pm.counts(pm.inactivatedIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.boundIndexs(otherMonIdxs, :)), pm.counts(pm.boundIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.misfoldedIndexs(otherMonIdxs, :)), pm.counts(pm.misfoldedIndexs(otherMonIdxs, :)));
            assertEqual(monCounts(pm.damagedIndexs(otherMonIdxs, :)), pm.counts(pm.damagedIndexs(otherMonIdxs, :)));

            if ~isempty(cpxIdxs)
                assertAllEqual(0, pc.counts(pc.nascentIndexs(cpxIdxs), :));
                assertAllEqual(0, pc.counts(pc.matureIndexs(cpxIdxs), :));
                assertAllEqual(0, pc.counts(pc.inactivatedIndexs(cpxIdxs), :));
                assertAllEqual(0, pc.counts(pc.boundIndexs(cpxIdxs), :));
                assertAllEqual(0, pc.counts(pc.misfoldedIndexs(cpxIdxs), :));
                assertAllEqual(0, pc.counts(pc.damagedIndexs(cpxIdxs), :));
            end
            assertEqual(cpxCounts(pc.nascentIndexs(otherCpxIdxs, :)), pc.counts(pc.nascentIndexs(otherCpxIdxs, :)));
            assertEqual(cpxCounts(pc.matureIndexs(otherCpxIdxs, :)), pc.counts(pc.matureIndexs(otherCpxIdxs, :)));
            assertEqual(cpxCounts(pc.inactivatedIndexs(otherCpxIdxs, :)), pc.counts(pc.inactivatedIndexs(otherCpxIdxs, :)));
            assertEqual(cpxCounts(pc.boundIndexs(otherCpxIdxs, :)), pc.counts(pc.boundIndexs(otherCpxIdxs, :)));
            assertEqual(cpxCounts(pc.misfoldedIndexs(otherCpxIdxs, :)), pc.counts(pc.misfoldedIndexs(otherCpxIdxs, :)));
            assertEqual(cpxCounts(pc.damagedIndexs(otherCpxIdxs, :)), pc.counts(pc.damagedIndexs(otherCpxIdxs, :)));

            %% test membrane protein decay
            %monomer
            sim = edu.stanford.covert.cell.sim.SimulationFixture.load([], true);
            comp = sim.compartment;
            g = sim.gene;
            pm = sim.state('ProteinMonomer');
            protDcy = sim.process('ProteinDecay');

            idx = find(pm.compartments(pm.matureIndexs) == comp.membraneIndexs, 1, 'first');

            sim.applyOptions('geneticKnockouts', g.wholeCellModelIDs(g.mRNAIndexs(idx)));
            sim.applyPerturbations();

            monIdx = pm.matureIndexs(idx);
            pm.counts(monIdx, :) = 0;
            pm.counts(monIdx, comp.membraneIndexs) = 1;

            protDcy.copyFromState();
            protDcy.enzymes(:) = 1e6;
            protDcy.substrates(:) = 1e6;
            protDcy.evolveState();
            protDcy.copyToState();

            assertEqual(0, pm.counts(monIdx, comp.membraneIndexs));

            %complex
            sim = edu.stanford.covert.cell.sim.SimulationFixture.load([], true);
            comp = sim.compartment;
            g = sim.gene;
            pc = sim.state('ProteinComplex');
            protDcy = sim.process('ProteinDecay');

            idx = find(pc.compartments(pc.matureIndexs) == comp.membraneIndexs, 1, 'first');
            geneIdx = find(any(pc.proteinComplexComposition(:, idx, :), 3), 1, 'first');

            sim.applyOptions('geneticKnockouts', g.wholeCellModelIDs(geneIdx));
            sim.applyPerturbations();

            cpxIdx = pc.matureIndexs(idx);
            pc.counts(cpxIdx, :) = 0;
            pc.counts(cpxIdx, comp.membraneIndexs) = 1;

            protDcy.copyFromState();
            protDcy.enzymes(:) = 1e6;
            protDcy.substrates(:) = 1e6;
            protDcy.evolveState();
            protDcy.copyToState();

            assertEqual(0, pc.counts(cpxIdx, comp.membraneIndexs));
        end

        function testEvolveState(this)
            sim = this.simulation;
            met = sim.state('Metabolite');

            t0 = sim.state('Time').values;

            %mechanism for recording a call sequence
            calls = {};
            function r = recorder(s, value)
                if ~exist('value', 'var')
                    value = [];
                end
                function result = onCall(varargin)
                    calls{end+1} = s;
                    if isa(value, 'function_handle')
                        value(varargin{:}); %#ok<NOEFF>
                        result = [];
                    else
                        result = value;
                    end
                end
                r = @onCall;
            end

            %mechanism for using substrates
            function u = user(substrates)
                function use(process)
                    process.substrates = process.substrates - substrates;
                end
                u = @use;
            end

            %metabolite indices of interest (no special significance)
            M1 = 7; M2 = 123; M3 = 432;

            %three fake processes
            sim.setForTest('processes', {
                %simple case: all metabolites in same compartment, all
                %substrates are metabolites
                edu.stanford.covert.test.mock(...
                    'substrates', [0 0]',...
                    'substrateMetaboliteLocalIndexs', [1 2]',...
                    'substrateMetaboliteGlobalIndexs', [M1 M3]',...
                    'substrateMetaboliteCompartmentIndexs', [1 1]',...
                    'substrateMetaboliteGlobalCompartmentIndexs', sub2ind(size(met.counts), [M1 M3]', [1 1]'), ...
                    'calcResourceRequirements_Current', recorder('r1', [10 10]'),...
                    'copyFromState', recorder('f1'),...
                    'copyToState', recorder('t1'),...
                    'evolveState', recorder('e1', user([3 4]')))
                %more complex: metabolites in various compartments, some
                %substrates are not metabolites
                edu.stanford.covert.test.mock(...
                    'substrates', [0 0 0 0 0]',...
                    'substrateMetaboliteLocalIndexs', [1 2 5]',...
                    'substrateMetaboliteGlobalIndexs', [M1 M2 M3]',...
                    'substrateMetaboliteCompartmentIndexs', [3 1 1]',...
                    'substrateMetaboliteGlobalCompartmentIndexs', sub2ind(size(met.counts), [M1 M2 M3]', [3 1 1]'), ...
                    'calcResourceRequirements_Current', recorder('r2', [5 5 0 0 5]'),...
                    'copyFromState', recorder('f2'),...
                    'copyToState', recorder('t2'),...
                    'evolveState', recorder('e2', user([1 0 0 0 -1]')))
                %each metabolite in multiple compartments
                edu.stanford.covert.test.mock(...
                    'substrates', [0 0 0 0; 0 0 0 0]',...
                    'substrateMetaboliteLocalIndexs', [1 3 4]',...
                    'substrateMetaboliteGlobalIndexs', [M2 M3 M1; M2 M3 M1]',...
                    'substrateMetaboliteCompartmentIndexs', [5 4 5; 3 1 3]',...
                    'substrateMetaboliteGlobalCompartmentIndexs', sub2ind(size(met.counts), [M2 M3 M1; M2 M3 M1]', [5 4 5; 3 1 3]'), ...
                    'calcResourceRequirements_Current', recorder('r3', [5 0 5 0; 0 0 5 5]'),...
                    'copyFromState', recorder('f3'),...
                    'copyToState', recorder('t3'),...
                    'evolveState', recorder('e3'))
                });
            sim.setForTest('processEvalOrderIndexs', [3 2 1]');
            sim.setForTest('processesInEvalOrder', sim.processes(sim.processEvalOrderIndexs));
            met.counts(M1,:) = 20;
            met.counts(M2,:) = 0;
            met.counts(M3,:) = 10;

            sim.evolveState();
            assertEqual(t0 + sim.stepSizeSec, sim.state('Time').values);
            assertEqual(...
                'f1 r1 f2 r2 f3 r3 f3 e3 t3 f2 e2 t2 f1 e1 t1',...
                strjoin(' ', calls{:}));

            %processes receive proporational to their allocation
            assertEqual(...
                [17 1],...
                sim.processes{1}.substrates');
            assertEqual(...
                [9 0 0 0 3],...
                sim.processes{2}.substrates');
            assertEqual(...
                [0 0 10 0;
                 0 0 2 10],...
                sim.processes{3}.substrates');

            %verify that metabolite/substrate usage/production propagate back
            assertEqual([17 20 19 20 20 20], met.counts(M1,:));
            assertEqual([ 0  0  0  0  0  0], met.counts(M2,:));
            assertEqual([ 7 10 10 10 10 10], met.counts(M3,:));
        end

        function testRunLogging(this)
            sim = this.simulation;
            sim.applyOptions('lengthSec', 10);
            sim.state('MetabolicReaction').initialGrowthFilterWidth = Inf;

            %1 logger
            logger = edu.stanford.covert.cell.sim.util.SummaryLogger(2, 0);
            sim.run(logger);

            %2 loggers
            logger1 = edu.stanford.covert.cell.sim.util.SummaryLogger(2, 0);
            logger2 = edu.stanford.covert.cell.sim.util.SummaryLogger(2, 0);
            sim.run({logger1 logger2});
        end

        function testMassBalance(this)
            sim = this.simulation;
            sim.applyOptions('lengthSec', 100);
            sim.state('MetabolicReaction').initialGrowthFilterWidth = Inf;

            sim.allocateMemoryForState(1);
            sim.initializeState();
            sim.applyPerturbations();

            mass = sim.state('Mass');
            initialMass = sum(mass.cell);

            sim.run();

            assertElementsAlmostEqual(initialMass, sum(mass.cell));
        end

        function testPlots(this)
            sim = this.simulation;

            %create figure, add axis
            handle = figure();
            axesHandle = subplot(1,1,1,'Parent',handle);
            legend(axesHandle,'off');
            set(axesHandle,'Box','on');

            %inputs
            time = 1;
            compartments = 1;

            %call all plotting functions
            simulationMetaData = metaclass(sim);
            failedPlotMethodNames = {};
            for i = 1:length(simulationMetaData.Methods)
                if length(simulationMetaData.Methods{i}.Name) > 4 && ...
                   strcmp(simulationMetaData.Methods{i}.Access, 'public') && ...
                   strcmp(simulationMetaData.Methods{i}.Name(1:4), 'plot') && ...
                   numel(simulationMetaData.Methods{i}.InputNames) == 4
                    cla(axesHandle);
                    try
                        sim.(simulationMetaData.Methods{i}.Name)(axesHandle, time, compartments)
                    catch %#ok<CTCH>
                        failedPlotMethodNames{end+1}=simulationMetaData.Methods{i}.Name; %#ok<AGROW>
                    end
                end
            end

            %close figure
            close(handle);

            assert(isempty(failedPlotMethodNames), ...
                ['The following plot methods failed: ' strjoin(', ',failedPlotMethodNames{:})]);
        end

        function testOptions(this)
            sim = this.simulation;
            assertEqual(0, sim.getOptions.verbosity);
            assertEqual(1, sim.getOptions.stepSizeSec);

            sim.applyOptions();
            assertEqual(0, sim.getOptions.verbosity);
            assertEqual(1, sim.getOptions.stepSizeSec);

            sim.applyOptions('verbosity', 3, 'stepSizeSec', 0.5);
            assertEqual(3, sim.getOptions.verbosity);
            assertEqual(0.5, sim.getOptions.stepSizeSec);

            sim.applyOptions('verbosity', 4);
            assertEqual(4, sim.getOptions.verbosity);
            assertEqual(0.5, sim.getOptions.stepSizeSec);
        end
    end

    %helpers
    methods (Access = private)
        function sim = newSimulation(~)
            sim = edu.stanford.covert.cell.sim.SimulationFixture.load();
        end

        function prepareOutputDir(this)
            this.outputDir = ['tmp/Simulation_Integrated_Test_' this.MethodName];
            if ~exist(this.outputDir, 'dir')
                mkdir(this.outputDir);
            end
            delete([this.outputDir '/*']);
        end

        function result = createMetadata(this)
            result = struct;
            result.shortDescription = 'Wild-type simulation';
            result.longDescription  = 'Wild-type simulation';
            result.email            = 'jkarr@stanford.edu';
            result.firstName        = 'Jonathan';
            result.lastName         = 'Karr';
            result.affiliation      = 'Covert Lab, Department of Bioengineering, Stanford University';
            result.knowledgeBaseWID = this.simulation.knowledgeBaseWID;
            result.downsampleStep   = 5000;
            result.outputDirectory  = this.outputDir;
            result.startTime        = datestr(clock,'yyyy-mm-dd HH:MM:SS');
            result.endTime          = datestr(clock,'yyyy-mm-dd HH:MM:SS');
            [result.userName, result.hostName, result.ipAddress] = ...
                edu.stanford.covert.util.computerInfo();
            result.revision = 234;
            result.differencesFromRevision = '';
        end
    end

    %static helpers
    methods (Static, Access = private)
        function assertPropertyValuesEqual(...
                metadata, options, parameters, fittedConstants, timeCourses, sim)
            %meta data
            metadataNames = fieldnames(sim.metadata);
            for i = 1:length(metadataNames)
                name = metadataNames{i};
                assertEqual(metadata.(name), sim.metadata.(name), name);
            end

            %options
            optionNames = sim.optionNames;
            for i = 1:length(optionNames)
                name = optionNames{i};
                switch class(options.Core__.(name))
                    case {'cell','struct'}
                        assertEqual(options.Core__.(name), sim.(name));
                    otherwise
                        assertElementsAlmostEqual(...
                            options.Core__.(name), sim.(name),...
                            'relative', 1e-4, name);
                end

            end
            for i = 1:length(sim.processes)
                process = sim.processes{i};
                optionNames = process.optionNames;
                for j = 1:length(optionNames)
                    name = optionNames{j};
                    switch class(options.Core__.(name))
                        case {'cell','struct'}
                            assertEqual(options.(process.wholeCellModelID).(name), process.(name));
                        otherwise
                            assertElementsAlmostEqual(...
                                options.(process.wholeCellModelID).(name),...
                                process.(name),...
                                'relative', 1e-4, name);
                    end
                end
            end

            %parameters
            parameterNames = sim.parameterNames;
            simulationfieldnames = fieldnames(sim);
            for i = 1:length(parameterNames)
                name = parameterNames{i};
                if ismember(name, simulationfieldnames)
                    if isnumeric(parameters.Core__.(name))
                        assertElementsAlmostEqual(...
                            parameters.Core__.(name), sim.(name),...
                            'relative', 1e-4, name);
                    else
                        assertEqual(parameters.Core__.(name), sim.(name), name);
                    end
                end
            end
            for i = 1:length(sim.processes)
                process = sim.processes{i};
                parameterNames = process.parameterNames;
                processFieldnames = fieldnames(process);
                for j = 1:length(parameterNames)
                    name = parameterNames{j};
                    if ismember(name, processFieldnames)
                        if isnumeric(parameters.(process.wholeCellModelID).(name))
                            assertElementsAlmostEqual(...
                                parameters.(process.wholeCellModelID).(name), ...
                                process.(name),...
                                'relative', 1e-4, name);
                        else
                            assertEqual(...
                                parameters.(process.wholeCellModelID).(name), ...
                                process.(name), name);
                        end
                    end
                end
            end

            %fit constants
            fittedConstantNames = sim.fittedConstantNames;
            for i = 1:length(fittedConstantNames)
                name = fittedConstantNames{i};
                assertElementsAlmostEqual(...
                    fittedConstants.Core__.(name), sim.(name),...
                    'relative', 1e-4, name);
            end
            for i = 1:length(sim.processes)
                process = sim.processes{i};
                fittedConstantNames = process.fittedConstantNames;
                for j = 1:length(fittedConstantNames)
                    name = fittedConstantNames{j};
                    assertElementsAlmostEqual(...
                        fittedConstants.(process.wholeCellModelID).(name),...
                        process.(name),...
                        'relative', 1e-4, name);
                end
            end

            %time courses
            timeCourseNames = sim.timeCourseNames;

            for i = 1:length(timeCourseNames)
                name = timeCourseNames{i};
                assertElementsAlmostEqual(...
                    timeCourses.Core__.(name), sim.(name),...
                    'relative', 1e-4, name);
            end

            for i = 1:length(sim.processes)
                process = sim.processes{i};
                timeCourseNames = process.timeCourseNames;
                for j = 1:length(timeCourseNames)
                    name = timeCourseNames{j};
                    if isa(timeCourses.(sim.processWholeCellModelIDs{i}).(name), 'edu.stanford.covert.util.CircularSparseMat')
                        assertTrue(...
                            isalmostequal(timeCourses.Core__.(name), sim.(name)),...
                            name);
                    else
                        assertElementsAlmostEqual(...
                            timeCourses.(process.wholeCellModelID).(name), ...
                            process.(name),...
                            'relative', 1e-4,...
                            name);
                    end
                end
            end
        end
    end

    %test division
    methods
        function testDivideState(~)
            import edu.stanford.covert.cell.sim.constant.Condition;
            import edu.stanford.covert.cell.sim.util.CachedSimulationObjectUtil;
            import edu.stanford.covert.cell.sim.util.DiskLogger;
            import edu.stanford.covert.cell.sim.util.SimulationDiskUtil

            %load simulation
            %sim = CachedSimulationObjectUtil.load();

            %baseOutDir = [SimulationDiskUtil.getBaseDir() filesep '2012_10_24_00_49_53'];
            %simDir = [baseOutDir filesep '2'];
            %md = DiskLogger.loadMetadata(simDir);
            %sim = loadSimulation(simDir, md.lengthSec, md.lengthSec, 1, 'extract');

            tmp = load('src_test/+edu/+stanford/+covert/+cell/+sim/fixtures/Simulation_EndOfCellCycle.mat');
            sim = tmp.simulation;

            %references to constants, states, processes
            c = sim.compartment;
            chr = sim.state('Chromosome');
            met = sim.state('Metabolite');
            r = sim.state('Rna');
            pm = sim.state('ProteinMonomer');
            pc = sim.state('ProteinComplex');
            trl = sim.process('Translation');

            %divide cell into 2 daughters
            daughters = sim.divideState();
            daughter1 = daughters{1};
            daughter2 = daughters{2};

            %test options, parameters copied correctly
            assertEqual(sim.getOptions(), daughter1.getOptions());
            assertEqual(sim.getParameters(), daughter1.getParameters());

            %% test
            % mass
            assertElementsAlmostEqual(sim.state('Mass').cell, ...
                + daughter1.state('Mass').cell ...
                + daughter2.state('Mass').cell, 'relative', 1e-100);

            %bound proteins
            d1_chr = daughter1.state('Chromosome');
            d2_chr = daughter2.state('Chromosome');
            d1_pm = daughter1.state('ProteinMonomer');
            d2_pm = daughter2.state('ProteinMonomer');
            d1_pc = daughter1.state('ProteinComplex');
            d2_pc = daughter2.state('ProteinComplex');

            [~, vals] = find(chr.monomerBoundSites);
            [~, vals1] = find(d1_chr.monomerBoundSites);
            [~, vals2] = find(d2_chr.monomerBoundSites);
            cnts = histc(vals, (1:numel(pm.boundIndexs)));
            cnts1 = histc(vals1, (1:numel(pm.boundIndexs)));
            cnts2 = histc(vals2, (1:numel(pm.boundIndexs)));
            cnts = cnts(:);
            cnts1 = cnts1(:);
            cnts2 = cnts2(:);
            assertEqual(cnts, cnts1 + cnts2);
            trlFactorIdxs = setdiff(pm.getIndexs(trl.enzymeWholeCellModelIDs(trl.enzymeIndexs_elongationFactors)), 0);
            idxs = setdiff((1:numel(pm.boundIndexs))', trlFactorIdxs);
            assertEqual(cnts(idxs), pm.counts(pm.boundIndexs(idxs), c.cytosolIndexs));

            [~, vals] = find(chr.complexBoundSites);
            [~, vals1] = find(d1_chr.complexBoundSites);
            [~, vals2] = find(d2_chr.complexBoundSites);
            cnts = histc(vals, (1:numel(pc.boundIndexs)));
            cnts1 = histc(vals1, (1:numel(pc.boundIndexs)));
            cnts2 = histc(vals2, (1:numel(pc.boundIndexs)));
            cnts = cnts(:);
            cnts1 = cnts1(:);
            cnts2 = cnts2(:);
            assertEqual(cnts, cnts1 + cnts2);
            trlFactorIdxs = setdiff(pc.getIndexs(trl.enzymeWholeCellModelIDs(trl.enzymeIndexs_elongationFactors)), 0);
            idxs = setdiff((1:numel(pc.boundIndexs))', [
                trlFactorIdxs
                pc.getIndexs({'MG_224_9MER_GTP'; 'MG_224_9MER_GDP'})
                pc.ribosome70SIndexs
                ]);
            assertEqual(cnts(idxs), pc.counts(pc.boundIndexs(idxs), c.cytosolIndexs));

            %total metabolites, RNA, protein except, FtsZ
            d1_met = daughter1.state('Metabolite');
            d2_met = daughter2.state('Metabolite');
            d1_r = daughter1.state('Rna');
            d2_r = daughter2.state('Rna');

            assertEqual(met.counts(:, setdiff(1:end, c.extracellularIndexs)), ...
                + d1_met.counts(:, setdiff(1:end, c.extracellularIndexs)) ...
                + d2_met.counts(:, setdiff(1:end, c.extracellularIndexs)));

            mediaIdxs = met.setCounts(:, Condition.objectIndexs);
            nonMediaIdxs = setdiff((1:numel(met.wholeCellModelIDs))', mediaIdxs);
            assertEqual(met.counts(nonMediaIdxs, c.extracellularIndexs), ...
                + d1_met.counts(nonMediaIdxs, c.extracellularIndexs) ...
                + d2_met.counts(nonMediaIdxs, c.extracellularIndexs));
            assertEqual(...
                d1_met.counts(mediaIdxs, c.extracellularIndexs), ...
                d2_met.counts(mediaIdxs, c.extracellularIndexs));

            assertEqual(r.counts, ...
                + d1_r.counts ...
                + d2_r.counts);
            assertEqual(pm.counts, ...
                + d1_pm.counts ...
                + d2_pm.counts);

            tmp = pc.getIndexs({'MG_224_9MER_GTP'; 'MG_224_9MER_GDP'});
            ftsZIdxs = [pc.matureIndexs(tmp) pc.boundIndexs(tmp)];
            idxs = setdiff(1:numel(pc.wholeCellModelIDs), ftsZIdxs(:));
            assertEqual(pc.counts(idxs, :), ...
                + d1_pc.counts(idxs, :) ...
                + d2_pc.counts(idxs, :));
            assertEqual(sum(pc.counts(ftsZIdxs(1, :), :), 1), ...
                + sum(d1_pc.counts(ftsZIdxs(1, :), :), 1) ...
                + sum(d2_pc.counts(ftsZIdxs(1, :), :), 1));
            assertEqual(sum(pc.counts(ftsZIdxs(2, :), :), 1), ...
                + sum(d1_pc.counts(ftsZIdxs(2, :), :), 1) ...
                + sum(d2_pc.counts(ftsZIdxs(2, :), :), 1));
            assertAllEqual(0, d1_pc.counts(ftsZIdxs(:, 2), :));
            assertAllEqual(0, d2_pc.counts(ftsZIdxs(:, 2), :));

            %metabolite, RNA, protein counts non-negative
            validateattributes(daughter1.state('Metabolite').counts, {'numeric'}, {'nonnegative'});
            validateattributes(daughter2.state('Metabolite').counts, {'numeric'}, {'nonnegative'});
            validateattributes(d1_r.counts, {'numeric'}, {'nonnegative'});
            validateattributes(d2_r.counts, {'numeric'}, {'nonnegative'});
            validateattributes(d1_pm.counts, {'numeric'}, {'nonnegative'});
            validateattributes(d2_pm.counts, {'numeric'}, {'nonnegative'});
            validateattributes(d1_pc.counts, {'numeric'}, {'nonnegative'});
            validateattributes(d2_pc.counts, {'numeric'}, {'nonnegative'});

            %total transcripts, RNA polymerase
            rnaPol = sim.state('RNAPolymerase');
            d1_rnaPol = daughter1.state('RNAPolymerase');
            d2_rnaPol = daughter2.state('RNAPolymerase');
            transcript = sim.state('Transcript');
            d1_transcript = daughter1.state('Transcript');
            d2_transcript = daughter2.state('Transcript');

            tmp1 = [rnaPol.states rnaPol.positionStrands transcript.boundTranscriptionUnits transcript.boundTranscriptProgress transcript.boundTranscriptChromosome];
            tmp2 = [
                d1_rnaPol.states d1_rnaPol.positionStrands(:, 1) d1_rnaPol.positionStrands(:, 2)                                                 d1_transcript.boundTranscriptionUnits d1_transcript.boundTranscriptProgress d1_transcript.boundTranscriptChromosome
                d2_rnaPol.states d2_rnaPol.positionStrands(:, 1) d2_rnaPol.positionStrands(:, 2)+2*(d2_rnaPol.states ~= rnaPol.freeValue) d2_transcript.boundTranscriptionUnits d2_transcript.boundTranscriptProgress 2*d2_transcript.boundTranscriptChromosome
                ];
            tmp1 = tmp1(tmp1(:, 1) ~= rnaPol.notExistValue, :);
            tmp2 = tmp2(tmp2(:, 1) ~= rnaPol.notExistValue, :);
            tmp1 = sortrows(tmp1, 1:6);
            tmp2 = sortrows(tmp2, 1:6);
            assertEqual(tmp1, tmp2);

            for i = 1:numel(daughters)
                d_pc = daughters{i}.state('ProteinComplex');
                d_rnaPol = daughters{i}.state('RNAPolymerase');
                d_transcript = daughters{i}.state('Transcript');

                assertEqual(...
                    sum(d_pc.counts(pc.boundIndexs(pc.rnaPolymeraseIndexs), c.cytosolIndexs)), ...
                    d_rnaPol.nActive + d_rnaPol.nNonSpecificallyBound + d_rnaPol.nSpecificallyBound);
                assertEqual(...
                    d_pc.counts(pc.boundIndexs(pc.rnaPolymeraseIndexs(2), c.cytosolIndexs)), ...
                    sum(d_rnaPol.states == rnaPol.activelyTranscribingValue) + d_rnaPol.nSpecificallyBound);
                assertEqual(...
                    d_pc.counts(pc.boundIndexs(pc.rnaPolymeraseIndexs(1), c.cytosolIndexs)), ...
                    sum(d_rnaPol.states > rnaPol.activelyTranscribingValue) + d_rnaPol.nNonSpecificallyBound);

                assertEqual(...
                    sum(d_pc.counts(pc.matureIndexs(pc.rnaPolymeraseIndexs), c.cytosolIndexs)), ...
                    d_rnaPol.nFree);

                assertEqual(double(d_rnaPol.states >= rnaPol.activelyTranscribingValue | d_rnaPol.states == rnaPol.specificallyBoundValue)', ...
                    d_transcript.boundTranscriptChromosome');
            end

            %total polypeptides, ribosomes
            rib = sim.state('Ribosome');
            d1_rib = daughter1.state('Ribosome');
            d2_rib = daughter2.state('Ribosome');

            tmp1 = [rib.states rib.boundMRNAs rib.mRNAPositions rib.tmRNAPositions];
            tmp2 = [
                d1_rib.states d1_rib.boundMRNAs d1_rib.mRNAPositions d1_rib.tmRNAPositions
                d2_rib.states d2_rib.boundMRNAs d2_rib.mRNAPositions d2_rib.tmRNAPositions
                ];
            tmp1 = tmp1(tmp1(:, 1) ~= rib.notExistValue, :);
            tmp2 = tmp2(tmp2(:, 1) ~= rib.notExistValue, :);
            tmp1 = sortrows(tmp1, 1:4);
            tmp2 = sortrows(tmp2, 1:4);
            assertEqual(tmp1, tmp2)

            assertEqual(d1_pc.counts(pc.boundIndexs(pc.ribosome70SIndexs), c.cytosolIndexs), d1_rib.nActive + d1_rib.nStalled);
            assertEqual(d2_pc.counts(pc.boundIndexs(pc.ribosome70SIndexs), c.cytosolIndexs), d2_rib.nActive + d2_rib.nStalled);

            assertEqual(rib.nStalled, r.counts(r.boundIndexs(trl.tmRNAGlobalIndex), c.cytosolIndexs));
            assertEqual(d1_rib.nStalled, d1_r.counts(r.boundIndexs(trl.tmRNAGlobalIndex), c.cytosolIndexs));
            assertEqual(d2_rib.nStalled, d2_r.counts(r.boundIndexs(trl.tmRNAGlobalIndex), c.cytosolIndexs));

            %chromosome
            for i = 1:numel(chr.stateNames)
                sName = chr.stateNames{i};
                if isequal(sName, 'segregated')
                    continue;
                end
                assertEqual(chr.(sName), ...
                    [daughter1.state('Chromosome').(sName)(:, [1 2]) ...
                    daughter2.state('Chromosome').(sName)(:, [1 2])]);
            end
            assertEqual(false, daughter1.state('Chromosome').segregated)
            assertEqual(false, daughter2.state('Chromosome').segregated)

            %stimulus
            assertEqual(sim.state('Stimulus').values, daughter1.state('Stimulus').values)
            assertEqual(sim.state('Stimulus').values, daughter2.state('Stimulus').values)

            %geometry
            assertElementsAlmostEqual(sim.state('Geometry').volume, ...
                + daughter1.state('Geometry').volume ...
                + daughter2.state('Geometry').volume, ...
                'relative', 1e-24);

            %FtsZ ring
            assertEqual(0, daughter1.state('FtsZRing').numEdgesOneStraight);
            assertEqual(0, daughter1.state('FtsZRing').numEdgesTwoStraight);
            assertEqual(0, daughter1.state('FtsZRing').numEdgesTwoBent);
            assertEqual(0, daughter1.state('FtsZRing').numResidualBent);

            assertEqual(0, daughter2.state('FtsZRing').numEdgesOneStraight);
            assertEqual(0, daughter2.state('FtsZRing').numEdgesTwoStraight);
            assertEqual(0, daughter2.state('FtsZRing').numEdgesTwoBent);
            assertEqual(0, daughter2.state('FtsZRing').numResidualBent);

            %host
            sNames = sim.state('Host').stateNames;
            for i = 1:numel(sNames)
                assertEqual(sim.state('Host').(sNames{i}), daughter1.state('Host').(sNames{i}));
            end

            %time
            assertEqual(0, daughter1.state('Time').values)
            assertEqual(0, daughter2.state('Time').values)
        end

        function testInitializeFromDaughter(~)
            import edu.stanford.covert.cell.sim.util.CachedSimulationObjectUtil;

            %sim = CachedSimulationObjectUtil.load();
            tmp = load('src_test/+edu/+stanford/+covert/+cell/+sim/fixtures/Simulation_EndOfCellCycle.mat');
            sim = tmp.simulation;

            %divide cell
            [~, state_daughters] = sim.divideState();

            %setup daughter cell simulation
            tmpDirName = 'output/runMediumTests/initializeFromDaughter';
            if exist(tmpDirName, 'dir')
                rmdir(tmpDirName, 's')
            end

            mkdir(tmpDirName)

            state_daughter1 = state_daughters(1);
            save([tmpDirName filesep 'initialConditions.mat'], '-struct', 'state_daughter1');
            copyfile('src_test/+edu/+stanford/+covert/+cell/+sim/fixtures/initializeFromDaughter.xml', ...
                [tmpDirName filesep 'conditions.xml']);

            %run simulation
            daughter = runSimulation('outDir', tmpDirName, 'logToDisk', true);

            %test options, parameters copied correctly
            sim.setForTest('lengthSec', 100);
            sim.setForTest('seed', daughter.seed);
            sim.setForTest('media', reshape(sim.media, [], 6));
            sim.setForTest('stimulus', reshape(sim.stimulus, [], 6));
            sim.setForTest('geneticKnockouts', reshape(sim.geneticKnockouts, [], 1));

            for i = 1:numel(sim.states)
                s = sim.states{i};
                s.seed = daughter.states{i}.seed;
            end
            for i = 1:numel(sim.processes)
                p = sim.processes{i};
                p.seed = daughter.processes{i}.seed;
            end

            assertEqual(sim.getOptions(), daughter.getOptions());
            assertEqual(sim.getParameters(), daughter.getParameters());

            %test state copied correctly
            tmp = load([tmpDirName filesep 'state-0.mat']);
            assertEqual(state_daughter1, tmp)

            %clean up
            rmdir(tmpDirName, 's')
        end
    end
end


%FONT_SIZE Set large graphic font
%
%       font_size(size)
%
% Set font size for current figure

function font_size(size)

  V = axis;
  H = get(gcf,'Children');
	c1 = [];
	for h = H'
	if strcmp(get(h,'type'),'axes')
  	set(get(h,'XLabel'), 'FontSize', size);
  	set(get(h,'YLabel'), 'FontSize', size);
  	set(get(h,'Title'),  'FontSize', size);
  	set(h, 'FontSize', size);
  	c1 = [c1; get(gca, 'Children')];
	end
	end
 	axis(V);
  for h1 = c1'
    v1 = get (h1);
    if (isfield (v1, 'FontSize'))
      set (h1, 'FontSize', size);
    end;
    c2 = get (h1, 'Children');
    for h2 = c2'
      v2 = get (h2);
      if (isfield (v2, 'FontSize'))
        set (h2, 'FontSize', size);
      end;
    end;
  end;

return


%%
% Compile all HTML files.

a = dir('test_*.m');
opts.outputDir = 'html';

for i=1:length(a)
    name = a(i).name(1:end-2);
	publish(name,opts);
end


function VAR = RenameClusGroup(VAR,i_fish,i_ClusGroup,name)
VAR(i_fish).ClusGroupName{i_ClusGroup} = name;
end


disp('Hello world!')

name = input('whats your name? ','s');

disp(['hello ',name])


function out = saveobj(obj)
%SAVEOBJ (overloaded)

% We have to save the persistent variables in the SDPVAR class
obj.savedata.internalsdpvarstate = yalmip('getinternalsdpvarstate');
obj.savedata.version = yalmip('version');
out = obj;


function printHyperlink( URL, OptionalText )
% Prints a hyperlink to the command window
%
% Syntax:	PRINTHYPERLINK( URL, OPTIONALTEXT)
%
% Inputs:
% 	URL - Address for the hyperlink
% 	OptionalText - The text to be printed which is hyperlinked
%
% See also: fprintf, cprintf

% Author: Jacob Donley
% University of Wollongong
% Email: jrd089@uowmail.edu.au
% Copyright: Jacob Donley 2017
% Date: 16 February 2017
% Revision: 0.2 (30 March 2017)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin < 2
    OptionalText = URL;
end
fprintf(['' OptionalText '\n']);
if exist('cprintf','file')
    cprintf('hyper', '');
end

end


function plotregionData(varargin)
%PLOTREGIONDATA   SINGFUN does not support PLOTREGIONDATA.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

error('CHEBFUN:SINGFUN:plotregionData:notSupported', ['SINGFUN does not' ...
    'support PLOTREGIONDATA']);

end


function [point, ind] = util_get_annopoint_by_id(points, id)
point = [];
for i=1:length(points)
    if (points(i).id == id)
        point = points(i);
        ind = i;
        return;
    end
end
end


function host = gethostname()

% HOSTNAME returns the hostname of this computer
%
% Use as
%   str = hostname;
%
% See also GETUSERNAME, GETADDRESS

% Copyright (C) 2011, Eelke Spaak
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% this is to speed up subsequent calls
persistent previous_argout
if ~isempty(previous_argout)
  host = previous_argout;
  return
end

if (ispc())
  host = getenv('ComputerName');
elseif (isunix())
  host = getenv('HOSTNAME');
  % the HOSTNAME variable is not guaranteed to be set
  if isempty(host)
    [status, host] = system('hostname -s');
    % remove the ^n from the end of the line
    host = deblank(host);
  end
end

host = strtok(host, '.'); % dots in filenames are not allowed by matlab

if (isempty(host))
  host = 'unknownhost';
end

% remember for subsequent calls
previous_argout = host;


function varargout = infoto(varargin)
% INFOTO M-file for infoto.fig
%      INFOTO, by itself, creates a new INFOTO or raises the existing
%      singleton*.
%
%      H = INFOTO returns the handle to a new INFOTO or the handle to
%      the existing singleton*.
%
%      INFOTO('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in INFOTO.M with the given input arguments.
%
%      INFOTO('Property','Value',...) creates a new INFOTO or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before infoto_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to infoto_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help infoto

% Last Modified by GUIDE v2.5 09-Jul-2012 15:08:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @infoto_OpeningFcn, ...
                   'gui_OutputFcn',  @infoto_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before infoto is made visible.
function infoto_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to infoto (see VARARGIN)

% Choose default command line output for infoto
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes infoto wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = infoto_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to axes1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes1
axes (hObject)
imshow('infoto.jpg')


function bvr_sendcommand(fcn, varargin)
%BVR_SENDCOMMAND - Control the BrainVision Recorder software
%
%Synopsis:
% bvr_sendcommand(FCN, <ARGS>)
%
%Arguements:
% FCN: Name of the function to be executed. See in the bvr_*.vbs files in
%     acquistion_tools folder for a list of options. Here are some:
%     'loadworkspace' - load BV workspace into the recorder; ARG: name of
%        the workspace (extension '.rwsp' may be left out)
%     'startrecording' - Start EEG recording; ARG: name of the file with
%        full path, without extension.
%     'startimprecording' - Make Impedance measurement first and start
%        recording afterward (impedance values are saved into the EEG
%        file); ARG as above.
%     'stoprecording' - Stops the recording.
%     'viewsignals' - Switch to monitoring state
%     'viewsignalsandwait' - Switch to monitoring mode and wait (unless monitoring
%        mode is already active). Example: bvr_sendcommand('viewsignalsandwait','3000');

mypath= fileparts(which(mfilename));
vbs_function= fullfile(mypath, ['bvr_' fcn '.vbs']);

system(['"' vbs_function '"' sprintf(' %s',varargin{:})]);


classdef HBox < uix.HBox
    %uiextras.HBox  Arrange elements in a single horizontal row
    %
    %   obj = uiextras.HBox() creates a new horizontal box layout with
    %   all parameters set to defaults. The output is a new layout object
    %   that can be used as the parent for other user-interface components.
    %
    %   obj = uiextras.HBox(param,value,...) also sets one or more
    %   parameter values.
    %
    %   See the documentation for more detail and the list of properties.
    %
    %   Examples:
    %   >> f = figure();
    %   >> b = uiextras.HBox( 'Parent', f );
    %   >> uicontrol( 'Parent', b, 'Background', 'r' )
    %   >> uicontrol( 'Parent', b, 'Background', 'b' )
    %   >> uicontrol( 'Parent', b, 'Background', 'g' )
    %   >> set( b, 'Sizes', [-1 100 -2], 'Spacing', 5 );
    %
    %   >> f = figure();
    %   >> b1 = uiextras.VBox( 'Parent', f );
    %   >> b2 = uiextras.HBox( 'Parent', b1, 'Padding', 5, 'Spacing', 5 );
    %   >> uicontrol( 'Style', 'frame', 'Parent', b1, 'Background', 'r' )
    %   >> uicontrol( 'Parent', b2, 'String', 'Button1' )
    %   >> uicontrol( 'Parent', b2, 'String', 'Button2' )
    %   >> set( b1, 'Sizes', [30 -1] );
    %
    %   See also: uiextras.VBox
    %             uiextras.HBoxFlex
    %             uiextras.Grid

    %  Copyright 2009-2014 The MathWorks, Inc.
    %  $Revision: 1077 $ $Date: 2015-03-19 16:44:14 +0000 (Thu, 19 Mar 2015) $

    properties( Hidden, Access = public, Dependent )
        Enable % deprecated
        Sizes
        MinimumSizes
    end

    methods

        function obj = HBox( varargin )

            % Call uix constructor
            obj@uix.HBox( varargin{:} )

            % Auto-parent
            if ~ismember( 'Parent', varargin(1:2:end) )
                obj.Parent = gcf();
            end

        end % constructor

    end % structors

    methods

        function value = get.Enable( ~ )

            % Warn
            % warning( 'uiextras:Deprecated', ...
            %     'Property ''Enable'' will be removed in a future release.' )

            % Return
            value = 'on';

        end % get.Enable

        function set.Enable( ~, value )

            % Check
            assert( ischar( value ) && any( strcmp( value, {'on','off'} ) ), ...
                'uiextras:InvalidPropertyValue', ...
                'Property ''Enable'' must be ''on'' or ''off''.' )

            % Warn
            % warning( 'uiextras:Deprecated', ...
            %     'Property ''Enable'' will be removed in a future release.' )

        end % set.Enable

        function value = get.Sizes( obj )

            % Get
            value = transpose( obj.Widths );

        end % get.Sizes

        function set.Sizes( obj, value )

            % Set
            obj.Widths = value;

        end % set.Sizes

        function value = get.MinimumSizes( obj )

            % Get
            value = transpose( obj.MinimumWidths );

        end % get.MinimumSizes

        function set.MinimumSizes( obj, value )

            % Get
            obj.MinimumWidths = value;

        end % set.MinimumSizes

    end % accessors

end % classdef


function varargout = cfg_get_defaults(defstr, varargin)

% function varargout = cfg_get_defaults(defspec, varargin)
% Get/set defaults for various properties of matlabbatch utilities.
% The values can be modified permanently by editing the file
% private/cfg_mlbatch_defaults.m
% or for the current MATLAB session by calling
% cfg_get_defaults(defspec, defval).
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg_get_defaults.m 1862 2008-06-30 14:12:49Z volkmar $

rev = '$Rev: 1862 $'; %#ok

persistent local_def;
if isempty(local_def)
   local_def = cfg_mlbatch_defaults;
end;

% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');

if nargin == 1
    try
        varargout{1} = subsref(local_def, subs);
    catch
        varargout{1} = [];
    end
else
    local_def = subsasgn(local_def, subs, varargin{1});
end;


function taxonomy = parseNCBItaxonomy(NCBI)
% Grabs taxonomic lineage from NCBI using the NCBI ID
%
% INPUT
% NCBI          NCBI ID (e.g., 511145)
%
% OUTPUT
% taxonomy      structure containing the taxonomic lineage
%
% Stefania Magnusdottir, Nov 2017

if iscell(NCBI)
    NCBI = NCBI{1};
end
if isnumeric(NCBI)
    NCBI = num2str(NCBI);
end

hmtlString = urlread(['https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=', NCBI]);
lineage = {
    'superkingdom'
    'phylum'
    'class'
    'order'
    'family'
    'genus'
    'species'};

% extract information from html string and fill in data (different parsing
% types)

% type 1
taxonomy = struct();
for i = 1:length(lineage)
    n = regexp(hmtlString, ['ALT="', lineage{i}, '">([^<]+)'], 'tokens');
    if ~isempty(n)
        n = [n{:}];
        if ~isempty(n{1, 1})
            taxonomy.(lineage{i}) = n{1, 1};
        else
            taxonomy.(lineage{i}) = '';
        end
    end
end

% type 2
taxFields = fieldnames(taxonomy);
if isempty(taxFields)
    taxonomy = struct();
    for i = 1:length(lineage)
        n = regexp(hmtlString, ['TITLE="', lineage{i}, '">([^<]+)'], 'tokens');
        if ~isempty(n)
            n = [n{:}];
            if ~isempty(n{1, 1})
                taxonomy.(lineage{i}) = n{1, 1};
            else
                taxonomy.(lineage{i}) = '';
            end
        end
    end
end

% extract strain from title
n = regexp(hmtlString, '<TITLE>Taxonomy browser (([^)]+)', 'tokens');
if isempty(n)  % try other type
    n = regexp(hmtlString, '<title>Taxonomy browser (([^)]+)', 'tokens');
end
if ~isempty(n)
    n = [n{:}];
    if ~isempty(n{1, 1})
        taxonomy.strain = n{1, 1};
    else
        taxonomy.strain = '';
    end
end


function [str, tag, cind] = gencode(item, tag, tagctx)

% function [str, tag, cind] = gencode(item, tag, tagctx)
% Generate code to recreate a cfg_item object. This function calls the
% cfg_item specific gencode_item method. Instead of creating one large,
% deeply nested struct/cell array, it creates separate variables for each
% cfg_item.
%
% Input arguments:
% item - MATLAB variable to generate code for (the variable itself, not its
%        name)
% tag     - optional: name of the variable, i.e. what will be displayed left
%           of the '=' sign. This can also be a valid struct/cell array
%           reference, like 'x(2).y'. If not provided, inputname(1) will be
%           used.
% tagctx  - optional: variable names not to be used (e.g. keywords,
%           reserved variables). A cell array of strings.
%
% Output arguments:
% str  - cellstr containing code lines to reproduce
% tag  - name of the generated variable
% cind - index into str to the line where the variable assignment is coded
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: gencode.m 3355 2009-09-04 09:37:35Z volkmar $

rev = '$Rev: 3355 $'; %#ok

if nargin < 2
    tag = inputname(1);
end;
if nargin < 3
    tagctx = {};
end
stoptag = tag;
tropts = cfg_tropts({{}},1,inf,1,inf,true);
[str, tag, cind] = gencode_item(item, tag, tagctx, stoptag, tropts);


curdir = fileparts(mfilename('fullpath'));
addpath(fullfile(curdir, 'selective_search'));
if exist(fullfile(curdir,'selective_search/SelectiveSearchCodeIJCV'), 'dir')
  addpath(fullfile(curdir,'selective_search/SelectiveSearchCodeIJCV'));
  addpath(fullfile(curdir,'selective_search/SelectiveSearchCodeIJCV/Dependencies'));
else
  fprintf('Warning: you will need the selective search IJCV code.\n');
  fprintf('Press any key to download it (runs ./selective_search/fetch_selective_search.sh)> ');
  pause;
  if ispc
      fetch_selective_search();
  else
      system('./selective_search/fetch_selective_search.sh');
  end
  addpath(fullfile(curdir,'selective_search/SelectiveSearchCodeIJCV'));
  addpath(fullfile(curdir,'selective_search/SelectiveSearchCodeIJCV/Dependencies'));
end
addpath(fullfile(curdir,'vis'));
addpath(genpath(fullfile(curdir,'utils')));
addpath(fullfile(curdir,'bin'));
addpath(fullfile(curdir,'nms'));
addpath(fullfile(curdir,'finetuning'));
addpath(fullfile(curdir,'bbox_regression'));
if exist(fullfile(curdir,'external/caffe/matlab/caffe'), 'dir')
  addpath(fullfile(curdir,'external/caffe/matlab/caffe'));
else
  warning('Please install Caffe in ./external/caffe');
end
addpath(fullfile(curdir,'experiments'));
addpath(fullfile(curdir,'imdb'));

mkdir_if_missing(fullfile(curdir, 'bin'));
mkdir_if_missing(fullfile(curdir, 'cachedir'));
mkdir_if_missing(fullfile(curdir, 'feat_cache'));
mkdir_if_missing(fullfile(curdir, 'imdb', 'cache'));

if ~ispc
    hfile = [matlabroot '/extern/include/matrix.h'];
    loadlibrary('libmx',hfile)
end

fprintf('SPP_net startup done\n');


%% Slip Systems
%
%%
%


%MRDIVIDE Mapping overload


function editCobraToolboxPath(basePath,folderPattern,method)
%recursively finds all the folders within a given basePath that contains a
%given folderPattern and either adds or removes that folder from the matlab
%path

if ~exist('basePath','var') || isempty(basePath)
    aPath = which('initVonBertalanffy');
    basePath = strrep(aPath,'vonBertalanffy/initVonBertalanffy.m','');
end
if ~exist('folderPattern','var') || isempty(folderPattern)
    folderPattern=[filesep 'new'];
end
if ~exist('method','var') || isempty(method)
    method = 'remove';
end

folderlist = dir(fullfile(basePath, ['**' filesep '*.*']));  %get list of files and folders in any subfolder
folderlist = folderlist([folderlist.isdir]);  %remove files from list

folderlistOnly=cell(length(folderlist),1);
for i=1:length(folderlist)
    folderlistOnly{i,1} = folderlist(i).folder;
end
folderlistOnly = unique(folderlistOnly);

for i=1:length(folderlistOnly)
    if contains(folderlistOnly{i,1},folderPattern)
        switch method
            case 'add'
                disp(['adding: ' folderlistOnly{i,1}])
                addpath(folderlistOnly{i,1})
            case 'remove'
                disp(['removing: ' folderlistOnly{i,1}])
                rmpath(folderlistOnly{i,1})
            otherwise
                error([method ' is not a recognised method'])
        end
    end
end


%PDF2EPS  Convert a pdf file to eps format using pdftops
%
% Examples:
%   pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
%   source - filename of the source pdf file to convert. The filename is
%            assumed to already have the extension ".pdf".
%   dest - filename of the destination eps file. The filename is assumed to
%          already have the extension ".eps".

% Copyright (C) Oliver Woodford 2009-2010

% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.

function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status message] = pdftops(options);
% Check for error
if status
    % Report error
    if isempty(message)
        error('Unable to generate eps. Check destination directory is writable.');
    else
        error(message);
    end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
    % Cannot open the file
    return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
    fseek(fid, -numel(str)-1, 'cof');
    fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
return


function env  = mrvGetEvironment()
% function env  = mrvGetEvironment()
%
% Copyright Stanford team, mrVista, 2011
%
% FP, 6/30/2011
%
% See also mrvValidate.m and mrvValidateAll.m

% save the matlab version being used
env.matlabVer = ver;

% save the architecture
env.computer = computer;

% vistasoft revision number
env.vistaDir = mrvRootPath;
tmp = gitInfo(vistaRootPath);
env.gitOrigin = tmp.origin;
env.gitchecksum = tmp.checksum;

return


function result = wildcardsearch(rootdir, searchstr, casesensitive, strict)
% WILDCARDSEARCH Searches the file system for files matching a wildcard
% pattern.
%    WILDCARDSEARCH(ROOTDIR, SEARCHSTRING) Searches the file system from
%    the starting directory ROOTDIR for files and folders matching the
%    pattern SEARCHSTRING. The function WILDCARDSEARCH is similar to the
%    search file option in Explorer.
%
%    WILDCARDSEARCH(ROOTDIR, SEARCHSTRING, CASESENSITIVE) The extra boolean
%    CASESENSITIVE allows for case senstive searching of files and folders.
%
%    WILDCARDSEARCH(ROOTDIR, SEARCHSTRING, CASESENSITIVE, STRICT) The extra
%    boolean STRICT allows for only precise matches to be returned. The
%    default behaviour is loose.
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = '*.jpg;*.tif';
%     files = wildcardsearch(rootdir, searchstr);
%
%    This wil return all JPG and TIF files on the C:\ drive and maybe some
%    folders or files also matching this pattern e.g. 'somefile.jpg.old'
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = 'MatLab';
%     files = wildcardsearch(rootdir, searchstr, true);
%
%    This wil return only return files or folders matching the pattern
%    'MatLab'. This could also match a file named 'MatLabRC'.
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = '*\matlab';
%     files = wildcardsearch(rootdir, searchstr, true, true);
%
%    This wil return only return files named exactly 'matlab'.
%
%    Example:
%     rootdir = 'C:\'
%     searchstr = '*\';
%     files = wildcardsearch(rootdir, searchstr, true, true);
%
%    To find only folders do a strict search and end your search string
%    with the file separator (\ on Windows, / on UNIX). The above example
%    will return a complete directory tree of the C-drive.
%
%    Have a look at the source code for more information. For more
%    info on this function and how to use it, bug reports, feature
%    requests, etc. feel free to contact the author.
%
%    See also REGEXPDIR

%==========================================================================
% B.C. Hamans (b.c.hamans@rad.umcn.nl)                                 2007
%==========================================================================

% Check input
error(nargchk(2, 4, nargin));

% Create the regular expression
beginstr='('; endstr=')';
if ~exist('strict','var'); strict = false; end
if strict; beginstr=['^' beginstr]; endstr=[endstr '$']; end
if ~exist('casesensitive','var'); casesensitive = false; end
if casesensitive; beginstr = ['(?-i)' beginstr]; end
regexpstr=[beginstr strrep(regexptranslate('wildcard', searchstr), pathsep, [endstr '|' beginstr]) endstr];

% Search
result = regexpdir(rootdir, regexpstr, true);

%==========================================================================
% Changelog:
% 03-09-2007 v1.00 (BCH)  Initial release
%==========================================================================


function maxFig(varargin)

%% Parse input

switch nargin
    case 0
        hf=gcf;
    case 1
        hf=varargin{1};
end

if isempty(hf)
    hf=gcf; %Take the current figure window handle if the handle is empty
end

%% Turn off warning (JavaFrame will become obsolete, this will lead to error in the future)
% warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
%
% %% Maximize using JaveFrame
% try
%     pause(0.01);
%     jFrame=get(hf,'JavaFrame');
% %     set(jFrame,'Maximized',1);
%     jFrame.setMaximized(1);
% catch exception
%     rethrow(exception)
% end

%%

jFrame=get(hf,'JavaFrame');
drawnow;  %Next line throws error without pause or drawnow here
jFrame.fHG2Client.setMaximized(true);

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


function apply_recursivly(in_dir,cmd,pattern)
% apply cmd recursively to all file in a directory
%
%% Input
%
%% Output

sub_dirs = getSubDirs(in_dir);

for id = 1:length(sub_dirs)

  %disp(sub_dirs{id});
  files = dir(fullfile(sub_dirs{id},pattern));

  for i = 1:length(files)
    cmd(fullfile(sub_dirs{id},files(i).name));
  end

end


function sessionGUI_close;
% Close a Session GUI, clearing the relevant global variables along the
% way.
%
% sessionGUI_close;
%
% ras, 07/06
mrGlobals2;

% close any subsidiary viewers
for v = GUI.viewers
    mrViewClose(v);
end

% close the main figure
delete(GUI.fig);

INPLANE{1} = [];
VOLUME{1} = [];
if isempty(cellfind(INPLANE)), INPLANE = {}; end
if isempty(cellfind(VOLUME)), VOLUME = {}; end

% Check if there are no more open views: if not, clean the workspace
if isempty(cellfind(INPLANE)) & isempty(cellfind(VOLUME))
    mrvCleanWorkspace;
end

clear global GUI;

return


% set default value for a field if not set yet.
function value = ReturnFieldWithDefaultValue(para, fieldName, defaultValue)
    if ~isfield(para, fieldName)
        value = defaultValue;
    else
        value = para.(fieldName);
    end
end


%% Twinning Tutorial
%
%%
%
%% Open in Editor
%
%% Contents
%


function [a] = save_warper(string, proposal,mask)
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here

 a=0;
 save(string,'proposal','mask');
end


%--------------------------------------------------------------------------
% HDL Workflow Script
% Generated with MATLAB 9.3 (R2017b) at 14:05:38 on 07/05/2018
% This script was generated using the following parameter values:
%     Filename  : '/tmp/MathWorks_tools/targeting_models/modem-qpsk/FixedPoint/demos/ADI_DMA_TT/hdlworkflow.m'
%     Overwrite : true
%     Comments  : true
%     Headers   : true
%     DUT       : 'combinedTxRx_ADIDMA/Combined TX and RX'
% To view changes after modifying the workflow, run the following command:
% >> hWC.export('DUT','combinedTxRx_ADIDMA/Combined TX and RX');
%--------------------------------------------------------------------------

%% Load the Model
load_system('combinedTxRx_ADIDMA');

%% Restore the Model to default HDL parameters
%hdlrestoreparams('combinedTxRx_ADIDMA/Combined TX and RX');

%% Model HDL Parameters
%% Set Model 'combinedTxRx_ADIDMA' HDL parameters
hdlset_param('combinedTxRx_ADIDMA', 'HDLSubsystem', 'combinedTxRx_ADIDMA/Combined TX and RX');
hdlset_param('combinedTxRx_ADIDMA', 'ReferenceDesign', 'adrv9361z7035 box lvds Base System (Vivado 2017.4)');
hdlset_param('combinedTxRx_ADIDMA', 'SynthesisTool', 'Xilinx Vivado');
hdlset_param('combinedTxRx_ADIDMA', 'SynthesisToolChipFamily', 'Zynq');
hdlset_param('combinedTxRx_ADIDMA', 'SynthesisToolDeviceName', 'xc7z035i');
hdlset_param('combinedTxRx_ADIDMA', 'SynthesisToolPackageName', 'fbg676');
hdlset_param('combinedTxRx_ADIDMA', 'SynthesisToolSpeedValue', '-2L');
hdlset_param('combinedTxRx_ADIDMA', 'TargetDirectory', 'hdl_prj/hdlsrc');
hdlset_param('combinedTxRx_ADIDMA', 'TargetLanguage', 'Verilog');
hdlset_param('combinedTxRx_ADIDMA', 'TargetPlatform', 'AnalogDevices adrv9361z7035 box lvds (modem)');
hdlset_param('combinedTxRx_ADIDMA', 'Workflow', 'IP Core Generation');

% Set SubSystem HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX', 'ProcessorFPGASynchronization', 'Free running');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/bytesIn', 'IOInterface', 'IP Data IN [0:63]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/bytesIn', 'IOInterfaceMapping', '[0:63]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/validIn', 'IOInterface', 'IP Valid Tx Data IN');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/validIn', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/FromRadioR', 'IOInterface', 'AD9361 ADC Data I0 [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/FromRadioR', 'IOInterfaceMapping', '[0:15]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/FromRadioI', 'IOInterface', 'AD9361 ADC Data Q0 [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/FromRadioI', 'IOInterfaceMapping', '[0:15]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/FRLoopBw', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/FRLoopBw', 'IOInterfaceMapping', 'x"100"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/EQmu', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/EQmu', 'IOInterfaceMapping', 'x"104"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Scope Select', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Scope Select', 'IOInterfaceMapping', 'x"108"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/DebugSelector', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/DebugSelector', 'IOInterfaceMapping', 'x"10C"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TxDMASelectIn', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TxDMASelectIn', 'IOInterfaceMapping', 'x"110"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/BypassEQ', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/BypassEQ', 'IOInterfaceMapping', 'x"114"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/EnableDecode', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/EnableDecode', 'IOInterfaceMapping', 'x"118"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/PDThreshold', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/PDThreshold', 'IOInterfaceMapping', 'x"11C"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TransmitToggle', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TransmitToggle', 'IOInterfaceMapping', 'x"120"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TransmitAlways', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TransmitAlways', 'IOInterfaceMapping', 'x"124"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/PacketSource', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/PacketSource', 'IOInterfaceMapping', 'x"128"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Loopback', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Loopback', 'IOInterfaceMapping', 'x"12C"');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/BypassCoding', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/BypassCoding', 'IOInterfaceMapping', 'x"130"');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/bytesOut', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/bytesOut', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/validBytesOut', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/validBytesOut', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/startPacketOut', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/startPacketOut', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/real', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/real', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/imag', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/IQ Interface Mapper/imag', 'IOInterfaceMapping', '');

% Set SubSystem HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL', 'ProcessorFPGASynchronization', 'Free running');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/re', 'IOInterface', 'Rx data I1 In [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/re', 'IOInterfaceMapping', '[0:15]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/Im', 'IOInterface', 'Rx data Q1 In [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/Im', 'IOInterfaceMapping', '[0:15]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/Enable', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/Enable', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/FRLoopBW', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/FRLoopBW', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/EQmu', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/EQmu', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/Scope Select', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/Scope Select', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/DebugSelector', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/DebugSelector', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/EQBypass', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/EQBypass', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/EnableDecode', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/EnableDecode', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/PDThreshold', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/PDThreshold', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/BypassCoding', 'IOInterface', 'Rx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/BypassCoding', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/bytesOut', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/bytesOut', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/validOut', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/validOut', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/sync', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/sync', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/payloadLenOut', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/payloadLenOut', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/dataRe', 'IOInterface', 'Rx data I1 Out [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/dataRe', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/dataIm', 'IOInterface', 'Rx data Q1 Out [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/dataIm', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/validIQ', 'IOInterface', 'Rx data Valid Out');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/validIQ', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/DebugSelection', 'IOInterface', 'Rx data Valid Out');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/DebugSelection', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/RxTransferComplete', 'IOInterface', 'Rx data Valid Out');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Receiver HDL/RxTransferComplete', 'IOInterfaceMapping', '[0]');

% Set SubSystem HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL', 'ProcessorFPGASynchronization', 'Free running');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/bytesIn', 'IOInterface', 'Tx data I1 In [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/bytesIn', 'IOInterfaceMapping', '[0:15]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/validIn', 'IOInterface', 'Tx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/validIn', 'IOInterfaceMapping', '[0]');

% Set Inport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/BypassEncode', 'IOInterface', 'Tx data Valid In');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/BypassEncode', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/Packet Generation/trueData', 'IOInterface', 'Tx data Valid Out');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/Packet Generation/trueData', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/real', 'IOInterface', 'Tx data I1 Out [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/real', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/imag', 'IOInterface', 'Tx data Q1 Out [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/imag', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/validOut', 'IOInterface', 'Tx data Valid Out');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/validOut', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/Need Data', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/Need Data', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/TxTransferComplete', 'IOInterface', 'Tx data Valid Out');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/Transmitter HDL/TxTransferComplete', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ToRadioR', 'IOInterface', 'AD9361 DAC Data I0 [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ToRadioR', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ToRadioI', 'IOInterface', 'AD9361 DAC Data Q0 [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ToRadioI', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ToRadioValid', 'IOInterface', 'IP Valid Tx Data OUT');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ToRadioValid', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/NeedData', 'IOInterface', 'IP Load Tx Data OUT');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/NeedData', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/BytesOutRx', 'IOInterface', 'IP Data OUT [0:63]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/BytesOutRx', 'IOInterfaceMapping', '[0:63]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/payloadLenOutRx', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/payloadLenOutRx', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ValidOutRx', 'IOInterface', 'IP Data Valid OUT');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/ValidOutRx', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/syncRx', 'IOInterface', 'ADC DMA sync');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/syncRx', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/reRx', 'IOInterface', 'IP Debug 1 OUT [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/reRx', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/imRx', 'IOInterface', 'IP Debug 2 OUT [0:15]');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/imRx', 'IOInterfaceMapping', '[0:15]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/validRx', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/validRx', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TxDMASelectOut', 'IOInterface', 'Tx Mux Sel');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TxDMASelectOut', 'IOInterfaceMapping', '[0]');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/debugSelectionAXI', 'IOInterface', 'AXI4-Lite');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/debugSelectionAXI', 'IOInterfaceMapping', 'x"140"');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TxTransferComplete', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/TxTransferComplete', 'IOInterfaceMapping', '');

% Set Outport HDL parameters
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/RxTransferComplete', 'IOInterface', 'No Interface Specified');
hdlset_param('combinedTxRx_ADIDMA/Combined TX and RX/RxTransferComplete', 'IOInterfaceMapping', '');

%% Workflow Configuration Settings
% Construct the Workflow Configuration Object with default settings
hWC = hdlcoder.WorkflowConfig('SynthesisTool','Xilinx Vivado','TargetWorkflow','IP Core Generation');

% Specify the top level project directory
hWC.ProjectFolder = 'hdl_prj';
hWC.ReferenceDesignToolVersion = '2016.4';
hWC.IgnoreToolVersionMismatch = false;

% Set Workflow tasks to run
hWC.RunTaskGenerateRTLCodeAndIPCore = true;
hWC.RunTaskCreateProject = true;
hWC.RunTaskGenerateSoftwareInterfaceModel = false;
hWC.RunTaskBuildFPGABitstream = true;
hWC.RunTaskProgramTargetDevice = false;

% Set properties related to 'RunTaskGenerateRTLCodeAndIPCore' Task
hWC.IPCoreRepository = '';
hWC.GenerateIPCoreReport = true;

% Set properties related to 'RunTaskCreateProject' Task
hWC.Objective = hdlcoder.Objective.None;
hWC.AdditionalProjectCreationTclFiles = '';
hWC.EnableIPCaching = false;

% Set properties related to 'RunTaskGenerateSoftwareInterfaceModel' Task
hWC.OperatingSystem = '';

% Set properties related to 'RunTaskBuildFPGABitstream' Task
hWC.RunExternalBuild = true;
hWC.TclFileForSynthesisBuild = hdlcoder.BuildOption.Custom;
hWC.CustomBuildTclFile = 'adi_build.tcl';

% Set properties related to 'RunTaskProgramTargetDevice' Task
hWC.ProgrammingMethod = hdlcoder.ProgrammingMethod.Download;

% Validate the Workflow Configuration Object
hWC.validate;

%% Run the workflow
hdlcoder.runWorkflow('combinedTxRx_ADIDMA/Combined TX and RX', hWC);


function marker = get_markers

marker = { '-*k', '-or', '-*b', '-ob', '-og', '-+m', '-*r', '-+g', '', '', '-*k', '-or', '-+b' };

end


% FT_PREAMBLE_LOADVAR is a helper script that optionally loads one or
% multiple FieldTrip data structures from mat files on disk, as an
% alternative to the user specifying the data structures as input variables
% to the calling function. This makes use of the cfg.inputfile variable.
%
% Furthermore, this function computes the MD5 hash of the input data structures for
% provenance.
%
% Use as
%   ft_preamble loadvar data
%   ft_preamble loadvar source mri
%   ft_preamble loadvar varargin
%
% See also FT_PREAMBLE, FT_POSTAMBLE, FT_POSTAMBLE_SAVEVAR, FT_PREAMBLE_PROVENANCE

% Copyright (C) 2011-2019, Robert Oostenveld, DCCN
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% use an anonymous function
assign = @(var, val) assignin('caller', var, val);

if (isfield(cfg, 'inputfile') && ~isempty(cfg.inputfile)) || exist('Fief7bee_reproducescript', 'var')
  % the input data should be read from file

  if exist('Fief7bee_reproducescript', 'var')
    % the script, input and output files are written to a directory

    % write the function input variables to a MATLAB file
    if isequal(preamble_argin, {'varargin'})
      cfg.inputfile = {};
      iW1aenge_now = datestr(now, 30);
      for i=1:(ft_nargin-1)
        cfg.inputfile{i} = make_or_fetch_inputfile(Fief7bee_reproducescript,...
          sprintf('%s_%s_input_varargin_%d.mat', iW1aenge_now, FjmoT6aA_highest_ft, i),...
          'data', varargin{i});
      end
    else
      cfg.inputfile = {};
      iW1aenge_now = datestr(now, 30);
      for i=1:(ft_nargin-1)
        cfg.inputfile{i} = make_or_fetch_inputfile(Fief7bee_reproducescript,...
          sprintf('%s_%s_input_%s.mat', iW1aenge_now, FjmoT6aA_highest_ft, preamble_argin{i}),...
          preamble_argin{i}, eval(preamble_argin{i}));
      end
    end

  elseif ft_nargin>1
    ft_error('cfg.inputfile should not be used in conjunction with giving input data to this function');
  end

  if isfield(cfg, 'inputlock') && ~isempty(cfg.inputlock)
    mutexlock(cfg.inputlock);
  end

  if isequal(preamble_argin, {'varargin'}) && ~iscell(cfg.inputfile)
    % this should be a cell-array, otherwise it cannot be assigned to varargin
    cfg.inputfile = {cfg.inputfile};
  end

  if iscell(cfg.inputfile)
    if isequal(preamble_argin, {'varargin'})
      % read multiple inputs and copy them into varargin
      tmp = {};
      for i=1:length(cfg.inputfile)
        tmp{i} = loadvar(cfg.inputfile{i}, 'data');
      end % for
      assign('varargin', tmp);
      clear i tmp
    else
      % preamble_argin is a cell-array containing the variable names
      for i=1:length(cfg.inputfile)
        assign(preamble_argin{i}, loadvar(cfg.inputfile{i}, preamble_argin{i}));
      end % for
      clear i
    end
  else
    % preamble_argin{1} contains the name of the only variable
    assign(preamble_argin{1}, loadvar(cfg.inputfile, preamble_argin{1}));
  end

  if isfield(cfg, 'inputlock') && ~isempty(cfg.inputlock)
    mutexunlock(cfg.inputlock);
  end

end % if inputfile