Flownex Version Control with GIT Client

Flownex 2024 has added version control in the form of a Git Client. In Git, all versions of a project and related files are stored in either a local or a remote repository (aka “repo”). This benefits the user as we are able to revert to older versions of a project merge changes made by multiple users, create branches within a design, and capture all changes in a log. The repository can also function as a form of backup.

Accessing the Git Client

There are two ways to access Flownex’ Git client. We can either navigate directly to the executable: C:\Program Files\Flownex SE X.X.X.XXXX\GitClient.exe, or we can open the Git client from the Flownex GUI itself.

To open the GIT client we will want to navigate to the configuration tab in the Flownex GUI and click on “Open Git Client”.

Prerequisites for Setting Up a Local Git Repository

Before we can begin storing versions of our project we want to create a repository. The first thing we must do is specify the Local Repository Credentials found in the settings tab.

The Flownex Git utility automatically records modifications and changes made to a network model. Through the Command History settings, we can omit certain user actions from the recording. Typical exclusions include:

  • “Open page”
  • “Deselect all”
  • “Select”
  • “Close page”

There is further reading on the settings customizations in section 24.1 of the Flownex General User Manual.

Creating a Git Repository

We will want to define our repository directory location in the Path or Repository field found near the top of the Git Client GUI. In this example I use the location E:\Tech Tips\5.31.2024.

If a valid Git repo does not already exist at this location we will click “Create” to make one. A new repo with a master branch will be created and an initial commit will also be performed when we click create.

Committing Changes to Git Repository

Once we’ve defined our GIT repo location we can create and commit the current version of our Flownex network. This can be done by clicking “Save and Commit” in the Flownex GUI in the Configuration Ribbon.

This will save our project and open the Git client. We should see the command history for any changes since the previous commit. At this point we can add any notes and commit our changes to the Git repository. Then we should click “Commit” to save.

Note that if we haven’t already defined our user credentials (found in the Settings tab of the Git Client GUI), we will get an error when trying to commit or create the repository.

Reverting to an Older Version

Through the Git client it is now quite simple to roll back to a previous version of a project.

To roll back to an older version of a project we should first ensure that the Flownex project in question is closed. Next, we will launch the standalone Flownex Git Client

We will need to navigate to our Git repo and then we can simply right-click on the version of the project which we’re reverting to and select “Revert to this Version”.

All changes after the selected version will be reverted without changing affecting the Git log. In this case, I can re-open the project and will see that the inlet pipe length has reverted to it’s original 100 m length.

Additional Operations

Other actions and operations available through the Git Client are described below. We can find more detailed information on these in section 24.2 and 24.3 of the Flownex General User Manual.

  • Export this Version
    • Used to export a copy of a selected version of a project.
  • Create and Switch to Branch
    • Used to create new version branches within a given master.
  • Switching between Branches
    • Users are able to switch between branches for a given project.
  • Merging Branches
    • This action will merge changes captured from separate branches into a specified “To” branch.
  • Add Remote and Push
    • This function will push existing local repo branches to a remote repo.
  • Clone
    • Used to copy a remote repo to a local location.
  • Fetch and Merge (Pull)
    • Retrieves changes from a remote repo after a clone or previous fetch.
  • Push
    • Updates all locally made changes to the remote repo.
  • Track Remote Branches as Local
    • This option allows for tracking a non-master branch from a cloned or fetched remote repo.

New Feature! Create a Reduced Order Model in Flownex

In the 2022 Flownex release (8.14.0) a new feature has been added to create Reduced Order Models. Today I’ll go over the basics for creating a reduced order model and how this can be utilized.

To demonstrate this functionality I built a simple network representing a shell and tube heat exchanger. In this model we’ve got liquid water on both the hot and the cold side. For simplicities sake we’ll keep the conditions such that the phase is always liquid.

The ROM builder setup is found under the “Configuration” ribbon in Flownex.

To configure our Reduced Order Model we will want to create a configuration and then define our Inputs (independent variables) and our Results (dependent variables). We do this by dragging and dropping inputs and results into the ROM Builder Configuration Window. For this example the independent variables will be the hot and cold side inlet mass flow rates and temperatures.

We’ll notice there are three different statuses for the ROM configuration. “New”, “SensitivityAnalysisCompleted”, and “NeuralNetworkTrained”. To complete the sensitivity analysis portion we need to set bounds for our independent variables, enter the total number of runs, and then click “Generate and Overwrite”. If we already have started creating our ROM and we simply want to expand the dataset we may want to choose “Generate and Append”.

Flownex will then run the sensitivity analysis which will provide the dataset to train our neural network.

In the creation of the neural network there are a variety of “hyperparameters” which can be adjusted to change the complexity and depth of the model. In this example we will stick with the default values but you can read all about what each of these parameters does in Chapter 23 of the Flownex General User Manual. At this point we can click the button to Build and Train our neural network! In the top right of the ROM Builder window we can see the approximate time remaining.

There are a few graphs we can view in the different tabs to assess the accuracy of our model. I am particularly fond of the results – predicted vs actual. This gives us an understanding, at a glance, of the deviation in what the ROM predicts vs Flownex results.

The last step is to export this as a standalone Functional Mockup Unit (FMU) for use in either other Flownex networks or in another tool like Ansys Twinbuilder.

Neat Input Keyboard Tricks

Do you ever find that the units on your Flownex input don’t match what you’re inputting? But you don’t notice until you’ve already typed in the value? There’s a trick to avoid redundant typing! After typing in our input we simply hold CTRL while changing the unit.

Here’s what it looks like if we hold Ctrl while choosing a new unit for a diameter input.

If we instead choose the unit while not holding Ctrl we see the units convert automatically.

If you’re more of a keyboard commando and like to avoid mouse-clicks we can also type in the units ourselves.

Some helpful keyboard shortcuts when entering units for areas, volumes, etc…

Alt + 0176 = ° (Superscript “0” used for degrees)

Alt + 0178 = ² (Superscript “2”)

Alt + 0179 = ³ (Superscript “3”)

Other Useful Input Keyboard Shortcuts

We can specify that an input is a global parameter by using “$” in the property input. Here is another blog post that goes into more detail on how to get the most out of Global Parameters.

Plotting Thermodynamic Cycles in Flownex

Often we find ourselves wanting to visualize results in a way to quickly understand how our thermal-fluid system is behaving. This is particularly desired when dealing with thermodynamic cycles. What I’d like to showcase today is how we can use the X-Y graph to plot an Organic Rankine Cycle. In today’s example I am using Flownex version 8.14.0.4675.

Rankine Cycle Modeling in Flownex

I won’t spend too much time on the system model itself, just note that we are working with a very simple network of flow components to lay the groundwork for the example. We use flow resistance elements to build the bulk of the network. We also use composite heat transfer elements to add/remove energy from the fluid. A turbine is used to extract power and, for simplicities sake, rather than model a pump we fixed the mass flowrate on one of the flow resistance components.

Creating the TS Diagram

To create the TS diagram we might first think we should use the Operating Point Plot. While this plot is indeed used for TS diagrams, since we want to plot multiple points we should instead use the XY Graph found in the components library under Visualization > Graphs. The XY Graph can be dragged and dropped onto the drawing canvas.

Another option would be to add the XY Graph as its own page. This can be done by clicking on the Project View pane, selecting the “Graphs” button, then right-clicking on the folder and adding a new graph page.

Then, to add our TS data points, we’ll simply drag and drop the Fluid Data Reference from the key components/nodes in our system onto our newly created graph.

Lastly, if we’d like to connect the data points we can do so by editing the properties of the XY Graph to connect points.

There we have it! A TS diagram with our operational points overlaid all in Flownex! Recall we can expose a lot of additional formatting for our graphs by checking the boxes under Advanced Formatting for either Graph formatting or Line formatting.

Save your back-end with the Flownex Backtracker

We’ve all experienced that fear. When we sit down at our computer and realize that all of our applications are closed. That Windows decided to do a restart in the middle of the night. If we are running any long simulations the thought of having to restart from the beginning is a tough pill to swallow. Luckily, in Flownex, we can use the backtracker functionality to create re-start points during the simulation. In today’s demo I am using the most recent Flownex release, 8.14.0.4675.

Enabling the Backtracker

The Backtracker is useful both for resuming long transients and for troubleshooting transient behavior around a transient action. The Backtrack setup can be found in the Configuration ribbon at the top of the Flownex GUI.

After clicking Backtrack setup we will see the backtracker pane available on the right side of the GUI similar to “Snaps”. We will want to click the floppy disk (save) button in the Backtrack pane to enable saving of backtracks. The button will have a blue outline when backtracking is enabled. The “X” button will delete all backtracks.

Backtracker Inputs

In the Backtracker interface we have several inputs we can define. The most important to define are the interval and the count.

  • Interval
    • Defines how often a backtrack is saved. The default unit for interval is in seconds.
  • Count
    • Determines the count of recent backtracks that are retained in the Backtracker. If we want to capture the entire transient we should multiply the count by interval to make sure the entire duration is covered.
  • “Use prefix number”
    • This checkbox along with the “Start number” will save the backtracks with the desired number as a prefix, counting up with each concurrent backtrack save.
  • “Use snap name as prefix”
    • This checkbox will ensure that the backtracks saved have the prefix of whatever snap was loaded before the run was initiated.
  • “Steps after snap load to first backtrack”
    • This allows us to specify how many timesteps should complete (after initial snap load) before the first backtrack is saved.

Breath Easy and Run Transients

At this point we should be able to run our transient and see the backtracker populate. To load a saved backtrack point we should ensure our simulation is in an inactive state before right-clicking on the backtrack and choosing load. From this point we can resume our transient simulation.

Bonus Tip!

  • When troubleshooting a transient right-click on the backtrack just before the event and select “copy to snap” so that you can retain and load the state of the network at this start point.

Flownex 2022 Release

The new 2022 Flownex release is here! Lots of great enhancements to take your simulations to the next level highlighted below.

Major Enhancements

New Non-Iterative Transient Solver

A new non-iterative transient solver has been implemented in Flownex®. Compared to the customary iterative solver, the non-iterative transient solver increases solve speed substantially during transient events by eliminating the need to iterate within time steps. This becomes very advantageous for networks of all sizes, but especially where large systems need to be modelled over a prolonged time span.

The user can switch between the iterative transient solver and the non-iterative transient solver via the dropdown provided in the Transient solver settings category on the Flow Solver input dialogue. For easy access, a direct toggle between the solvers was added as a tab to the Home ribbon as well.

Fig. 1 – Non-Iterative Transient Solver Toggle on the Home Ribbon.
Fig. 2 – Non-Iterative Transient Solver Selection Option in the Flow Solver.

The non-iterative transient solver retains the implicit pressure-velocity coupling in use for the iterative solver, thereby maximizing numerical stability in typical flow systems. Since the pressure-flow solution is not iterated with respect to the enthalpy solution, the method may be classified as semi-implicit.

Instead of using successive iteration with underrelaxation to obtain a converged solution, all governing equations are fully linearized with respect to the primary variables as well as the temporal variable, using exact and accurate gradients and derivatives without any relaxation. For this reason, all inputs within the Convergence, Relaxation Parameter as well as the Iterations categories become redundant when using the non-iterative transient solver option.

Mixture Generalization

The capability to create a mixture of fluids has been expanded to create mixtures of mixtures for all fluid types, with the exception of two-phase fluids. When a fluid mixture is created, the user now has the option to select more than one liquid and more than one gas when creating mixtures for each of those phases. The below figure shows a Gas and Liquid Mixture, where the user can create a liquid mixture and a gas mixture that consists of multiple liquids and gases within the liquid-gas mixture.

Fig. 3 – Example of a Gas and Liquid Mixture with a Mixture of Gases and a Mixture of Liquids.

Mixing rules for transport properties are applied to the individual phases separately and in the case of a liquid-gas mixture, additional liquid-gas mixing rules are applied when determining the transport properties of the liquid-gas mixture-of-mixtures.

To use the new capability a mixture is configured in the Fluid mixture specification dialog.  The remaining user interface experience has not changed.  Mixture mass fraction boundary conditions are specified as before, with the list of fluid components expanded to include all of the components of the mixture.

Fig. 4 – Specifying Mass Fractions of a Liquid-Gas Mixture which Contains a Liquid Mixture and Gas Mixture.

Similarly, the result property displays the fluid component mass fraction results for the expanded mixture of mixtures, as seen in Figure 5.

Fig. 5 – Mass Fraction Results of a Liquid-Gas Mixture which Contains a Liquid Mixture and Gas Mixture.

As phase transitions in two-phase fluids are significantly impacted by the presence of other two-phase fluids, the new mixture capability does not currently include the possibility to create a mixture of two-phase fluids.  It is however possible to create a Two-Phase Fluid and Gas Mixture where a mixture of gasses can be specified with a single two-phase fluid, as seen in Figure 6.

Fig. 6 – Two-Phase Fluid and Gas Mixture.

ROM Builder

The Flownex® ROM (Reduced Order Model) Builder generates a multi-platform enabled FMU (Functional Mock-up Unit) containing a Neural Network that was trained on sensitivity analysis data. The user is guided from specifying the input and result properties, creating sample data in a sensitivity analysis, specifying the Neural Network hyperparameters, evaluating the trained Neural Network to exporting the FMU ROM using one convenient dialog. The ROM Builder Configuration dialog can be seen in the image below:

Fig. 7 – ROM Builder Configuration.
Fig. 8 – ROM Builder training a Neural Network

Video Recorder

The capability has been added to record graphs and the screen synchronized with transient solving. The video recording options are added to the properties of each graph. When “Record graph as video” is set to “Yes”, a new video is recorded for each transient run. From the Video Recorder task properties (under Solvers), Flownex® can be configured to record the whole screen.

Fig. 9 – Recording a graph to the Videos folder.

Two Phase Heat Transfer

The two-phase fluid generator has been updated to include Steiner and Taborek normalized coefficients and includes an updated radiation model specification. In previous versions the Steiner and Taborek normalized coefficients were effectively hardcoded and were only available for a limited number of two-phase fluids.  These coefficients have now been moved to the two-phase fluid data files and the fluid generator therefore required updating to allow the user to provide the appropriate values for generated fluids.  The latest two-phase data file format also provides for the selection of the radiation participation model to be used for the generated fluid.

Fig. 10 – Two-Phase Fluid Importer with Saturated Boiling and Radiation Model Specification.

Minor Enhancements

USER INTERFACE FRAMEWORK

Higher resolution (4K) compatibility has been added to the Graphical User Interface.

ACTIONS

The capability to specify a Ramp action has been added. When a Ramp action is created, the user can specify the duration and final value for the action rather than the coefficients for a straight line.

Fig. 11 – Ramp Action.

UNITS

  • The mils unit has been added that is used for vibration.
  • Added the capability for a user to reset the unit of a property to the current selected unit system default. This option is available on the context menu on a property, as seen below.
Fig. 12 – Reset Unit Option.

GRAPHS

  • Added a property to change point symbols to be solid or hollow.
  • Added a ThinCross symbol type.
Fig. 13 – ThinCross Symbol Type and Solid Symbol Option Properties added to Graphs.
  • Grouping line items with the same unit group onto one Y-axis is now possible. The “Display multiple Y-Axis” property has been replaced with ”Axes displayed” property.
Fig. 14 – Axes Displayed Property.
Fig. 15 -Axes Displayed Property.

COMPONENT CHARACTERISTIC GRAPHS

  • An option to view all Angles on Compressor Component Characteristic Graph has been added.
  • Angles are now available to be checked/unchecked from the graph legend.
  • All four dimension’s values of the chart are displayed in the chart tooltip.
  • Only plotting the closest lines functionality is still available by setting a new property: “Show closest background lines” to “Yes”. Property is below “Background lines”.
  • By default, all lines with check boxes will be displayed for new graphs and graphs from older projects.

SCRIPTING

  • The Script component has been updated such that the “Initialise” function is called only once before Steady State and “Cleanup” is called once after Steady State. This is done if any or all of the options are active for Before, During and After Steady State. Previously it was called multiple times during Steady State if more than one of the options were active.
  • The Iterative Script’s “Initialise” and “Cleanup” functions now works similar to a normal Script and is called before and after every steady state and called before and after every transient.
  • The font of the code editor was changed to a monotype font in order for spacing to align better.
  • A repository was added that allows for easy sharing of values between scripts. The repository of values can also be loaded and saved as needed.
    • The repository is used in the following manner:
      • To add or change a value:

IPS.Scripting.SharedValueRepository.AddOrUpdateDoubleValue(“MyVal”, 10.0);

    • To access a value from a different script:

double val = IPS.Scripting.SharedValueRepository.GetDoubleValue(“MyVal”);

  • The repository supports the following functions:
    • void AddOrUpdateDoubleValue(string Name, double Value);
    • void AddOrUpdateIntegerValue(string Name, int Value);
    • void AddOrUpdateBooleanValue(string Name, bool Value);
    • void AddOrUpdateStringValue(string Name, string Value);
    • void AddOrUpdateValue(string Name, System::Object^ Value);
    • double GetDoubleValue(string Name);
    • int GetIntegerValue(string Name);
    • bool GetBooleanValue(string Name);
    • string GetStringValue(string Name);
    • System::Object^ GetValue(string Name);
    • bool HasValue(string Name);
    • void SaveRepository(string FileName);
    • void LoadRepository(string FileName);

DRAWING

  • An application setting has been added so that new pages have the viewport in the middle of the page. This setting is false by default.
Fig. 16 – Viewpoint in Center for New Pages Setting.

SNAPS

  • Added an application wide setting: “Turn snap before run on by default”. This option is false by default, but a user can make it true, then it will be on for all new projects.
Fig. 17 – Turn Snap Before Run on by Default Option.

PCF IMPORTING

  • Added a default import mapping that imports components other than only pipes as applicable.
Fig. 18 – Import Configuration Dialog.

DATA TRANSFER LINKS

  • Implemented bi-directional data transfer capability for Data Transfer Links. The user can drag and drop from the left or the right side of the Data Transfer Link Setup dialog. The direction of the transfer is indicated by the arrows. Bi-directional transfers show arrows at both sides, as seen below.
Fig. 19 – Bi-Directional Data Transfer Capability for Data Transfer Links.
  • The letters F and C are displayed on a Data Transfer Link when a factor (F) or constant (C) is used.
Fig. 20 – F and C Displayed on Drawing Page.

FLOW PATH GRAPHS

  • Added the ability to plot Flow Path Graphs along the Rotating Annular Gap length and length increments of the Rotating Channel.

TWO PHASE PRESSURE LOSS

  • Added output for Lockhart-Martinelli two-phase pressure loss calculations and the parameters that are used in its calculation as results.

HEAT TRANSFER

  • Reynolds and Prandtl Number results have been added to convective subdivision element results.
  • Errors have been implemented to prevent Composite Heat Transfer element to Composite Heat Transfer element connection via a solid Node with non-adiabatic boundary conditions, since these are non-physical configurations.

RELAP COUPLING

  • Added an option to Relap simulation to save every transient step’s output file.
  • Fixed the problem where the minor edits were deleted in Relap files.
  • Allow users to add additional inputs or outputs to the Flow solver coupling. This is especially useful to extract additional results from the Relap simulation.

COMMAND LOGGING

  • Flownex® logs many of the user actions now to a file. This log is useful to keep track of what was changed in a project and when.
  • The command log files are located in the project folder in the sub folder CmdRec\Logs.
  • Each new Flownex® session starts a new log with the date and time of the session. The user, operating system and computer name are recorded at the top of each file.
  • The following user actions are recorded to the file:
    • Interaction with the drawing canvas (e.g. adding, deleting, selecting components).
    • Interaction with pages (opening, closing, selecting pages).
    • Interaction with snaps (saving, loading).
    • Setting component inputs.
    • Solving commands (solve steady state, transient, stopping etc.).
Fig. 21 – Command Logging Text File.

FMI

  • Exported Flownex® FMUs now launch a separate console that communicates with the Flownex® instance that is launched. This is done to enable the FMU binary to be unloaded by the master simulator. The binary was previously locked until the master simulator process shuts down due to the CLR being loaded as part of the binary. All CLR code is now loaded in the separate console process.
  • The locked binary gave a warning or error when the FMU was unloaded, even though the FMU functioned correctly.

NIST IMPORTER

  • The NIST fluid importer was updated to list all the available fluids and mixtures in NIST.

BUG FIXES

RESULT LAYERS

  • Fixed the bug where Result Layers did not update during transient in 3D view.
  • Result Layers are now updated after a Snap is loaded.
  • Fixed absolute value usage in Result Layers.
  • Changed mass flow, volume flow and velocity built in Result Layers to use absolute values.

VELOCITY PID

  • Fixed the bug where state of the PID was not saved to Snaps.

DRAWING TEXTS

  • Fixed the problem when pressing the Cancel button when changing settings for the drawing texts, the operation was not fully cancelled.

EXCEL COMPONENT

  • Fixed bug where Snaps were not correctly loaded for Excel component if an editor wasn’t opened previously or network wasn’t solved previously.

RESULTS OVERVIEW

  • Fixed the bug where the Solving On/Off state was not saved with the project. This meant that the user had to turn it off again every time the user opened a project.

API

  • Fixed a bug where an exception in the user interface was sometimes shown when using the API. This happened when using the API with a network with open graphs.

DUCTING

  • Added tooltip results for all Junction component types.

POSITIVE DISPLACEMENT PUMP

  • Fixed the unit for NPSH in the characteristic chart.

EXCESS FLOW VALVE

  • Added tooltip results for the Excess Flow Valve.

NODES

  • Fixed the error where a user could connect multiple views of a node or element to a fiber that should only allow a single connection. This caused an error in the solver that was not very descriptive and hard to trace.

WARNINGS AND ERRORS

  • Updated MATRIX_NOT_POSITIVE_DEFINITE error to also show the Node related to the error.
  • Added a warning when a large non-normalized energy residual is detected at a node and the energy equations may not have converged.

NEUTRONICS SCRIPT

  • Implemented Total power result and Transient Fix power option correctly for the Neutronics Script.
  • Initialisation was not correctly called for the Neutronics Script and a Cleanup function has been added.

BOUNDARY CONDITIONS

  • If Mass source fraction is disabled after being specified, the mass fraction did not reset to 1 and 0, as with the normal mass fraction specification.
  • Fixed the problem where a Data Transfer Link could write and change the temperature of a Boundary Condition even if the option to specify temperature is not turned on.

HEAT TRANSFER

  • Addressed Conduction results that went out of sync when changing from upstream Convection results to Conduction element results after an increment other than 1 is selected for the upstream Convection results.

TWO PHASE FLOW HEAT TRANSFER

  • The Steiner and Taborek reference coefficients are now specified in the two-phase fluid specification file and are no longer hard coded. Approximations have been provided for Flownex® fluids that are not featured in the original Steiner and Taborek paper, and a warning is issued.
  • The heat flux at the critical heat flux conditions is used when the wall temperature commensurate with the critical heat flux that is calculated. Previously the current heat flux result was used in the wall temperature calculation.
  • Updated the Groeneveld critical heat flux and film boiling lookup tables to the latest versions.

V&V

  • The Validation Runner was renamed to Verification Runner. The Verification Runner is now included in the Nuclear module and uses the normal Nuclear license and does not require a separate license anymore.

ACTIONS

  • Fixed the problem where actions wrongly set integer values at the start of an action. The initial value of the integer property was always added as an offset. This was reported as a multiplexer problem but is a general problem.

Using Property Monitor to Pause a Simulation in Flownex

Hi All! It has been a little while since a Friday Tech Tip has gone out – 2022 has been a busy year so far! Today we’ll share a quick how-to on using the property monitor to interrupt our simulations. This is a powerful tool for transient analysis to quickly define a pause or stop criteria.

In this demo we’ll be reviving the previous fire suppression demo. I’m faced with a situation where I don’t know how long it will take for the suppression agent bottle to empty. Rather than running a long simulation or trying a variety of transient lengths we can instead use the property monitor to interrupt the solve.

The property manager can be found in the configuration ribbon;

The important thing here is that we pick a reasonable property to use as our criteria for interrupting the solve. My first thought was to pick the pressure remaining in the tank but after giving it more thought I think that mass flowrate is probably a better measure since it may take quite awhile before the pressure in the tank drops all the way down to atmospheric.

To assign a property to monitor we simply drag and drop the property into the property monitor window:

There are a lot of settings we can manipulate in the property monitor for a variety of different applications. In this instance, I would like the solve to pause when the mass flow rate drops below a certain point. We can do this by checking the “Pause” box and choosing an appropriate criteria to trigger the pause.

Once this is set up we can safely let the simulation run unattended, safely knowing when our pause criteria is met Flownex will interrupt the solve for us!

Reading values from Excel component into Flownex Scripts!

Today we’re going to explore how we can directly reference specific cells in Excel workbooks via script. By building the direct reference in the script we can avoid having to assign specific cells as outputs and we can also avoid having to use data transfer links which can clutter our work canvas.

Code Snippets

Depending on when we want the script to execute we should choose the appropriate function to make this part of. Since I want this to be called every cycle I will make this part of the “Execute” function.

//script main execution function - called every cycle
public override void Execute(double Time)
{
//new code to go here	
}

The first bit of code we’re going to use will link our script to the excel file “Workbook (2).xlsx” in the Flownex project directory.

SpreadsheetGear.IWorkbookSet workbookSet = SpreadsheetGear.Factory.GetWorkbookSet(); 

// Path to where Flownex Project is located
System.IO.DirectoryInfo projectpath = new System.IO.DirectoryInfo(Project.ProjectRootPath);	        
		
// Create Workbook object linked to .xlsx file or .csv
SpreadsheetGear.IWorkbook workbook = workbookSet.Workbooks.Open(projectpath + "\\Tasks\\ExcelWorkBooks\\Workbook (2).xlsx"); 

Now that we’ve created our workbook object connected to the Excel file we can read in values from cells in a couple of different ways.

To read from an explicit cell (A1),

// Read from Cell A1 in Sheet 1
double excel_value_1 = Convert.ToDouble(workbook.Worksheets["Sheet1"].Cells["A1"].Value); 

to read from a set row and column,

// Read from Row 4, Column 1 in Sheet 2 (Note: row and column indices start at 0)
double excel_value_2 = Convert.ToDouble(workbook.Worksheets["Sheet2"].Cells[3,0].Value); 

If the value in the Excel cell is a string we can use the following,

// Read text from Cell B1 in Sheet 1
string excel_value_3 = workbook.Worksheets["Sheet1"].Cells["B1"].Value as string; 

There we have it! These are now internal variables to the script. To assign them as output variables we can use the following syntax (this is all still within the Execute function).

//Save Value to Output Script Variable
Output1.Value = excel_value_1;
Output2.Value = excel_value_2;
Output3.Value = excel_value_3;

Then, as per the usual, we’ll need a bit of code to initialize these output variables and make them visible/usable outside of the script.

//constructer initializes parameters
	public Script()
	{
		_Output1 = new IPS.Properties.Double();
		_Output2 = new IPS.Properties.Double();
		_Output3 = new IPS.Properties.Text();
	}

	//property declarations to make
	//parameters visible to outside world
	[PropertyUsage(UseProperty.DYNAMIC)]
	public IPS.Properties.Double Output1
	{
		get
		{
			return _Output1;
		}
	}
	
	[PropertyUsage(UseProperty.DYNAMIC)]
	public IPS.Properties.Double Output2
	{
		get
		{
			return _Output2;
		}
	}
	
	[PropertyUsage(UseProperty.DYNAMIC)]
	public IPS.Properties.Text Output3
	{
		get
		{
			return _Output3;
		}
	}
}

Happy Friday and Happy Scripting!