tutorial_pse
tutorial-pseudocode-java-programming-online
2. Decision structures:
If (condition is true) Then
True-actions
Else
False-actions
3
Basic Constructs of Pseudo-Code
3. Loop Structures
1) While-loops
while (condition is true) do Actions
5
Introduction of Pseudo-code
* Pseudo-code is written for human reader, not for a computer. * Try to represent/describe high-level ideas, rather than low-level implementation details.
Class Modifiers – specify a class’s scope and status
Abstract – a class that has abstract methods. Final – describes a class that can have no subclasses Public – is visible/accessible from any classes Default: None – is considered friendly. Visible by all classes in the same package
Body
Set of basic code constructs
2
Basic Constructs of Pseudo-Code 伪代码的基本结构
tutorial_1 soluation
Hardware Macstuff Winstuff 200 100
Software 1000 1500
In this economy the firm whose opportunity cost of producing a good is lowest is said to have a comparative advantage (CA) in producing that good. The firm with an absolute advantage (AA) in producing a good produces that good with the least amount of resources. Opportunity cost of producing 1 unit of: Hardware Macstuff Winstuff 5 units of software 15 units of software Software 1/5 units of hardware 1/15 units of hardware
Question 3 There are two firms: Macstuff and Winstuff. Each firm can produce either software or hardware using their resources. With one unit of its own resources Macstuff can produce 200 units of hardware or 1000 units of software. With one unit of its own resources Winstuff can produce 100 units of hardware or 1500 units of software. Each firm has 10 units of resources to allocate to the production of software and hardware. Suppose Macstuff and Winstuff agree to specialise their production according to their comparative advantage in producing software and hardware, and to then exchange with each other. Identify the bounds on the terms at which they would agree to trade software for hardware? Express your answer in terms of the amount of hardware that would be ‘paid’ for software. Explain your answer.
PSCAD_tutorials_1_4
PSCAD BASIC TRAININGTutorials 1 – 4Getting Started and Basic FeaturesTutorial 1Getting familiar – creating cases and librariesT1.1 Create a new case by using either the Menu or Toolbar . A new case should appear in the Workspace settings entitled noname [psc]. Right-click on this Workspace settings entry and select Save As… and give the case a name.NOTE: Do not use any spaces in the name!Create a folder called c:……/PscadTraining/Tutorial_01. Save the case as case01.pscT1.2 Open the main page of your new case. Build a case to compute the product of two input signals.21X X Y ⋅=t Sin X ⋅⋅⋅=10051 52=XYou may use the wire mode to connect different components Wire Mode.T1.3 Plot the output Y. Name the plots. Use X-Y plot feature to plot Y vs. X1 and X1 vs. X2.T1.4 Unload the above case and create a new library by using either the Menu or Toolbar . A new library should appear in the Workspace settings entitled noname [psl]. Right-click on this Workspace setting sentry and select Save As… and give the library a name.Save the case as case01.psl in c:……/PscadTraining/Tutorial_01T1.5 Under the Component Definitions branch, Copy the Component Definition called Multiplier from the Master Library into your new library. Rename the definition [my_mul] and enter a new description. Create an Instance of this definition and paste it into the main page of the new library. You have now created a new Component Definition!T1.6 Unload case01.psc and reload it. Save it as case02.psc . Replace the multiplier with the new component that you just created. Run the case to verify results. Modify the new component so that the output Y is()212X X Y ⋅⋅=Run the case and observe results.T1.7 Unload all cases except the master library. Load case02.psc and try to run the case. Now load case02.psl and try to run case02.psc.Unload and reload case02.psc. Now run the case!Tutorial 2Getting Familiar with PSCAD: Plots, Graphs & Curves and single line diagramsT2.1 In your …Program Files/pscad/examples/tutorial directory, open the case project called simpleac.psc. Set the case Plot Step to 50 μs and run the case. Using the Zoom feature, zoom into the area where the fault occurs. Get familiar with keyboard shortcuts.Save the case as simpleac01.psc in c:……/PscadTraining/Tutorial_02T2.2 Invoke the cross hairs mode and follow the curves with the cross hairs. Monitor all phases A, B and C by switching between curves using the ‘space bar’. Turn cross hairs off, zoom out to the previous view and resize if necessary. Get familiar with the ‘graph properties’ ‘graph frame properties’ and keyboard short cuts.T2.3 Right-click on the top graph and select Graph Properties. Invoke the cross hairs and flip between curves. Experiment with grid lines, markers, colors and line thickness. Is it presently possible to have curves of different thickness on the same graph?T2.4 Plot the Phase A sending end and receiving end currents on the same graph.T2.5 Convert the circuit of the sending end to a single line format.Save the case as simpleac02.psc in c:……/PscadTraining/Tutorial_02T2.6 Convert the transmission line interface component in the receiving end to single line format. Use the’ breakout’ component to link single line drawings to three phase drawings.T2.7 Measure the line to ground voltage on the sending end. Use the ‘data tap’ to derive the three voltage signals from the voltmeter connected to the ‘single’ line. Plot the voltages.Rerun the case, starting from a S napshot file, taken at 0.2 s.Note that the timed fault logic and timed breaker logic settings are not changed in the simulation. However, the fault appears to be initiated at 0.05 s and not 0.25s as specified. Why? Can the time axis scale be changed to reflect the ‘actual’ time?Can the simulation time step be changed when the case is run from a snapshot file?T2.8 Resize the page and add sticky notes and experiment with curve settings. Make the page look ‘presentable’ in a report. Go to edit=> workspace settings and check out the available options.Tutorial 3Building a simple caseT3.1 Create a new case by using either the Menu or Toolbar. A new case should appear in the Workspace settings entitled noname [psc]. Right-click on this Workspace settings entry and select Save As… and give the case a name. NOTE: Do not use any spaces in the name!).Save the case as accircuit01.psc in c:……/PscadTraining/Tutorial_03T3.2 Open the main page of your new case. Construct the circuit as shown below using the methods discussed up until now.T3.3 Use the Three Phase Source model and externally control it using a Real Constant tag for frequency and a Slider to control L-G Peak Voltage. Create a Plot and monitor currents Ia, Ib and Ic flowing through the Three Phase Breaker. Set the Timed Breaker Logic for 1 operation and so that the breaker is initially closed and will open at 0.4 sec.Externally control the Three Phase Fault with a Dial. Initiate the fault at 0.1 sec., with duration of 0.2 sec. Run the case multiple times, each time trying a different Fault Type.Experiment with different fault and breaker times. What happens when the series inductors are all set to 0.5 H? Why?T3.4 Your supervisor asks you to monitor the fundamental +\-\0 sequence currents flowing through the breaker during each fault: Use the On-Line FFT component for this as shown to the right. Run the case again multiple times, each time trying a different Fault Type. Does zero sequence current flow for every type of fault?T3.5 Add a Three Phase RMS Voltage meter between the breaker and the fault branch. Set the Voltage for Per-Unitizing to the voltage specified in your source. Why is voltage ripple sometimes present? What happens when you adjust the Smoothing Time Constant of the RMS meter?Save the case as accircuit01.psc in c:……/PscadTraining/Tutorial_03T3.6 Construct a Sequence of Events, which performs exactly the same timed control logic you are using now for your breaker and fault. When you are finished, delete the Fault Logic and Timed Breaker Logic components and provide the required control signals from your Sequencer.Save the case as accircuit02.psc in c:……/PscadTraining/Tutorial_03T3.7 Create a page module and move the Three Phase Fault component, along with the Dial, inside of it. HINT: The sub-page will require 3 electrical nodes (X-Nodes) and one data input node.Save the case as accircuit03.psc in c:……/PscadTraining/Tutorial_03T3.8 Measure the Harmonic impedance of this system at different points. Use the ‘Harmonic Impedance’ meter and get the instructor to explain how it is used.Open the case as accircuit04.psc in c:……/PscadTraining/Tutorial_03. Run the case and see the output files created from the ‘Harmonic Impedance’ component.T3.9 EXTRA: Create a data signal to monitor the A Phase fault current by defining it as an “Internal Output Variable” in the Three Phase Fault Component dialog window. Add Output Channels and create a plot inside the Page Component to monitor the signal. Cut the entire Plot window and Paste it into the Main Page of the case and run it again. What happens?T3.10 EXTRA: Output the Phase A fault current through an Export Tag to the main page. HINT: You must modify the Page Component.Tutorial 4Series tuned filterT4.1 Create a new case by using either the Menu or Toolbar . A new case should appear in theWorkspace settings entitled noname [psc]. Right-click on this Workspace settings entry and select Save As… and give the case a name. NOTE: Do not use any spaces in the name!). Save the case as tunedfilt01.psc in c:……/PscadTraining/Tutorial_04T4.2 Open the main page of your new case. Construct the circuit as shown below using the methods discussed until now:T4.3 Add a File Reference to point to a file called signal.out in your course directory. To view the file, double-click the File Reference icon. Signal.out will be the input file for the File Read component. NOTE: The file signal.out is an output file created by PSCAD and is located on your course disk. The two columns of data represent time and signal magnitude, which has an AC fundamental frequency, along with 5th and 7th harmonics.T4.4 Use the File Read component to input an external signal to the Single Phase Source , as shown in the diagram above. Under File Name in the File Read dialog window, enter signal.out and change the number of columns to read to 2. Set the Single Phase Source to Ideal , DC and External Input . Set the default variable R, L and C values to 0.1 Ω, 0.07036 H and 100 μF respectively.T4.5 In the Project Settings dialog window set the simulation time to 0.15 sec and time and plot step to 50 μs. Run the case and plot the signals Vin and Vout as curves on the same graph. The series filter is tuned by default to pass only one frequency. What frequency does the signal Vout appear to be? HINT: Use markers- mode on the graphT4.6 Revert back to standard startup (that is, remove starting from a snapshot). Add the Multiple Run component and set it up to sequentially vary the capacitance of the capacitor from 10 μF to 100 μF (in 10 μF increments). Connect the Multiple run output to the capacitor as shown to the right. NOTE : Make sure the Multiple Run component is enabled!T4.7 Run the case and monitor Vin and Vout . What affect does the varying capacitance have on the output voltage?T4.8 Use the feature in Multiple Run to analyze Vin . Find the value of C that would give the minimum Vin .T4.9 EXTRA : Using components from the CSMF section of the Master Library to calculate the resonant frequency in Hz for each new value of capacitance C.CL 21f 0⋅⋅π⋅=T4.10 EXTRA : Check the impedance spectrum using the ‘Harmonic Impedance’ component.。
最新Tutorial_CHAP11 英文版宏经讲义
3
r LM
IS
Chapter Eleven
y
4
+G
Consider an increase in government purchases. This will raise the level of income by G/(1- MPC)
The interest rate r then falls until people are willing to hold all the extra
money that the Fed has created; this brings the money market to a new
equilibrium. The lower interest rate, in turn, has ramifications for the goods
This will raise the level of income by
T ×MPC/(1- MPC)
r IS IS´ LM B
A
Y
The IS curve shifts to the right by T ×MPC/(1- MPC) which raises
income and the interest rate.
r IS IS´ LM B
A
Y
The IS curve shifts to the right by G/(1- MPC) which raises income
and the interest rate.
Chapter Eleven
PySide Tutorials(Beginner tutorials)
PySide TutorialsIn this wiki page, we have sorted out some tutorials structured by rough experience levels. So we have tutorials for absolute beginners, for intermediate#调解,中间,中级 PySide developers and for the more advanced ones who are just searching for simple solutions for their complex problems.Beginner tutorials⇧Your first PySide application – A simple Hello World application.⇧A simple clickable button tutorial – Clickable button which will show Hello World each time you press it.⇧Simple PySide dialog application – Creates a simple dialog with an edit area and a button to greet the user.⇧pyside-simplicissimus – 10 minutes newbie to newbie code snippets.Advanced tutorials⇧Hatchet: hack frozen PySide apps down to size [rfk.id.au]Your first PySide applicationIf you followed Setting up PySide wiki page to install PySide, you should now have a full blown copy of PySide on your machine to start developing Qt+Python GUI applications. As any other programming framework, you start by the traditional “Hello World”.Here is a simple example of an Hello World in PySide:1 2 3 4 5 #!/usr/bin/python# Import PySide classes import sysfrom PySide.QtCore import *6 7 8 9 10 11 12 13 14 15 16 from PySide.QtGui import *# Create a Qt applicationapp = QApplication(sys.argv)# Create a Label and show itlabel = QLabel("Hello World")label.show()# Enter Qt application main loopapp.exec_()sys.exit()With PySide desktop applications, you must always start your file by importing PySide.QtCore and PySide.QtGui classes. These classes have the main functions for building PySide applications. For instance, PySide.QtGui contains functions for dealing with widgets while PySide.QtCore contains methods for handling signals and slots, and controlling the application.After the imports, you create a QApplication which is the main Qt application. As Qt can receive arguments from command line, you must pass any arguments to the QApplication obje ct. Usually, you don’t need to pass any arguments so you can leave it as it is.After the creation of the application object, we have created a QLabel object. A QLabel is a widget that can present text (simple or rich, like html), and images. Note that after the creation of the label, we are calling the method show which will present the label to the user.Finally, we call app.exec_() which will enter the Qt main loop and start to execute the Qt code. In reality, it is only here that the label will be shown, but this can be ignored for now.Displaying html in the labelAs mentioned previously, you can insert html tags in the label to present rich text. Try changing the code which creates the label for something like:label = QLabel("<font color=red size=40>Hello World</font>")#就是用htmltag 指定 str 样式and you will the the “Hello World” now bigger and red. You can try to change to another color, another size, or make it blink! Or you can create other elements instead of the QLabel, like QPushButton, or others. PySide 教程:第一个PySide 应用使用你已经安装了PySide,那么现在你应该已经拥有完整的PySide拷贝,并且可以使用Qt+Python的方式开发GUI应用程序。
Python Tutorial 手册
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. Python 是一种容易学习的强大语言。它包括了高效的高级数据结构,提供了一个简单但很有效的方式进 行面向对象编程。Python 优雅的语法,动态类型,以及它天然的解释能力,使其成为了大多数平台上应 用于各领域理想的脚本语言以及开发环境。 The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site, /, and can be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation. Python 解释器及其扩展标准库的源码和编译版本可以从Python 的Web 站点, /, 及其所 有镜像站上免费获得,并且可以自由发布。该站点上也提供了Python 的一些第三方模块,程序,工具, 以及附加的文档。 The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications. Python 的解释器很容易通过C 或C++ (或者其它可以由C来调用的语言)来实现功能和数据结构的扩 展。因此Python 也很适于做为定制应用的一种扩展语言。 This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. 这个手册介绍了一些Python 语言及其系统的基本知识与概念。这有助于读者对Python 有一个基本的认 识,当然所有的例子都包括在里面文中了,所以这本手册很适合离线阅读。 For a description of standard objects and modules, see the Python Library Reference document. The Python Reference Manual gives a more formal definition of the language. To write extensions in C or C++, read Extending and Embedding the Python Interpreter and Python/C API Reference. There are also several books covering Python in depth. 需要有关标准对象和模块的详细介绍的话,请查询Python 库参考手册 文档。Python 参考手册 提供 了更多的关于语言方面的正式说明。需要编写C或C++扩展,请阅读Python 解释器的扩展和集成 以 及Python/C API 参考手册。这几本书涵盖了各个深度上的Python知识。 This tutorial does not attempt to be comprehensive and cover every single feature, or even every commonly used feature. Instead, it introduces many of Python’s most noteworthy features, and will give you a good idea of the language’s flavor and style. After reading it, you will be able to read and write Python modules and programs, and you will be ready to learn more about the various Python library modules described in the Python Library Reference. 本手册不会涵盖Python 的所有功能,也不会去解释所用到的所有相关的知识。相反,它介绍了许 多Python 中最引人注目的功能,这会对读者掌握这门语言的风格大有帮助。读过它后,你应该可以阅读 和编写Python 模块和程序,接下来可以从Python 库参考手册 中进一步学习Python复杂多变的库和模块。
tutorial(中文版)
FastCAM绘图练习题
休息5分钟
第三讲:手动编程 第四讲:自动编程
(所需时间:15分钟) (所需时间:30分钟)
一、FastPATH 设置
(在桌面上看不到,在使用CAM模块或NEST模块时会被调用。) 主要的功能: 设置数控切割工艺:全自动设置零件的切割路径,提高工作效率。 自动设置引入引出线,设置割缝补偿,设置各种切割工艺,包括共 边,桥接和连续切割工艺。
1. 切割路径效验
2. 成本核算
手动编程练习
1、将《练习1.CAM》经过处理后通过手动方法输出NC码,并观察。 2、将《练习2.dxf》经过处理后通过手动方法输出NC码,并观察。 要求:切割过程为CUTTING,引入线类型为直线(同时测试为半圆/四分之一圆的 情况),长度为8,角度为0[同时测试角度为90,来观察变化情况],无引出线。
练习二
查看<<练习2.CAM>>,对于这个图形应该只有18个实体,请检查为什么?
FASTCAM绘图模块(即桌面FastCAM图标) 掌握点: ⑴.点、线、弧的应用与学习 ⑵. 删除、修剪、块操作、显示、工具及文字的学习 ⑶. 文字、效验、标准件等操作及应用
一、绘图功能练习
一、绘图功能练习
二、 手动套料
1、 参数设置: (输入格式、输出格式、套料参数、手动套料菜单)
二、 手动套料
1、 参数设置: (板材设置、套排料保存和读取方式)
二、 手动套料
二、 手动套料
一、 自动套料
二、 自动交互式套料
手动套料练习
1、将《工件4.CAM》使用手动套排料方法后输出NC码,并观察。 要求:设置自动FastPATH 工艺。 2、将《工件3.DXF》使用手动套排料方法后输出NC码后,用FastPLOT观察切割顺序 ,切割中与变形情况,同时查看一下成本内容并做好记录等。 要求:设置自动FastPATH 工艺。
tutorial_basic_pp
Brillouin zone sampling BZ sampling is performed using 2 Chadi-Cohen special points for the fcc lattice. For an introduction to special points techniques see for instance A. Baldereschi, Phys. Rev. B 7, 5212 (1973). D.J. Chadi e M.L. Cohen, Phys. Rev. B 8, 5747 (1973). H.J. Monkhorst e J.D. Pack, Phys. Rev. B 13, 5188 (1976). check in the input file how k-points are provided manually k-points are given (default) in cartesian coordinates in unit of 2pi/celldm(1) k-point weights need not add-up to 1, they are normalized later
Quantum-ESPRESSO
Basic PostProcessing
What can I learn in this lecture ?
What can I learn in this lecture ?
How to get the band structure of Silicon along the main symmetry directions How to draw charge density map of Silicon in a given plane How to get an electronic Density of State plot for Silicon
DotSpatial_Tutorial_3
Raster Data Operations in DotSpatial Tutorial (2)Purpose of this tutorial: Become familiar with the following raster operations in DotSpatial:1. Loading different formats of raster data in DotSpatial.2. Implementing the hill shade.3. Change the color of the raster data.4. Multiply the raster data.5. Reclassify the raster data.6. Get the mouse clicked point values on the raster data layer.This tutorial has 5 important steps.Step 1: Download the DotSpatial class libraryStep 2: Add the DotSpatial reference and change the compile option.Step 3: Add the DotSpatial Controls into the Visual Studio Toolbox.Step 4: Copy the Data Extensions folder to the debugs folder of the current projectStep 5: Design the GUI. (GUI - Graphical User Interface)Step 6: Write the code for implementing the map operations.Step 1: Download the DotSpatial class libraryThis step is the same as Tutorial #1 step 1.Step 2: Add the DotSpatial reference and change the compile option.1.1) Adding the references.DotSpatial.Data.Forms.dll, DotSpatial.Symbology.dll, DotSpatial.Controls.dll, DotSpatial.Projections.dll, DotSpatial.Data.dll, DotSpatial.Topology.dllFig. 1 Required references.2.2) Change the compile option.Change the compile option from .Net Framework 4 Client Profile to .Net Framework4.This step is the same as the Tutorial # 1 step 2.2.Step 3: Add the DotSpatial Controls into the Visual Studio Toolbox.This step is the same as the Tutorial # 1 step 3.Step 4: Copy the Data Extension folder from your downloaded folder to your current project bin/debug folder. The .dlls from this folder is necessary for GDAL data provider access.Fig. 2 Data Extensions folder from DotSpatial downloaded unzip folderStep 5: Design the GUIDesign the GUI as follows:Fig. 3 Final GUIInterface design considerations.1. Add three panel controls. Panel control's properties should be as follows:Properties Panel1 Panel2 Panel3Name pnlOperations pnlLegend pnlMapDock Top Left Fill2. Add five buttons. Button properties should be as follows:Properties Button1 Button2 Button3 Button4 Button5 Name btnLoadRaster btnHillshade btnChangeColor btnMultiplyRaster btnReclassify Text &Load Raster &Hillshade Change &Color &Multiply Raster &ReclassifyRaster3. Add two label controls. Labels' properties should be as follows:Properties Label1 Label2Name lblElevation lblRasterValueText Elevation Row: Column: Value:4. Add a checkbox and it should have the following properties.Name: chbRasterValue Text : Raster value at clicked point5. Add a textbox and it should have the following features.Name: txtElevation Text: 30006. Drag a “Legend” control from the DotSpatial tab under toolbox and drop it on pnlLegend. Legend properties should be as follows:Name: Legend1 Dock: Fill7. Drag a “Map” control from the DotSpatial tab under toolbox and drop it on pnlMap. Map properties should be as follows:Name: Map1 Dock: Fill Legend: Legend18. Drag an "AppManager" control from DotSpatial tab under toolbox and drop it on the form. Note: This control is necessary for loading different formats of raster data.Fig. 4 AppManager9. Set the properties of AppManager1 as follows:Map: Map1 Legend: Legend1Step: 6 Loading the different formats of raster data.6.1) Import the following namespaces in the coding window.//Required namespacesusing DotSpatial.Symbology;using DotSpatial.Controls;using DotSpatial.Data;using DotSpatial.Topology;6.2 ) btnLoadRaster click event should be as follows:private void btnLoadRaster_Click(object sender, EventArgs e){//AddRasterLayer() method is used to load the raster layers on the mapmap1.AddRasterLayer();map1.ZoomToMaxExtent();}Implementing the hill shade.btnHillshade_Click event should have the following code.private void btnHillshade_Click(object sender, EventArgs e){if (yers.Count > 0){//IMapRasterLayer layer = (IMapRasterLayer)yers[0];IMapRasterLayer layer =yers[0] as IMapRasterLayer;if (layer == null){MessageBox.Show("Please select a raster layer");return;}layer.Symbolizer.ShadedRelief.ElevationFactor = 1;layer.Symbolizer.ShadedRelief.IsUsed = true;layer.WriteBitmap();}else{MessageBox.Show("Please add a layer to the map.");}}Change the color.btnChangeColor click event should has the following event.private void btnChangeColor_Click(object sender, EventArgs e){if (yers.Count > 0){//change the color of raster//typecast the first layer to MapRasterLayerIMapRasterLayer layer = yers[0] as IMapRasterLayer;if (layer == null){MessageBox.Show("Please add a raster layer.");return;}//set the color scheme//create an instance for a colorschemeColorScheme scheme = new ColorScheme();//create a new categoryColorCategory category1 = new ColorCategory(2500, 3000, Color.Red, Color.Yellow);category1.LegendText = "Elevation 2500 - 3000";//add the category to the color schemescheme.AddCategory(category1);//create another categoryColorCategory category2 = new ColorCategory(1000, 2500, Color.Blue, Color.Green);category2.LegendText = "Elevation 1000 - 2500";scheme.AddCategory(category2);//assign new color schemelayer.Symbolizer.Scheme = scheme;//refresh the layer display in the maplayer.WriteBitmap();}else{MessageBox.Show("Please add a layer to the map.");}}Multiply the raster.btnMultiplyRaster should has the following event.private void btnMultiplyRaster_Click(object sender, EventArgs e){if (yers.Count > 0){IMapRasterLayer layer = yers[0] as IMapRasterLayer ;if (layer == null){MessageBox.Show("Please select a raster layer");}IRaster demRaster = layer.DataSet;string[] rasterOptions = new string[1];IRaster newRaster = Raster.CreateRaster("multiply.bgd", null, demRaster.NumColumns, demRaster.NumRows, 1, demRaster.DataType, rasterOptions);//Bounds specify the cellsize and the coordinates of raster corner newRaster.Bounds = demRaster.Bounds.Copy();newRaster.NoDataValue = demRaster.NoDataValue;newRaster.Projection = demRaster.Projection;for (int i = 0; i <= demRaster.NumRows - 1; i++){for (int j = 0; j <= demRaster.NumColumns - 1; j++) {if (demRaster.Value[i, j] != demRaster.NoDataValue) {newRaster.Value[i, j] = demRaster.Value[i, j] * 2; }}}//save the new raster to the filenewRaster.Save();//add the new raster to the mapyers.Add(newRaster);}else{MessageBox.Show("Please add a layer to the map.");}}Reclassify the raster.btnReclassify should has the following event.private void btnReclassify_Click(object sender, EventArgs e){//typecast the selected layer to IMapRasterLayerIMapRasterLayer layer = yers.SelectedLayer as IMapRasterLayer ;if (layer == null){MessageBox.Show("Please select a raster layer.");else{//get the raster datasetIRaster demRaster = layer.DataSet;//create a new empty raster with same dimension as original rasterstring[] rasterOptions = new string[1];IRaster newRaster = Raster.CreateRaster("reclassify.bgd", null, demRaster.NumColumns, demRaster.NumRows, 1, demRaster.DataType, rasterOptions);newRaster.Bounds = demRaster.Bounds.Copy();newRaster.NoDataValue = demRaster.NoDataValue;newRaster.Projection = demRaster.Projection;//reclassify raster.// values >= specified value will have new value 1// values < specified value will have new value 0double oldValue = 0;//get the specified value from the textboxdouble specifiedValue = Convert.ToDouble(txtElevation.Text);for (int i = 0; i <= demRaster.NumRows - 1; i++){for (int j = 0; j <= demRaster.NumColumns - 1; j++){//get the value of original rasteroldValue = demRaster.Value[i, j];if (oldValue >= specifiedValue){newRaster.Value[i, j] = 1;}else{newRaster.Value[i, j] = 0;}}}newRaster.Save();yers.Add(newRaster);}}Get the mouse clicked point values on the raster data layer.Select the chbRasterValue's "CheckedChanged" event.fig.5 ChbRasterValue checkbox's checked changed event.chbRasterValue_CheckedChanged event should has the following events.private void chbRasterValue_CheckedChanged(object sender, EventArgs e) {if (chbRasterValue.Checked){IMapRasterLayer rasterLayer = yers.SelectedLayer as IMapRasterLayer ;if ((rasterLayer != null)){//set the map cursor to crossmap1.Cursor = Cursors.Cross;}else{//if no raster layer is selected, uncheck the checkboxMessageBox.Show("Please select a raster layer.");chbRasterValue.Checked = false;}}else{//change map cursor back to arrowmap1.Cursor = Cursors.Arrow;}}Select the Map1's mouse up event.fig.6 Map1_MouseUp eventmap1_MouseUp event should have the following code.private void map1_MouseUp(object sender, MouseEventArgs e){if (chbRasterValue.Checked){//get the layer selected in the legendIMapRasterLayer rasterLayer = yers.SelectedLayer as IMapRasterLayer;if ((rasterLayer != null)){//get the raster data objectIRaster raster = rasterLayer.DataSet;//convert mouse position to map coordinateCoordinate coord = map1.PixelToProj(e.Location);//convert map coordinate to raster row and columnRcIndex rc = raster.Bounds.ProjToCell(coord);int row = rc.Row;int column = rc.Column;//check if clicked point is inside of rasterif ((column > 0 & column < raster.NumColumns & row > 0 & row < raster.NumRows)){//get the raster value at row and columndouble value = raster.Value[row, column];//show the row, column and value in the labellblRasterValue.Text = string.Format("row: {0} column: {1} value: {2}", row, column, value);}else{lblRasterValue.Text = "outside of raster";}}}}Output screen shot for different operations.Fig.7 Load a raster dataFig.8 After the hill shade operationFig.9 After the color change operationFig.10 After the raster multiplicationFig.11 After the reclassify operationFig.12 Getting the mouse click point value on the raster data file.。
TSTutorial软件包说明书
Package‘TSTutorial’September4,2023Type PackageTitle Fitting and Predict Time Series Interactive LaboratoryVersion1.2.7Author Alberto Lopez MorenoMaintainer Alberto Lopez Moreno<*******************>Description Interactive laboratory of Time Series based in Box-Jenkins methodology.License GPL(>=2.0)Depends methods,grDevices,graphics,stats,tools,MASSEncoding UTF-8LazyData trueNeedsCompilation noRepository CRANDate/Publication2023-09-0415:10:06UTCR topics documented:TSTutorial-package (2)AirBcn (3)TSTutorial (3)Turismes (5)Victimes (6)Index712TSTutorial-package TSTutorial-package Time Series TutorialDescriptionTSTutorial packages is an implementation for learningfitting and getting predictions of Time Se-ries with the methology Box-Jenkins.This consist on an interactive laboratory showing differents menus which contain all the steps of the methodology.Furthemore,these menus,and its options, have some explanatory texts and suggestions(based in created tests)to facilitate the learning pro-cess.DetailsPackage:TSTutorialType:PackageVersion: 1.2.7Date:2023-09-04License:GPL(>=2)LazyLoad:yesDepends:methods,grDevices,graphics,stats,snowfall,MASSOverviewThe use of this package is very simple,to start the tutorial only is required a time series in the method TSTutorial.Moreover,the package includes three time series as data examples to use them with the function TSTutorial.Author(s)Author and maintainer:Alberto Lopez Moreno<*******************>See AlsoOverview:TSTutorial-package.Methods:TSTutorial.AirBcn3 AirBcn Monthly Airline Passenger Numbers1990-2009of BarcelonaDescriptionMonthly totals of international airline passengers of Barcelona,1990to2009.UsageAirBcnFormatA monthly time series,in thousands.SourceMinisterio de Fomento(www.fomento.es)Examplesdata(AirBcn)plot(AirBcn)TSTutorial Interactive Laboratory of Time SeriesDescriptionTSTutorial is an interactive laboratory for learningfitting and getting predictions from Time Se-ries.It consist on an ordered collections of menus where it is explained the Box-Jenkins methodology.The principal objective of the function is to be a useful tool in the process of learning this method-ology.Howerver,if you are an expert user who knows the Box-Jenkins methodology,you can use TSTutorial to work with your time series because it avoids you to write all the code.To know more how to use TSTtutorial you can read the vignette"Tutorial"of this package or directly read it executing the function and selecting the third option(3.Tutorial)of thefirst menu.UsageTSTutorial(series,student,report,contRep)4TSTutorialArgumentsseries Object of clase.ts(Time Series)student A logical which indicates if you want the student mode(T)or expert mode(F).See"Details".report A logical list which indicates if you want to get a report of the session after finish it,and more options.See"Details".contRep A list containing some parameters to modify parameters of the report,introduce an.texfile modified by the user,etc.See"Details"for more information. DetailsThe student has two options:T:the laboratory is for students.It shows help texts and suggestions to teach the Box-Jenkins method.F:the laboratory is for expert users.Only shows the basic information avoiding all the helps and suggestions.It is an useful tool for Time Series advanced users to avoid to write their own scripts.The report has three options:report:a logical value indicating(with the value T)to the program to create a.pdffile with the name of the time series introduced in TStutorial and it is saved in the current working directory.comment:a logical value inidicating(with the value T)to let to the user write comments during the session which will appear in the report.By default,and when report is F,its value is F.files:a logical value inidicating(with the value T)to not delete thefiles which are created during the report building process.In this case,the onlyfile created will be the.pdffile.By default,and when report is F,its value is F.The contRep has three options:fil:a logical value indicating(with the value T)whether the user set a new.texfile introduced in name.By default is F.name:the name of the.texfile which the head of the report is to be read from.By default is NULL.maingraph:The size of the graphics that are plotted in one column.twograph:The size of the graphics that are plotted in two columns.ValueNone(invisible NULL).Author(s)Author and maintainer:Alberto Lopez MorenoReferencesBox JenkinsTurismes5 See AlsoOverview:TSTutorial-package.Methods:TSTutorial.Examples#data(AirBcn)#TSTutorial(AirBcn)Turismes Monthly Made Vehicles in Spain1990-2008.DescriptionMonthly made vehicles in Spain,Genuary1990to August2008.UsageTurismesFormatA monthly time series,in thousands.SourceInstituto Nacional de Estadistica(www.ine.es).Examplesdata(Turismes)plot(Turismes)6Victimes Victimes Monthly Traffic Deads Number1993-2008of Spain.DescriptionMonthly totals of traffic deads in road and urban accidents of Spain,1993to2008.UsageVictimesFormatA monthly time series,in thousands.SourceDireccion General de Trafico(www.dgt.es)Examplesdata(Victimes)plot(Victimes)Index∗datasetsAirBcn,3Turismes,5Victimes,6∗packageTSTutorial-package,2[,cami,character,missing,missing-method(TSTutorial-package),2[,datos,character,missing,missing-method(TSTutorial-package),2[,lineal,character,missing,missing-method(TSTutorial-package),2[,menu,character,missing,missing-method(TSTutorial-package),2[,menuitem,character,missing,missing-method (TSTutorial-package),2[,modelo,character,missing,missing-method(TSTutorial-package),2[,report,character,missing,missing-method(TSTutorial-package),2[,serie,character,missing,missing-method(TSTutorial-package),2[,sessio.ts,character,missing,missing-method (TSTutorial-package),2[,tex,character,missing,missing-method(TSTutorial-package),2[<-,cami,character,missing-method(TSTutorial-package),2[<-,datos,character,missing-method(TSTutorial-package),2[<-,lineal,character,missing-method(TSTutorial-package),2[<-,menu,character,missing-method(TSTutorial-package),2[<-,menuitem,character,missing-method(TSTutorial-package),2[<-,modelo,character,missing-method(TSTutorial-package),2[<-,report,character,missing-method(TSTutorial-package),2[<-,serie,character,missing-method(TSTutorial-package),2[<-,sessio.ts,character,missing-method (TSTutorial-package),2[<-,tex,character,missing-method(TSTutorial-package),2 AirBcn,3TSTutorial,2,3,5TSTutorial,ts-method(TSTutorial),3 TSTutorial-method(TSTutorial),3 TSTutorial-package,2Turismes,5Victimes,67。
Vensim_PLE_中文教程 简体中文
Vensim ® PLE 快速参考与自学手册台湾科技大学摘要1.File(档案)与cutting/pasting(剪下/贴上) 的操作如微软窗口系统之功能‧2.许多功能列中经常使用的功能项目都放在工具栏的按钮,以利操作‧3.专门术语:”click”即按压鼠标左键再释放之‧”drag” 即按压鼠标左键不释放而移动鼠标‧”right-click” 即按压鼠标右键再释放之‧而”control-click” 即按ctrol键及按鼠标左键再释放之,结果与”right-click”相同‧4.Vensim使用默认变量,无论建立任何模块,系统自动建立必要变量而使用它;如标题栏的FINAL TIME变数‧________________________Copyright 2002, Craig W. Kirkwood. All rights reserved. (Email: craig.kirkwood@)Updated on December 12, 2002 by Jennifer Cihla Vender using VensimPLE Version 5.0c1Main Toolbar(工具栏)。
分析工具注意事项:1.若有较多的模拟执行,则分析工具是无法运作的。
因此,在实验中,必须仔细地追踪在窗口中所显示的结果。
2.大部分窗口显示有关工作变量的信息。
在窗口中选择一变量,用鼠标双击变量即成工作变量。
3.在分析工具所输出图形左上角功能列如右图,其中最左边的键是删除窗口键。
在其右边则是锁住删除功能键,再按一次则可恢复删除功能。
其右边则是打印机功能键可 以打印此窗口内容。
其右边键则是复制窗口至回纹夹。
最后键则是储存窗口内容于档案。
4.在图形内有多个曲线,这些曲线会使用不同颜色显示。
黑白打印机打印时很难区隔它,因此在Option 功能键,选择”Show Line Markers on Graph Lines”可以在曲线上标示不同数字以示区隔。
Tutorial_Guide_IGG_82_1-Acrov5
TutorialsIGG™ v8.aDocumentation v8.aNUMECA International5, Avenue Franklin Roosevelt1050 BrusselsBelgiumTel: +32 2 647.83.11Fax: +32 2 647.93.98Web: ContentsTABLE OF CONTENTINTRODUCTIONTUTORIAL 1: Geometry Creation1-1 INTRODUCTION1-11-1.1 Introduction1-11-1.2 Prerequisites1-21-1.3 Preparation1-21-2 CARTESIAN POINT1-31-2.1 Create Cartesian Point1-31-2.2 Select Cartesian Point1-31-2.3 Delete Cartesian Point1-31-3 CURVES1-31-3.1 Create Curves1-31-3.2 Select Curves1-51-3.3 Visualize Curves1-51-3.4 Modify Curves1-61-3.5 Edit/Copy Curves1-71-3.6 Export Curves1-71-3 SURFACES1-81-3.1 Create Surfaces1-81-3.2 Select Surfaces1-101-3.3 Visualize Surfaces1-101-3.4 Modify Surfaces1-111-3.5 Edit/Copy Surfaces1-111-3.6 Export Surfaces1-11 TUTORIAL 2: 2D Airfoil Mesh Generation2-1 INTRODUCTION2-12-1.1 Introduction2-12-1.2 Prerequisites2-22-1.3 Presentation2-22-1.4 Preparation2-22-2 MESH GENERATION2-32-2.1 Define Project Configuration2-42-2.2 Define Geometry2-52-2.3 Create Blocks2-62-2.4 Define Clustering2-112-2.5 Generate Face Grid2-142-2.6 Control Mesh Quality2-162-2.7 Define Boundary Conditions2-172-2.8 Save Project2-18ContentsTUTORIAL 3: Pipe to Pipe Mesh Generation3-1 INTRODUCTION3-13-1.1 Introduction3-13-1.2 Prerequisites3-23-1.3 Presentation3-23-1.4 Preparation3-23-2 MESH GENERATION3-33-2.1 Define Geometry3-33-2.2 Create & Control Blocks3-53-2.3 Generate Block Grid3-133-2.4 Define Butterfly Topology3-143-2.5 Control Mesh Quality3-163-2.6 Define Boundary Conditions3-183-2.7 Define Full Non Matching Connection3-193-2.8 Save Project3-20TUTORIAL 4: Volute Mesh Generation4-1 INTRODUCTION4-14-1.1 Introduction4-14-1.2 Prerequisites4-24-1.3 Presentation4-24-1.4 Preparation4-24-2 MESH GENERATION4-34-2.1 Load Geometry4-34-2.2 Create & Control Blocks4-44-2.3 Generate Block Grid4-184-2.4 Control Mesh Quality4-194-2.5 Define Boundary Conditions4-204-2.6 Define Full Non Matching Connection4-224-2.7 Save Project4-23TUTORIAL 5: Axi Seal Leakage Mesh Generation5-1 INTRODUCTION5-15-1.1 Introduction5-15-1.2 Prerequisites5-25-1.3 Presentation5-25-1.4 Preparation5-25-2 MESH GENERATION5-35-2.1 Define Project Configuration5-35-2.2 Import Geometry5-45-2.3 Create & Control Blocks5-45-2.4 Define Clustering5-105-2.5 Control Mesh Quality5-135-2.6 Define Boundary Conditions5-155-2.7 Save Project5-18What’s in This Guide ?This Tutorial Guide contains a number of tutorials driving the user in IGG™ v8 to mesh different internal and external configurations. In each tutorial, features related to mesh generation are dem-onstrated.Tutorials 1 to 5 are detailed tutorials designed to introduce the beginner to IGG™ v8. These tutori-als provide explicit instructions for all steps of the mesh generation process. Tutorials 1 to 5 do not require any pre-requisite and can be treated separately, in any order. They address different types of applications, including both internal and external cases.Where to Find the Files Used in the Tutorials ?Each of the mesh generation starts from a geometry that is existing or is created. The appropriate files (and any other relevant files used in the tutorial) are stored on IGG™ v8 DVD-ROM, more precisely in the /DOC/_Tutorials directory.How to Use this Guide ?Depending upon your familiarity with computational fluid dynamics and your interest in some par-ticular configuration, you can use this tutorial guide in a variety of ways.For the BeginnerIf you are beginning user of IGG™, you should first read and solve tutorials 1 and 2, in order to familiarize yourself with the interface and basis of the mesh generation technique. You may then want to concentrate on a tutorial that demonstrates features that you are going to resolve. For exam-ple, if you are planning to mesh a volute, you should look at tutorial 4.For the Experienced UserIf you are an experienced user of IGG™, you can read and/or solve the tutorial(s) that demonstrate features that you are going to resolve. For example, if you plan to mesh a 2D airfoil, you should look at tutorial 2.Conventions Used in this GuideSeveral conventions are used in the tutorials to facilitate your learning process.Following a short introduction, each tutorial is divided into sections respectively related to the mesh generation steps from the geometry definition to the 3D mesh generation.Inputs required to execute the tutorials are restricted to the geometry, either in a ".dat" or CAD related format.The sequence of actions to be executed are described through a step-by-step approach, in the form of arabic numbers.Additional insight about some specific actions and/or features is frequently added to illustrate the tutorial further. This information is proposed for the purpose of clarity and completeness, and should not be executed. It appears in italicized type.Contact NUMECA support team at +32-2-647.83.11 or send an e-mail to sup-port@numeca.be for any question or information you may require. To allowNUMECA support to help you out within the shortest delays, please provide adetailed description of the observed behaviour and performed analysis.TUTORIAL 1:Geometry Creation1-1Introduction1-1.1IntroductionThe resolution of computational fluid dynamics (CFD) problems involves three main steps:•spatial discretization of the flow equations,•flow computation,•visualization of the results.To answer these questions, NUMECA has developed a F low IN tegrated E nvironment for internaland Turbomachinery assimilations. Called FINE™/Turbo, the environment integrates the followingtools:•IGG™ is an I nteractive G eometry modeler and G rid generator software, based on structured multi-block techniques,•AutoGrid™ is a three-dimensional Automated Grid generation software, dedicated to turboma-chinery applications. Similarly to IGG™, it is based on structured multi-block techniques,•Euranus is a state-of-the-art multi-block flow solver, able to simulate Euler and Navier-Stokes equations in the laminar, transitional and turbulent regimes,•CFView™ is a highly interactive flow visualization and post-treatment software,•FINE™ Graphical User Interface is a user-friendly environment that includes the different soft-wares. It integrates the concept of projects and allows the user to achieve complete simulations,going from the grid generation to the flow visualization, without the need of file manipulation.This tutorial is particularly adapted to the creation and modification of geometrical entities. Itmakes exclusive use of IGG™.In this tutorial you will learn how to:•Create Cartesian point,•Create and modify curve entities,•Create and modify surface entities,•Select and delete geometrical entities,Geometry Creation Introduction•Group/ungroup geometrical entities,•Save geometrical entities.1-1.2PrerequisitesThis tutorial does not require any particular prerequisite.1-1.3Preparation•Copy the files located in cdrom:\DOC\_Tutorials\IGG\Tutorial_1 to your working directory, where cdrom must be replaced by the name of your DVD-ROM.•Start IGG™ v8.xFor LINUX and UNIX systems, you can access IGG™ v8.x graphical user interface with thefollowing command lineigg -niversion 8x -print or igg -niversion autogrid8x -printFor WINDOWS systems, you can access IGG™ v8.x graphical user interface from the startmenu going to /Programs/NUMECA software/fine8x/IGG or /Programs/NUMECA software/autogrid8x/IGGMenu BarTool Bar3D ViewQuick Access PadControl Areakeyboard input areainformation areaYou’re now ready to start to create and modify geometrical entities!IGG™ v8 graphical user interface allows to visualize the geometry and mesh of the internal orexternal test case in a 3D view by default. The access to main menu and controls is proposedthrough a menu bar and a quick access pad, and is completed with a tool/icon bar and a control area(including the keyboard input area).Cartesian Point Geometry Creation1-2Cartesian Point1-2.1Create Cartesian Point1.Select the Geometry/Create Points/Cartesian Point menu to initiate the creation of aCartesian point2.Type the sequence <1 1 0> <Enter> in the keyboard input area. This action will create theCartesian point (black or white point is appearing in the graphics area)Cartesian points can also be defined as intersection between two selectedcurves or between a selected curve and a plane or between a selected curveand a surface (see User Manual for more details).3.Select the Geometry/Create Points/Cartesian Point menu to initiate the creation of a sec-ond Cartesian point4.Type the sequence <1 1 1> <Enter> in the keyboard input area. This action will create thesecond Cartesian point (second black or white point is appearing in the graphics area) 1-2.2Select Cartesian Point5.Select the Geometry/Select/Cartesian Points menu to select Cartesian points6.Move the mouse on the Cartesian point (1,1,1) and click-left on it when highlighted in blueto select it7.Click-right or <q> in the graphics area to end the selection1-2.3Delete Cartesian Point8.Select the Geometry/Delete/Cartesian Points menu to delete the selected Cartesian points(highlighted in blue)1-3Curves1-3.1Create CurvesThe following section describes how to:—create basic curves—use the keyboard or the mouse to input points—use the attraction featureThe below geometry, consisting of two polylines, one C-spline and one arc, will be created.Geometry Creation Curves9.Define a polyline curve:•Select the Geometry/Draw Polyline/Free menu (shortcut <p >) to initiate the creation of a polyline•Type the sequence <1 0 0> <Enter > in the keyboard input area . This action will create thefirst point of the polylineThe keystrokes are automatically echoed in the keyboard input area.•Enter a second point at position <1.2 0.5 0> and press <Enter >•Move the mouse near the Cartesian point. When close enough, the mouse will normally beattracted to this point if the attraction to points feature is enabled. If there is no attraction,press <a > in the graphics area. Then click-left to add this point to the polyline•Click-right or <q > in the graphics area to end the polyline creation•Repeat above steps to create another polyline passing through the points (0,0,0), (-0.2,0.5,0)and (0,1,0)10.Define a C-spline curve:•Select the Geometry/Draw CSpline/Free menu (shortcut <c >) to initiate the creation of aC-spline curve•Move the mouse near the point (0,0,0) of the second polyline. When close enough, themouse will normally be attracted to this point if the attraction to points feature is enabled. If there is no attraction, press <a > in the graphics area. Then click-left to add this point to the C-spline•Move the mouse somewhere between the points (0,0,0) and (1,0,0) and click-left to add apoint•Move the mouse near the point (1,0,0) of the first polyline. When close enough, the mousewill normally be attracted to this point if the attraction to points feature is enabled. If there is no attraction, press <a > in the graphics area. Then click-left to add this point to the C-spline•Click-right or <q > in the graphics area to end the C-spline creation11.Define a circular arc curve:•Select the Geometry/Circular Arc/Normal-Point-Point-Radius menu option to initiatethe creation of a circular arc. Several inputs will be requested to define the arcThe circular arc can be created using different methods (see User Manual for more details).•Enter <0 0 1> <Enter > to define the arc normalpolyline 1polyline2C-splinearcCurves Geometry Creation •Move the mouse near the Cartesian point. When close enough the point will be highlighted (if there is no attraction, press <a> in the graphics area). Click-left to define the arc startpoint•Move the mouse near the point (0,1,0) of the second polyline. When close enough the point will be highlighted (if there is no attraction, press <a> in the graphics area). Click-left todefine the arc end point•Enter <0.6> <Enter> to define the arc radius•Press <o> until the circle has the same shape as the one presented on above figure. Then click-left to create the arcClick-right or <q> in the graphics area to end the arc creation.1-3.2Select CurvesThe curve selection operation is used to activate one or more curves for subsequent operations ingeometry modelling or grid generation. When a curve is selected it appears highlighted in yellow(default). All the curves created in the previous steps are selected.12.Select the Geometry/Select/Curves option to initiate curve(s) selectionThe shortcut <s> can also be used to activate the option without accessing themenu.13.Press <a> to unselect all the curves, which become unhighlighted14.Move the mouse over the C-spline which is then highlighted. At the same time, the name,type of curve and approximate arc length of the curve appear in the information area15.Click-left to select it16.Repeat above step to select the first created polyline17.Click-right to quit the selectionSelection and deselection of all curves can be done by pressing <a> repeat-edly (toggle option).1-3.3Visualize CurvesWhen importing complex models, many curves may be created and visualized in IGG™, makingthe graphics unclear. It is possible to visualize only specific curves on the screen, hiding all others,in the following way:18.Select the Geometry/View/Curves option. A curve chooser appears with the name of allthe curves. All the names are highlighted since all the curves are visible19.Select the C-spline in the chooser (click-left on it) and press Apply. Only the C-splinecurve now appears in the view20.Select the first polyline in the chooser (click-left on it) while holding the <Ctrl> key. Thepolyline is highlighted in the chooser, together with the C-spline. Press Apply to visualizeboth curves21.Select the first and last curves in the chooser while holding the <Shift> key. All the curvesare now selected. Press Apply to visualize them all22.Close the chooserAfter selecting the curves by using the Geometry/Select/Curves menu, the selected curves can befurther investigated in the following way:Geometry Creation Curves23.Select the Geometry/View/Curve Orientation menu. The default orientation of theselected curves is shown. This orientation is important for other geometry modelling andgrid generation operations. These orientations can be hidden by selecting the menu onceagain (toggle option)24.Select the Geometry/View/Control Points menu. The control points of the selected curvesappear now. This options acts as a toggle (display on-off) on all selected curves25.Select the Geometry/Select/Control Points menu. A control point must be selected. Whenmoving the mouse near a control point, the point becomes highlighted. Click-left on a con-trol point to display the point coordinates in the information area26.Click-right to quit the option27.Select the Geometry/Distance menu (). A prompt appears to select two points betweenwhich the distance will be measured and displayed:•Press <c> to disable the attraction to curves (this can be verified by moving the cursor near the start point of the C-spline. Normally, there is no attraction to the curve. Otherwise, press<c> a second time)•Move and attract the cursor over the start point of the C-spline. If there is no attraction, press <a>. Click-left on curve to select the start point•When moving the mouse, the distance between the selected point and the cursor is indi-cated. Move the mouse over the last point of the C-spline. The cursor is attracted to thepoint and the distance is indicating d=1•Click-left to fix the distance on the screenThe above steps can be repeated to measure the distance between otherpoints.•Click-right to quit the option.1-3.4Modify CurvesExisting selected curves can be modified within IGG™ in the following way:28.Select the Geometry/Modify Curve/Add Control Point option to add control points onselected curve by click-left on itCurves Geometry Creation29.Select the Geometry/Modify Curve/Remove Control Point option to remove a controlpoint on selected curve by click-left on control point30.Select the Geometry/Modify Curve/Modify Point (On surface) option to move an exist-ing control point on selected curve (on surface) by click-left to select the point and click-left after moving the control point31.Select the Geometry/Modify Curve/Set Name... option to impose a userdefined name tothe selected entity (one curve should be selected)32.Select the Geometry/Modify Curve/Divide option to split the selected curve at a userde-fined location by click-left on it (one curve should be selected)33.Select the Geometry/Modify Curve/Reverse option to reverse the curve orientation plot-ted when selecting Geometry/View/Curve Orientation menu1-3.5Edit/Copy CurvesExisting selected curves can be moved or copied within IGG™ in the following way:34.Select the Geometry/Select/Curves menu to select all the curves (highlighted in yellow)35.Select the Geometry/Edit/Copy menu to copy all the selected entities with a translation,rotation, scaling or mirror operation36.Type <new> <Enter> to impose a userdefined prefix to the geometrical entities that will becreated37.Type <t> <Enter> to select a copy with a translation38.Type <1 0 0> <Enter> to impose the translation vectortranslation (1 0 0)The menus Geometry/Edit/Translate, Rotate, Scale or Mirror allow to moveand not to copy the selected geometry.1-3.6Export CurvesIt is possible to save during the work the curves created in the previous steps. Only the curvesselected are saved into a file:39.Select the Geometry/Select/Curves menu to select all the curves (highlighted in yellow)Geometry Creation Surfaces40.Select File/Export/Geometry Selection... menu. A file chooser is opened to specify the name of a file ".dat" (with corresponding Parasolid ™file "X_T"). This file can be readback using the File/Import/IGG Data... menu ().1-4Surfaces 1-4.1Create Surfaces In this section simple surface creation is described, starting from a set of curves. A new session will be opened to clear all previous drawings.41.Select File/New - yes to close the current project and open a new, empty, project.Opening a new project closes the current project without automatic saving.42.Define a lofted surface:•Select File/Import/IGG Data and choose the file "geometry_curves.dat" in the\DOC\_Tutorials\IGG\Tutorial_1 directory of the installation cdrom. Three curves are readand stored in the geometry repository•Select the curves using Geometry/Select/Curves (<s >) in the order indicated on the figure•Verify that the curves are well oriented by using the Geometry/View/Curve Orientationmenu otherwise you need to reverse the curves by using the Geometry/Modify Curve/Reverse menu in order to impose the same orientation to all the curves•Select the Geometry/Surface/Lofted menu in the Quick Access Pad . A NURBS surface,interpolating the curves is now created. Notice that two new curves, representing surfaceboundaries, are created. These curves automatically appear in the curve chooser (Geome-try/View/Curves ) when it is opened123Boundary curves automatically created1234Surfaces Geometry Creation43.Define a coons patch:A Coons surface is a surface interpolating 4 boundary curves using a bilinearinterpolation. To avoid overlapping with the lofted surface, the selected curveswill be copied and translated.•Select the four boundary curves (<s>) of the lofted surface, in the order indicated in the above figure•Select the Geometry/Edit/Copy menu in the Quick Access Pad. IGG™ interrogates whether the duplicated curves must be translated, rotated, scaled, mirror or not. To avoid overlappingwith the existing curves and surface, a translation will be performed•Type <new> <Enter> to impose a userdefined prefix to the geometrical entities that will be created•Type <t> <Enter> to select a copy with a translation•Type <1 1 1> <Enter> to impose the translation vectorThe selected curves are duplicated and the new curves are automaticallyselected (the other curves are now unselected)•Select the Quick Access Pad/Geometry/Surface/Coons menu. A new surface is created which interpolates the four selected curvesIt can be noticed that 4 additional curves have been created. These are curves following the parametricdirections of the surface and are used to provide a better visualization of the surface.44.Define a surface of revolution:A surface of revolution will be created by rotating a newly created curve aroundthe Y axis.•First create a C-spline (Geometry/Curve/CSpline) between the points (-0.5,-2,0.1), (-0.5,0,0.2) and (-0.5,2,0.1). These points were selected so that the surface of revolution thatwill be created intersects the lofted surface•Make this curve the only selected curve (Geometry/Select/Curves)•Select Geometry/Surface/Revolution in the Quick Access Pad to create a surface of revolu-tion by rotating this new curve around a line parallel to the Y axis. The rotation origin is takenso that the surface of revolution intersects the lofted surface•Type <0 1 0> <Enter> to select the rotation axis direction•Type <-0.5 0 -1> <Enter> to select the rotation axis origin•Type <300> <Enter> to select the angle of rotationGeometry Creation SurfacesAs it may be noticed, the curve used for the rotation constitutes the first boundary of the surface.Three other boundary curves are automatically created to delimitate the surface.1-4.2Select SurfacesThe surface selection operation is used to activate one or more surfaces for subsequent operations in geometry modelling (i.e surface-surface intersection) or grid generation (i.e. face grid mapping).When a surface is selected its boundary curves appear highlighted in red or yellow.45.Select the Geometry/Select/Surfaces menu to initiate surface(s) selectionThe <Ctrl-s> shortcut can also be used to activate the same option, withoutaccessing the menu.46.Press <a > to unselect all the surfaces (toggle option), which become unhighlighted (bound-ary curves are unhighlighted)47.Move the mouse over the lofted surface. The surface becomes highlighted in blue.48.Click-left to select the surface. The boundary curves remain now permanently in red or yel-low49.Repeat above steps to select the surface of revolution50.Click-right to quit the selectionSelection and deselection of all the visible surfaces can be done by pressing<a> repeatedly (toggle option).1-4.3Visualize SurfacesSurfaces stored in IGG ™ are by default visualized by displaying their boundaries. As soon as the boundary curves of a surface are visible, the surface is considered visible. The following step describes how to hide surfaces, hence hide their boundaries.51.Select the Geometry/View/Surfaces option. A surface chooser appears with the name ofall the surfaces in the geometry repository. All surfaces in the chooser are highlighted sincethey are all visible in the graphics area52.Select the lofted surface (click-left on it) in the chooser and press Apply . The lofted surface appears alone in the graphics area with all the previously created curvesboundary curvesSurfaces Geometry Creation53.Select the surface of revolution (click-left on it) in the chooser while holding the <Ctrl> key.The surface of revolution is highlighted in the chooser together with the lofted surface. PressApply to visualize both surfaces. Notice that the surface of revolution is now unselected inthe graphics area (highlighted in blue)54.Select the first and last surfaces (click-left on them) in the chooser while holding the <Shift>key. All surfaces are highlighted in the chooser. Press Apply to visualize them all in thegraphics area55.Close the chooser1-4.4Modify SurfacesWhen manipulating parametric surfaces, it is possible to create curves in the parametric directions ofthe surfaces. These curves can be used to better visualize the surfaces or for other geometry and gridmodelling operations.56.After selecting a surface, select the Geometry/Modify Surface/Representation menu.IGG™ requests the number of curves to be created in the u and v direction of each selectedsurface:•Type <15 15> <Enter> to plot 15 curves in both parametric directions of the selected surfaces•Repeat the previous step and specify 5 curves in each direction57.Select the Geometry/Modify Surface/Add uv Curves menu. Then a point must be selectedon the selected surfaces:•Move the mouse inside the limits of the selected surfaces. Two orthogonal curves appear at the mouse position. The attraction feature can be enabled, if needed•Click-left to add the two curves in the geometry repositoryThe curves created in the above steps are deleted when the surface is deleted,except if they are used by other entities.1-4.5Edit/Copy SurfacesExisting selected surfaces can be moved or copied within IGG™ as presented on the curves in section1-3.5.1-4.6Export SurfacesIt is possible to save during the work the curves and surfaces created in the previous steps. Only thecurves and surfaces selected are saved into a file:58.Select the Geometry/Select/Curves and Surfaces menu to select respectively the curves(highlighted in yellow) and the surfaces (highlighted in red or yellow)59.Select the File/Export/Geometry Selection... menu. A file chooser is opened to specify thename of a file ".dat" (with corresponding Parasolid™ file "X_T"). This file can be read backusing the File/Import/IGG Data... menu ()Geometry Creation SurfacesTUTORIAL 2:2D Airfoil MeshGeneration2-1Introduction2-1.1IntroductionThe resolution of computational fluid dynamics (CFD) problems involves three main steps:•spatial discretization of the flow equations,•flow computation,•visualization of the results.To answer these questions, NUMECA has developed a F low IN tegrated E nvironment for internaland Turbomachinery assimilations. Called FINE™/Turbo, the environment integrates the followingtools:•IGG™ is an I nteractive G eometry modeler and G rid generator software, based on structured multi-block techniques,•AutoGrid™ is a three-dimensional Automated Grid generation software, dedicated to turboma-chinery applications. Similarly to IGG™, it is based on structured multi-block techniques,•Euranus is a state-of-the-art multi-block flow solver, able to simulate Euler and Navier-Stokes equations in the laminar, transitional and turbulent regimes,•CFView™ is a highly interactive flow visualization and post-treatment software,•FINE™ Graphical User Interface is a user-friendly environment that includes the different soft-wares. It integrates the concept of projects and allows the user to achieve complete simulations,going from the grid generation to the flow visualization, without the need of file manipulation.A C-type block grid around an airfoil is proposed to explain the basic features of the major topol-ogy and grid generation modules within IGG™.The tutorial shows the successive steps that must be followed to generate a 2D mesh and to definethe boundary conditions required before starting a solver:•Set up a 2D project,•Import/Create geometry curves needed for meshing,•Define the topology before meshing,。
Tutorial 使用指南
使用指南(Tutorial)修订版序从首次接触这个软件到现在,有一段时间了。
那时由于急着使用,因此对一些认为不太重要的地方没有进行整理。
后来才发现,其实每一部分都是很有用的。
此修订,一个是将LineSim(Tutorial)与后加的Crosstalk(Tutorial)的目录统一起来,再有就是原文基础上增加了多板仿真(Tutorial)一节。
同样,对于那一时期我整理的BoardSim 、LineSim使用手册,也有同样的一个没有对一些章节进行翻译整理问题(当初认为不太重要)。
而实际上使用时,有一些东西是非常重要的,同时也顺便进行了翻译。
此外,通过使用,对该软件有了更多一些理解,显然以前只从字面翻译的东西不太好理解,等我有时间将它们重新整理后,再提供给初学的朋友。
对在学习中给予我大量无私帮助的Aming、pandajohn、lzd 等网友表示忠心的感谢。
P o q i0552002-8-202002-8-20目录使用指南(TUTORIAL ) 1 第一章 LINESIM4 1.1 在L INE S IM 里时钟信号仿真的教学演示 4 第二章 时钟网络的EMC 分析 7 2.1 对是中网络进行EMC 分析7 第三章 LINESIM'S 的干扰、差分信号以及强制约束特性 8 3.1 “受害者”和 “入侵者” 8 3.2如何定线间耦合。
8 3.3 运行仿真观察交出干扰现象9 3.4 增加线间距离减少交叉干扰(从8 MILS 到 12 MILS ) 93.5 减少绝缘层介电常数减少交叉干扰 93.6 使用差分线的例子(关于差分阻抗) 93.7仿真差分线 10第四章 BOARDSIM114.1 快速分析整板的信号完整性和EMC 问题 11 4.2 检查报告文件 11 4.3 对于时钟网络详细的仿真 11 4.4 运行详细仿真步骤: 11 4.5 时钟网络CLK 的完整性仿真 12 第五章 关于集成电路的MODELS 145.1 模型M ODELS 以及如何利用T ERMINATOR W IZARD 自动创建终接负载的方法 14 5.2 修改U3的模型设置(在EASY.MOD 库里CMOS,5V,FAST ) 14 5.3 选择模型(管脚道管脚)C HOOSING M ODELS I NTERACTIVELY (交互), P IN -BY -P IN 14 5.4 搜寻模型(F INDING M ODELS (THE "M ODEL F INDER "S PREADSHEET ) 15 5.5 例子:一个没有终接的网络 15 第六章 BOARDSIM 的干扰仿真 186.1 B OARD S IM 干扰仿真如何工作 186.3仿真的例子:在一个时钟网络上预测干扰 18 6.3.1加载本例的例题“DEMO2.HYP” 18 6.3.2A UTOMATICALLY F INDING "A GGRESSOR"N ETS 18 6.3.3为仿真设置IC模型 19 6.3.4查看在耦合区域里干扰实在什么地方产生的 19 6.3.5驱动IC压摆率影响干扰和攻击网络 20 6.3.6电气门限对比几何门限 20 6.3.7用交互式仿真"CLK2"网络 20 6.4快速仿真:对整个PCB板作出干扰强度报告 20 6.5运行详细的批模式干扰仿真 21第七章关于多板仿真237.1多板仿真例题,检查交叉在两块板子上网络的信号质量 23 7.2浏览在多板向导中查看建立多板项目的方法 24 7.3仿真一个网络A024 7.4用EBD模型仿真24HyperLynxHyperLynx是高速仿真工具,包括信号完整性(signal-integrity)、交叉干扰(crosstalk)、电磁屏蔽仿真(EMC)。
tutorial 中文手册2.2
感 谢本tutorial Manual 2.2翻译文档在许多网友的关心和支持下,得以翻译成功,在此对他们表示热烈地感谢:蝈蝈、fiona、kailinziv、Yan、杀毒软件、tiny0o0、timothy、prolee等关心TG手册翻译的热心朋友。
关于本文档内容说明:由于本手册由不同网友翻译,可能对某些概念有不同的理解,翻译可能不大一样,但决不影响理解,欢迎大家探讨。
再一次对各位网友的努力和汗水表示感谢!如有什么问题可以联系我:Mail:tiny0o0@注:本文档内容版权归X Y Z scientific company 所有,谢绝任何意图商用。
I、TrueGrid介绍True Grid是一套优秀的、功能强大的通用网格生成前处理软件。
它可以方便快速生成优化的、高质量的、多块结构的六面体网格模型。
作为一套简单易用,交互式、批处理前处理器,True Grid支持三十多款当今主流的分析软件。
True Grid是基于多块体结构(multiple-block-structured)的网格划分工具,尽管这个指南手册开始会提供一些介绍信息,新手还是强烈要求阅读用户手册(True Grid® User’s Manual)的前2章,用户指南和参考手册。
True Grid是几何和网格形成过程是分开进行。
曲面和曲线形成的方式有以下几种:内部产生,从CAD/CAE系统导出IGES格式导入TG,或用vpsd命令导入多边曲面。
块网格(block mesh)初始化然后通过各种变换与几何模型匹配形成最后的有限元模型。
True Grid网格划分过程:运用block命令初始化块网格;块网格部分会被删掉以使拓扑结构与划分目标对应;块网格部分通过移动,曲线定位,曲面投影等方法进行变换;网格插值、光滑和Zoning(控制边界节点分布)等技术可以用来形成更好的网格;块网格之间独立形成,然后通过块边界面(BB)和普通节点合并命令(指定容差范围内合并)将各块网格合并成完整的有限元模型。
ansys_tutorial
– SELECT
– RESELECT
– ALSO SELECT
– UNSELECT
– INVERT
– SELECT ALL
– SELECT NONE
Specogna Ruben – ANSYS Tutorial
10
Selezione 2/2
• Provate a selezionare ad Entità esempio l’area 12 e 14
• Si puòapplicate un diverso infittimento per ogni indice materiale
– vsel,s,mat,,2 – smrtsize,2 – vmesh,all – vsel,s,mat,,1 – smrtsize,7 – vmesh,all – eplot
• Lo script èun semplice file di testo ASCII che contiene una lista di comandi
• Una volta salvato il file con un qualsiasi editor di testi lo si può eseguire attraverso FILE->Read Input from…
Nodi
– asel,s,,,12
Elementi
– asel,a,,,14
Keypoints Linee
– S sta per SELECT
Aree Volumi
– A per ALSO SELECT
Componenti
Comando base
NSEL ESEL KSEL LSEL ASEL VSEL CMSEL
LIGGGHTS_Tutorial
LIGGGHTS_TutorialLIGGGHTS is a simulation code for conducting Discrete Element Method (DEM) simulations of granular materials. Unlike some commercial codes, LIGGGHTS is not driven by a graphical user interface. Rather, the user drives the simulation by assembling a text-based input deck consisting of a series of commands to conduct the simulation. The input deck is read sequentially, so ordering of statements is important.A LIGGGHTS input script typically has four parts:1.InitializationSet the parameters that need to be defined before particles are created2.SetupDefine the material properties, particles, geometry, and particle generation3.Detailed SettingsDefine some settings that correspond to speed and memory utilization, output options, etc.4.ExecutionThe actual run command that executes the simulationNote that there are two basic types of statements in a LIGGGHTS input deck – individual commands and fixes. The individual commands establish basic settings for the simulation, while the fixes are used to set particular aspects of the simulation. Generally, fixes (and a few commands, e.g. region) follow a common structure offix ID group-ID style argsID = user assigned name for the fixgroup-ID = ID of the group of atoms to which the fix is appliedstyle = type of fix being appliedargs = arguments used by a particular style; often consists of a keyword and corresponding valueIn this tutorial, we will step through a few input decks to describe the commands and fixes to run each simulation. This tutorial is not intended to cover all possible situations and commands, but rather, to try to describe some common elements in a LIGGGHTS simulation and to provide a starting point for users to develop their own simulations. For additional or more specific information about options for each statement, please see the documentation.Finally, at the end of this report, we provide some ‘best practices’ that have been collected over the past few years to try to help the reader avoid some common mistakes and to achieve the maximum performance out of the simulation.Example 1 – Bin flowA cylindrical hopper was initially filled with a set of spherical particles which were allowed to settle under the influence of gravity. The bottom of the hopper was then opened and the material was allowed to pour from the hopper.Example 2 – Continuous Blending MixerA continuous blending mixer is simulated in which a stream of particles enters at one end and is continuously blended as it travels down the length of the bed before discharging through a chute at the other end of the unit. We consider different feed rates and different impeller rotation rates. Material is fed into the simulation via a constant mass flowrate stream at one end of the unit, and is removed through a chute at the other end.Example 3 – Couette cylinderA Couette cylinder with axial flow, based on work by Kheiripour et al1, is depicted in the figure below. The device is intended to look at the rheological behaviour of a granular flow and to permit study of the tendency for material to segregated based on particle size. In these simulations, we have randomly inserted two different particle sizes (particles are otherwise identical) over a one second interval. The stopper at the bottom of the hopper is then pulled and material flows through a periodic z-boundary condition to flow back into the top of the unit. In doing so, the net mass in the system remains constant. Simultaneously, the drum in the center of the unit rotates about its axis, setting up a shearing action inside the cylinder.1Study of powder flow patterns in a Couette cell with axial flow using tracers and solid fraction measurements, M. Kheiripour Langroudi, P. R. Mort, Gi. I. Tardos, Granular Matter, Oct 2011, Vol 13, Iss 5, pp 541-552# Gravityfix grav all gravity 9.81 vector 0.0 0.0 -1.0# Timesteptimestep 0.00000625# Thermodynamic output settingsthermo_style custom step atoms ke cputhermo 8000thermo_modify lost ignore norm no# Check timestepfix timecheck all check/timestep/gran 1 0.01 0.01run 1unfix timecheck# Dump output#dump dmp all custom 16000 dump.1 id type type x y z ix iy iz vx vy vz fx fy fz & omegax omegay omegaz radius#dump dumpstl all stl 16000 dump*.stl#dump dmp2 all custom 16000 dump.txt type x y z radius### Execution and further settings# Run 1.0 sec to insert and settle particlesrun 160000 upto# Remove the stopper and start the rotationunfix geometryfix geometry all wall/gran/hertz/history mesh n_meshes 3 meshes cad1 cad2 cad3 & rolling_friction cdtfix movecad all move/mesh mesh cad2 rotate origin 0. 0. 0. axis 0. 0. 1. period 1. # Run 30 secrun 4800000Example 4 – 1-Way Flow CouplingA narrow slot is filled by a stream of particles falling near one side, with the flow passing across a narrow jet of air. The air stream causes the particles to blow towards the opposite end of the slot and creates a pile against the far wall.In this example, we’ve designed the stream force to be added via the ‘fix addforce’ command. Using this command, we have designated a small region of space immediately below the inlet stream of particles that causes all particles that enter the region to experience a body force that pushes them laterally. While we’ve used a simple constant force in this example, it is also possible to use variable quantities for the force to represent more complicated flow fields. In addition, the force can be applied to certain groups of particles.While this flow treatment is obviously reduced in fidelity from a truly coupled CFD-DEM simulation, it does provide a simple way to at least include some influence of an external flow field. Thus, for situations in which the particles do not significantly alter the flow field, we can use CFD to determine the flow field in the absence of the solid phase, and then apply this flow field to the DEM simulations to better understand the actual particle dynamics. One could envision using this to model the segregation due to drag forces acting on different sized particles.timestep 0.00001# Thermo settingsthermo_style custom step atoms ke cputhermo 10000thermo_modify lost ignore norm nocompute_modify thermo_temp dynamic yes# Run 1 step to check timestep and initializefix ctg all check/timestep/gran 1 0.01 0.01run 1unfix ctg# Dump particle positionsdump dmp all custom 100 dump.1 id type type x y z ix iy iz vx vy vz fx fy fz & omegax omegay omegaz radius### Execution and further settings# Run remainderrun 200000 uptoExample 5 – Shear CellThis simulation is designed to highlight the use of the servo-controlled wall, in which a geometric construct can move in response to a collision with a particle. Typical walls in a DEM simulation are assumed to be immune to the influence of particle impacts, and so wall motions must be completely prescribed. Using the servo wall allows us to consider additional systems, such as the shear cell shown here, in which the wall position is determined by a combination of a subjected load and impacts with the particles.An annular ring was initially filled with two sets of spherical particles (red = 4 mm diameter and blue = 6 mm) which were allowed to settle under the influence of gravity. The particles were filled sequentially with the larger blue particles on the bottom, followed by the red particles on top. After the cell is filled, an annular lid is lowered onto the top of the cell and held with a load on top. The lid is allowed to move in the z-direction in response to stresses imparted by the particles and the load on top. Once the lid has been placed, the bottom of the ring is slowly rotated to create a shear field and instigate segregation. Once the shearing action starts, the smaller particles percolate down through the layer of larger particles, causing the material to vertically segregate.Best PracticesStabilityKeep the timestep below 20% TR for stability. Use the fix_check_timestep_gran to ensure that your timestep is not too large.Use ‘thermo modify lost ignore’ for continuous processes in order to allow the simulation to ignore particles that leave the simulation domain. Otherwise, the simulation will shut down once the firstparticle is lost.In conjunction with the previous note, do not ignore lost particles for batch processes as a lost particle is an indication that the simulation isn’t stable.Pay attention to the kinetic energy and cpu time in your thermo output.o If the kinetic energy is jumping about violently, it is an indication that the timestep may be too large. This could result in a particle deeply penetrating another body during the course of onetimestep, resulting in a huge repulsive force and high corresponding kinetic energy in the nextstep.o The cpu time per step should remain fairly constant when at equilibrium, and should follow a fairly smooth progression when filling a system. If the time/step suddenly starts to increasedramatically during filling, it is an indication that something is blocking the feed zone andpreventing you from achieving the desired fill rate. This may also manifest as warnings thatfewer particles were inserted than desired.Particle generationIf you see warnings that the simulation was unable to insert the desired amount of particles, it is an indicator that you are trying to feed too aggressively. To counter this, either (1) decrease the feed rate,(2) increase the size of the insertion zone, or (3) increase the initial velocity of the particles so they clearthe zone more quickly.o The insertion zone is often limited by the size of the geometry. In cases where it is not, it can sometimes be tempting to enlarge the zone dramatically to ease particle insertion. However,this can cause two problems. First, if the zone is large in the direction of gravity, particles mayaccelerate to sufficiently high velocities so as to cause stability problems where a particle willimpact another body at too high of a speed to be handled by the base timestep. Second, it mayforce you to expand the domain of the simulation, which can slow the simulation down(depends on processor assignment).o Setting the initial velocity too high can lead to stability problems as described above.If the simulation initially inserts particles without issue, but then starts to suffer problems where it is unable to insert the desired number of particles, it is an indication that something is now obstructing the insertion zone. Most likely is that the previously inserted mass has backed up or formed a pile that isnow intruding into the insertion zone.It is generally a good idea to make sure a batch system is fully enclosed so as to avoid losing particles during the simulation. However, the presence of a lid can limit the ability to insert particles. If the lid is inserted as a separate object, it can be moved about before and after the particle insertion to facilitate the filling operation, or simply added to the system afterall particles have been added.Using different material types for different groups of particles, even if all of the material properties are identical, can be a convenient way to identify particles and groups of particles during post-processing.This is especially true for mixing problems.Of the three insertion methods (pack, rate/region, and stream), it is recommended to use the rate/region or stream methods. The pack method relies on being able to fill a volume with a largenumber of particles at one time via random sequential addition, which will typically fill a volume to no more than 30%. This can make it difficult to achieve the desired number of particles and will often leavea large empty space in the simulation domain that reduces the efficiency of parallelization. Using therate/region or stream options allows you to use a much smaller insertion volume and insert materialover time. Rate/region is preferred in general over stream solely because the user can define theinsertion region from within the input deck and does not require the user to create and import some external CAD. That said, sometimes (e.g. filling an annular ring) is accomplished far more efficiently with the rate/stream option.GeometryUse a simple mesh, even w/ high-aspect ratio triangles. Tests thus far indicate no difference in accuracy of results (disclamer – more testing is needed here, especially for stress calculations!) between using a coarse mesh as generated directly from a CAD program, and using a fine mesh as generated by a toolsuch as gmsh.o The high-aspect ratio triangles may diminish the ability to parallelize the geometry, but if there are significantly fewer facets than a fine description, you may end up saving more time in thelong run. In many simulations, the number of particles will far exceed the number of facets inthe geometry, and so parallelizing the geometry isn’t as critical.Simplify the geometry to avoid including parts that will never touch the particles (e.g. the motor that drives a mixer). Simplify geometry to avoid very small curved surfaces if possible. These may end up using a lot of facets that aren’t really that important.Keep in mind that gravity doesn’t always have to point down.Speed-upsKeep the domain size as small as possible without losing geometry. This will avoid wasting processing power on empty space.Pay attention to the processor distribution. For many systems, you can take advantage of knowing where your particles will be during the simulation to assign processors in an advantageous way andenhance the speed of the simulation. For example, if you have a batch mixer where the particles aregently mixed and generally occupy only the lower half of the mixer volume, using two processors in the z-direction results in the top-most layer of processors doing very little work and not being usedeffectively. Using a single layer in the z-direction instead will lead to a significantly faster simulation.In the absence of testing, set the skin size for neighbor list calculations to ~ 1 particle diameter. Setting the neighbor list skin size too small leads to overly frequent recalculations of the neighbor list, whilesetting it too large leads to huge memory requirements. The optimal setting is a balance between the two and depends on the size of the particles, the density of the system, and the speed at which particles are moving about. A single guideline for all cases is thus difficult to set, and ideally some testing should be done to optimize the simulation.Adjust physical properties as possible for speed. For example, modulus can often be set much lower than realistic values, yielding a significant speedup, without impacting the overall simulation results.Typically, setting the elastic modulus to ~107 Pa is sufficiently high so as to capture the basic particledynamics. Increasing the density also has a positive effect by allowing for a larger timestep, thoughtypically we are not able to alter density by as much as an order of magnitude.Visualization/post-processingYou can export the geometry in multiple sets of dump files to facilitate visualization by allowing you to set the transparency on a per-body basis.You can use multiple particle types, even if they all have the same material properties, to help with post-processing elements. For example, when considering the performance of a mixer, having two particle types, with one type fed to each side of the mixer, it becomes trivial to visualize mixing performance as you can color by particle type. You can also calculate quantities like a mixing index based on particletype.。
Tutorial_2
Identify points at which the plane intercepts the x, y, z axis. Take reciprocals of these intercepts. Clear fractions and do NOT reduce to the lowest integers. Enclose the numbers in parentheses () and a bar over negative integers.
E.g. (010) ≠ (020) See example!
Each unit cell, equivalent planes have their particular indices because of the orientation of the coordinates.
Family of planes: {110} = (110),(110),(110),(101), (101),…
Special note for directions…
For Miller Indices of directions:
Since directions are vectors, a direction and its negative are not identical!
[100] ≠ [100] Same line, opposite directions!
A direction and its multiple are identical!
[100] is the same direction as [200] ( need to reduce!) [111] is the same direction as [222], [333]!
python3.7.5官方tutorial学习笔记
python3.7.5官⽅tutorial学习笔记⽤了好久python,还没有完整看过官⽅的tutorial,这⼏天抽空看了下,还是学到些东西---Table of Contents1 课前甜点Python 代码通常⽐ C 系语⾔短的原因1. ⾼级数据类型允许在⼀个表达式中表⽰复杂的操作2. 代码块的划分是按照缩进3. 不需要预定义变量2 使⽤ Python 解释器2.1 调⽤解释器EOF unix C-d windows C-z执⾏ Python 代码 python -c command [arg]把 Python 模块当脚本使⽤ python -m module [arg]执⾏脚本后进⼊交互模式 python -i 1.py2.1.1 传⼊参数sys.argv sys.argv[0] 是程序名2.1.2 交互模式2.2 解释器的运⾏环境2.2.1 源⽂件的字符编码默认编码就是 utf-8 必须放在第⼀⾏或者 UNIX “shebang” 后3 Python 的⾮正式介绍注释 #3.1 Python 作为计算器使⽤3.1.1 数字除法 / 永远返回浮点数类型 // floor division乘⽅ **交互模式下,上⼀次被执⾏显⽰的表达式的值会被保存在 _Python 内置对复数的⽀持 3+5j3.1.2 字符串原始字符串三重引号会⾃动包含换⾏,可以在⾏尾加反斜杠防⽌换⾏相邻的两个字符串字⾯值会⾃动连接到⼀起通过索引取得的单个字符是⼀个长度为⼀的字符串切⽚中越界索引会被⾃动处理Python 中字符串是不可修改的,如果需要⼀个不同的字符串,应当新建⼀个 a = “heheda” b = a[:-1] + “b”3.1.3 列表列表的切⽚都返回⼀个新列表列表⽀持使⽤ + 拼接其他列表可以给列表切⽚赋值,这样可以改变列表⼤⼩,甚⾄清空整个列表a = [1, 2, 3, 4]a[1:3] = [4, 5]a[:] = []3.2 ⾛向编程的第⼀步3.2.1 多重赋值3.2.2 printprint 会在多个参数间加空格可以传⼊ end 参数指定结尾替换换⾏的字符串4 其他流程控制⼯具4.1 if 语句输⼊ aa = input(“input: ”)if if elif else4.2 for 语句Python 中的 for 是对任意序列进⾏迭代如果在循环内需要修改序列中的值,推荐先拷贝⼀份副本words = ['aaa', 'bbb', 'ccccccc']for w in words[:]:if len(w) > 5:words.insert(0, w)4.3 range() 函数range(0, 10, 3) 0, 3, 6, 9以序列的索引迭代a = ['a', 'b', 'c']for i in range(len(a)):print(i, a[i])for i, v in enumerate(a):print(i, v)range() 返回的不是列表,是⼀个可迭代对象4.4 break 和 continue 语句,以及循环中的 else ⼦句else ⼦句 else ⼦句会在未执⾏ break,循环结束时执⾏4.5 pass 语句pass 通常⽤于创建最⼩的类 class MyEmptyClass: passpass 也⽤于写代码时作为函数或条件⼦句体的占位符,保持在更抽象的层次上思考4.6 定义函数⽂档字符串全局变量和外部函数的变量可以被引⽤,但是不能在函数内部直接赋值函数的重命名机制没有 return, 函数会返回 None列表⽅法 append() ⽐ + 效率⾼4.7 函数定义的更多形式4.7.1 参数默认值in 测试⼀个序列是否包含某个值默认值时在定义过程中在函数定义处计算的,⽽不是调⽤时默认值只执⾏⼀次,如果是可变对象,⽐如列表,就可以在后续调⽤之间共享默认值类似于 c 中的静态变量def f(a, L=[]):print(a)L.append(a)print(L)f(1)f(2)f(3)f(4)4.7.2 关键字参数关键字参数必须在位置参数后形参 * **4.7.3 任意的参数列表任意的参数列表 *args ⼀般位于形式参数列表的末尾,只有关键字参数能出现在其后4.7.4 解包参数列表使⽤* 从列表或元组中解包参数 args = [3, 6] range(*args)使⽤** 从字典解包参数4.7.5 Lambda 表达式闭包def make_incrementor(n):return lambda x: x + nf = make_incrementor(33)f(0)传递⼀个函数作为参数pairs = [(1, 'one'), (2, 'two'), (3, 'three')]pairs.sort(key=lambda pair: pair[1])4.7.6 ⽂档字符串⼀些约定第⼀⾏简要描述对像的⽬的,⼤写字母开头,句点结尾第⼆⾏空⽩,后⾯⼏⾏是⼀个或多个段落,描述调⽤约定,副作⽤等4.7.7 函数标注标注不会对代码有实质影响,只是给⼈看def f(ham: str, eggs: str = "eggs") -> str:print(f.__annotations__)return ham + ' and ' + eggs4.8 ⼩插曲: 编码风格使⽤ 4 空格缩进,⽽不是制表符⼀⾏不超过 79 个字符(可以在较⼤显⽰器并排放置多个代码⽂件)使⽤空⾏分割函数和类,以及函数内的较⼤的代码块尽量把注释放到单独的⼀⾏使⽤⽂档字符串在运算符前后和逗号后使⽤空格函数和类命名应使⽤⼀致规则类 UpperCamelCase 函数 lowercase withunderscores⼀般不另外设置代码的编码不要在标识符中使⽤⾮ ASCII 字符5 数据结构5.1 列表的更多特性列表对象⽅法的清单 list.append(x) list.extend(iterable) list.insert(i, x) list.remove(x) list.pop([i]) list.clear() list.index(x[, start[, end]]) list.count(x) list.sort(key=None, reverse=False) list.reverse() list.copy()5.1.1 列表作为栈使⽤list.append(x) list.pop()5.1.2 列表作为队列使⽤在列表开头插⼊或弹出元素很慢from collections import dequequeue = deque(['aaa', 'bbb', 'ccc'])queue.append('ddd')queue.popleft()5.1.3 列表推导式for 循环后,循环变量还存在列表推导式中,for 和 if 顺序和展开形式的顺序是⼀致的如果表达式是⼀个元组,需要加括号5.1.4 嵌套的列表推导式a = [1, 2, 3]b = [4, 5, 6]print(list(zip(a, b)))5.2 del 语句del 可以删除指定索引的元素del 可以删除切⽚指定的范围del a[:]del a5.3 元组和序列元组通常包含不同种类的元素,列表的元素⼀般是同种类型空元组可以直接被⼀对圆括号创建元组输⼊时圆括号可有可⽆5.4 集合set()集合操作 a | b a - b a & b a ^ b集合推导式 a = {x for x in ’abcdedd’ if x not in ’abc’}5.5 字典只要不包含不可变对象,都可以作为键5.6 循环的技巧字典循环时,可以⽤ items() ⽅法把关键字和值同时取出序列循环时,可以⽤ enumerate()函数将索引和值同时取出要同时在多个序列中循环时,可以⽤ zip()函数如果要逆向⼀个序列,可以使⽤ reversed()函数sorted()函数可以返回⼀个新的排好序的序列在循环时想修改列表内容,最好创建新列表5.7 深⼊条件控制in 和 not inis 和 is not ⽐较是不是同⼀个对象⽐较操作可以传递5.8 ⽐较序列和其他类型序列也可以⽐较6 模块如果经常使⽤某个导⼊的函数,可以赋值给⼀个局部变量重命名6.1 更多有关模块的信息⼏种导⼊⽅式from fibo import fib, fib2from fibo import *import fibo as fibfrom fibo import fib as fibonacci每个模块在每个解释器会话中只被导⼊⼀次,如果更改了模块,要重新启动解释器或 import importlib importlib.reload(module) 6.1.1 以脚本的⽅式执⾏模块如果直接执⾏脚本,_name__ 被赋值为_main__6.1.2 模块搜索路径搜索路径1. 内置模块2. sys.path 给出的⽬录列表1. 包含输⼊脚本的⽬录2. PYTHONPATH3. 取决于安装的默认设置6.1.3 “编译过的”Python ⽂件python3 会把 pyc 统⼀放在_pycache_下 python2 是放在源⽂件同⽬录下pyc 和 py ⽂件运⾏速度是⼀样的,只是 pyc 的载⼊速度更快6.2 标准模块sys.ps1 sys.ps2 ⽤于定义交互模式下的提⽰符6.3 dir() 函数dir ⽤于查找模块定义的名称如果没有参数,dir 会列出当前定义的名称dir 不会列出内置函数和变量,他们定义在标准模块 builtins6.4 包包是⼀种通过⽤“带点号的模块名”来构造 Python 模块命名空间的⽅法_init_.py中可以执⾏包的初始化代码或设置_all__ 变量⼀些导⼊⽅式1. 导⼊模块 import a.b.c 使⽤时要使⽤全名 from a.b import c 可以直接⽤ c from a.b.c import d 可以直接⽤ d6.4.1 从包中导⼊*导⼊⼀个包时会参考它 init.py 内_all__ 列表的内容6.4.2 ⼦包参考相对导⼊ from . improt echo from .. import formats from ..filters import equalizer相对导⼊时基于当前模块的名称进⾏导⼊的,所以主模块必须⽤绝对导⼊6.4.3 多个⽬录中的包7 输⼊输出7.1 更漂亮的输出格式⼀些格式化输出⽅式 aa = ’a test’ b = f’hehe {aa}’ ’{gg}’.format(aa)str() 返回⼈类可读的值的表⽰repr() ⽣成解释器可读的表⽰7.1.1 格式化字符串⽂字⼀些⽰例 print(f’value {math.pi:.3f}.’) print(f’{name:10} {num:10d}’) print(f’{animal!r}’) # !a ascii() !s str() !r repr() 7.1.2 字符串的 format() ⽅法7.1.3 ⼿动格式化字符串rjust() ljust() center()7.1.4 旧的字符串格式化⽅法%7.2 读写⽂件最好使⽤ with7.2.1 ⽂件对象的⽅法常⽤⽅法列表 f.read() f.readline() f.write() f.tell() f.seek(5) f.seek(-3,2) # 0 start 1 current 2 end遍历⾏ for line in f: pass7.2.2 使⽤ json 保存结构化数据常⽤⽅法 jons.dumps([1, ’a’, 2]) json.dump(x, f) x = json.load(f)8 错误和异常8.1 语法错误8.2 异常8.3 处理异常else ⼦句必须放在 except 后8.4 抛出异常在 except 处理时可以 raise 抛出异常8.5 ⽤户⾃定义异常⾃定义异常⼀般只是提供⼀些属性8.6 定义清理操作finally ⼦句8.7 预定义的清理操作with 语句9 类9.1 名称和对象Python 中,多个变量可以绑定到⼀个对象,对于可变对象,表现得类似于指针9.2 Python 作⽤域和命名空间9.2.1 作⽤域和命名空间⽰例关于 nonlocal global 的⽤法def do_local():spam = "local spam"def do_nonlocal():nonlocal spamspam = "nonlocal spam"def do_global():global spamspam = "global spam"spam = "test spam"do_local()print("After local assignment:", spam)do_nonlocal()print("After nonlocal assignment:", spam)do_global()print("After global assignment:", spam)scope_test()print("In global scope:", spam)输出结果 After local assignment: test spam After nonlocal assignment: nonlocal spam After global assignment: nonlocal spam In global scope: global spam9.3 初探类9.3.1 类定义语法9.3.2 类对象类对象⽀持两种操作: 属性引⽤和实例化_doc__ ⽂档字符串9.3.3 实例对象实例对象的唯⼀操作是属性引⽤两种属性名称: 数据属性和⽅法数据属性不需要声明,在第⼀次赋值时产⽣9.3.4 ⽅法对象区分⽅法对象和函数对象class TestClass:def kk(self):print('aaa')bb = TestClass()bb.kk()TestClass.kk(bb)9.3.5 类和实例变量9.4 补充说明9.5 继承isinstance(obj, int)issubclass(bool, int)9.5.1 多重继承搜索的顺序是深度优先,从左到右9.6 私有变量通过约定,下划线开头的名称9.7 杂项说明定义空类,简单实现将命名数据捆绑在⼀起class Employee:passjohb = Employee() = "peter"john.dept = "computer lab"实例⽅法对象具有的属性 m._self__ 带有 m ⽅法的实例对象 m._func__ 该⽅法对应的函数对象9.8 迭代器for 的机制1. for 会⽤ iter() 函数调⽤容器内的_iter_()⽅法2. 此⽅法会返回⼀个定义了_next_()⽅法的对象3. 调⽤ next() 函数,会调⽤上⼀步返回对象的_next_()⽅法4. 当元素⽤尽时,_next_()会引发 StopIteration 异常给⾃⼰的类添加迭代器⾏为1. 定义_iter__ ⽅法,返回 self2. 定义_next__ ⽅法,返回⼀个改变引⽤所指的对象,同时设置条件,遍历完 raise StopIterationclass Reverse:def__init__(self, data):self.data = dataself.index = len(data)def__iter__(self):return selfdef__next__(self):if self.index == 0:raise StopIterationself.index = self.index - 1return self.data[self.index]9.9 ⽣成器写法类似标准函数,但是返回不⽤ return,⽤ yield⽣成器会⾃动创建_iter_()和_next_(),⽣成器终结时会⾃动引发 StopIteration9.10 ⽣成器表达式⽣成器表达式被设计⽤于⽣成器将⽴即被外层函数所使⽤的情况 sum(i*i for i in range(10))10 标准库简介10.1 操作系统接⼝import os os.getcwd() os.chdir() os.system对于⽇常⽂件和⽬录管理任务,shutil 模块提供了更易于使⽤的更⾼级模块 shutil.copyfile() shutil.move() 10.2 ⽂件通配符import glob 提供了在⼀个⽬录中使⽤通配符搜索⽂件列表的函数 glob.glob(’*.py’)10.3 命令⾏参数import sys print(sys.argv)argparseimport argparsefrom getpass import getuserparser = argparse.ArgumentParser(description='An argparse example.')parser.add_argument('name', nargs='?', default=getuser(), help='The name of someone to greet.')parser.add_argument('--verbose', '-v', action='count')args = parser.parse_args()greeting = ["Hi", "Hello", "Greetings! its very nice to meet you"][args.verbose % 3]print(f'{greeting}, {}')if not args.verbose:print('Try running this again with multiple "-v" flags!')10.4 错误输出重定向和程序终⽌sys.std sys.stdin sys.stdout sys.stderr.write(’wrong’)终⽌脚本 sys.exit()10.5 字符串模式匹配import re re.findall(r’\bf[a-z]*’, ’which foot or hand fell fastest’) re.sub(r’(\b[a-z]+) \1’, r’\1’, ’cat in the the hat’) ’cat in the hat’当只需要简单的功能时,⾸选字符串⽅法10.6 数学math 提供了对浮点数的低层 C 库函数的访问import math math.cos(math.pi / 4) math.log(1024, 2)random random.choice([’a’, ’b’, ’c’]) random.sample(range(100), 10) # 选 10 个样本出来 random.random() # 0 到 1 的随机数random.randrange(5) # 从 range(5) 选import statistics statistics.mean() # 平均值 statistics.median() # 中位数 statistics.variance() # ⽅差10.7 互联⽹访问urllib.requestfrom urllib.request import urlopenwith urlopen('') as response:for line in response:line = line.decode('utf-8')if'EST'in line or'EDT'in line:print (line)smtplibimport smtplibserver = smtplib.SMTP('localhost')server.sendmail('soothsayer@', 'jcaesar@',"""To: jcaesar@From: soothsayer@Beware the Ides of March.""")server.quit ()10.8 ⽇期和时间datetime# dates are easily constructed and formattedfrom datetime import datenow = date.today()now# datetime.date(2003, 12, 2)now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")# '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'# dates support calendar arithmeticbirthday = date(1964, 7, 31)age = now - birthdayage.days# 1436810.9 数据压缩zlibimport zlibs = b'witch which has which witches wrist watch'len(s)t = press(s)len(t)zlib.decompress(t)zlib.crc32(s)10.10 性能测量timeit 快速测试⼩段代码>>> from timeit import Timer >>> Timer(’t=a; a=b; b=t’, ’a=1; b=2’).timeit() 0.57535828626024577 >>> Timer(’a,b = b,a’, ’a=1; b=2’).timeit() 0.54962537085770791Profileimport cProfile, pstats, iofrom pstats import SortKeyimport hashlibimport timepr = cProfile.Profile()pr.enable()data = "你好"for i in range(10000):m = hashlib.md5(data.encode("gb2312"))time.sleep(2)pr.disable()s = io.StringIO()sortby = SortKey.CUMULATIVEps = pstats.Stats(pr, stream=s).sort_stats(sortby)ps.print_stats()print (s.getvalue())10.11 质量控制doctests 可以验证⽂档字符串中嵌⼊的测试def average(values):"""Computes the arithmetic mean of a list of numbers.>>> print(average([20, 30, 70]))40.0"""return sum(values) / len(values)import doctestdoctest.testmod() # automatically validate the embedded testsunittestimport unittestclass TestStatisticalFunctions(unittest.TestCase):def test_average(self):self.assertEqual(average([20, 30, 70]), 40.0)self.assertEqual(round(average([1, 5, 7]), 1), 4.3)with self.assertRaises(ZeroDivisionError):average([])with self.assertRaises(TypeError):average(20, 30, 70)unittest.main() # Calling from the command line invokes all tests10.12 ⾃带电池xmlrpc.client xmlrpc.serveremailjsoncsvxml.etree.ElementTree xml.dom xml.saxsqlite3gettext locale codecs11 标准库简介 – 第⼆部分本部分介绍的是专业编程需要的更⾼级的模块,很少⽤在⼩脚本中11.1 格式化输出reprlib ⽤于缩略显⽰⼤型或深层嵌套的容器对象 >>> reprlib.repr(set(’supercalifragilisticexpialidocious’))“{‘a’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, …}”pprint 美化输出版 printtextwrap 格式化⽂本段落,适应给定的屏幕宽度 print(textwrap.fill(doc, width=40))11.2 模板from string import Template>>> t = Template(’${village}folk send $$10 to $cause.’) >>> t.substitute(village=’Nottingham’, cause=’the ditch fund’) ’Nottinghamfolk send $10 to the ditch fund.’11.3 使⽤⼆进制数据记录格式struct 模块的 pack() unpack()11.4 多线程threading11.5 ⽇志记录logging11.6 弱引⽤weakref 可以不必创建引⽤就能跟踪对象11.7 ⽤于操作列表的⼯具from array import arrayfrom collections import dequeimport bitsetfrom heapq import heapify, heappop heappush11.8 ⼗进制浮点运算from decimal import * 可以提供⾜够的精度,也能满⾜浮点数的相等性12 虚拟环境和包12.1 概述12.2 创建虚拟环境venv12.3 使⽤ pip 管理包pip 常⽤命令 pip search xxx pip install novas pip install requests==2.6.0 pip install –upgrade requests pip show requests pip list pip freeze > requirements.txt pip install -r requirements.txt13 接下来?14 交互式编辑和编辑历史14.1 Tab 补全和编辑历史python3 解释器已经有 tab 补全了默认配置,编辑历史会被保存在 home ⽬录 .python history14.2 默认交互式解释器的替代品ipython15 浮点算术16 附录Author: catCreated: 2019-11-01 Fri 17:48。
Ruby编程语言教程(Tutorials Point)说明书
About the T utorialRuby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.This tutorial gives a complete understanding on Ruby.AudienceThis tutorial has been prepared for beginners to help them understand the basic to advanced concepts related to Ruby Scripting languages.PrerequisitesBefore you start practicing with various types of examples given in this tutorial, we are making an assumption that you are already aware of computer programs and programming languages in general.Copyright & DisclaimerCopyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our websiteorinthistutorial,******************************************iT able of ContentsAbout the Tutorial ......................................................................................................................................Audience (i)Prerequisites (i)Copyright & Disclaimer (i)Table of Contents ...................................................................................................................................... i i 1. RUBY – OVERVIEW (1)Features of Ruby (1)Tools You Will Need (2)What is Next? (2)2. RUBY – ENVIRONMENT SETUP (3)Try it Option Online (3)Local Environment Setup (3)Ruby Installation on Linux/Unix (3)Using yum to Install Ruby (4)Ruby Installation on Windows (4)Ruby Command Line Options (5)Ruby Environment Variables (7)Popular Ruby Editors (9)Interactive Ruby (IRb) (9)What is Next? (10)3. RUBY – SYNTAX (11)Whitespace in Ruby Program (11)Line Endings in Ruby Program (11)Ruby Identifiers (11)iiHere Document in Ruby (12)Ruby BEGIN Statement (13)Ruby END Statement (14)Ruby Comments (15)4. RUBY – CLASSES AND OBJECTS (16)Defining a Class in Ruby (17)Variables in a Ruby Class (17)Creating Objects in Ruby Using new Method (18)Custom Method to Create Ruby Objects (18)Member Functions in Ruby Class (19)Simple Case Study (20)5. RUBY – VARIABLES, CONSTANTS AND LITERALS (24)Ruby Global Variables (24)Ruby Instance Variables (25)Ruby Class Variables (26)Ruby Local Variables (27)Ruby Constants (27)Ruby Pseudo-Variables (28)Ruby Basic Literals (28)Integer Numbers (28)Floating Numbers (29)String Literals (29)Backslash Notations (30)Ruby Arrays (31)Ruby Hashes (31)iii6. RUBY – OPERATORS (33)Ruby Arithmetic Operators (33)Ruby Comparison Operators (33)Ruby Assignment Operators (35)Ruby Parallel Assignment (35)Ruby Bitwise Operators (36)Ruby Logical Operators (37)Ruby Ternary Operator (38)Ruby Range Operators (38)Ruby defined? Operators (38)Ruby Dot "." and Double Colon "::" Operators (40)Ruby Operators Precedence (41)7. RUBY – COMMENTS (43)Ruby Multiline Comments (43)8. RUBY –IF...ELSE, C ASE, UNLESS (45)Ruby if...else Statement . (45)Ruby if modifier (46)Ruby unless Statement (46)Ruby unless modifier (47)Ruby case Statement (47)9. RUBY – LOOPS (50)Ruby while Statement (50)Ruby while modifier (51)Ruby until Statement (51)ivRuby for Statement (53)Ruby break Statement (54)Ruby next Statement (55)Ruby redo Statement (56)Ruby retry Statement (56)10. RUBY – METHODS (58)Return Values from Methods (59)Ruby return Statement (59)Variable Number of Parameters (60)Class Methods (61)Ruby alias Statement (62)Ruby undef Statement (62)11. RUBY – BLOCKS (64)The yield Statement (64)Blocks and Methods (66)BEGIN and END Blocks (66)12. RUBY – MODULES AND MIXINS (68)Ruby require Statement (69)Ruby include Statement (70)Mixins in Ruby (71)13. RUBY – STRINGS (73)Expression Substitution (73)General Delimited Strings (73)Escape Characters (74)vString Built-in Methods (75)String unpack Directives (85)14. RUBY – ARRAYS (89)Creating Arrays (89)Array Built-in Methods (91)Array pack Directives (99)15. RUBY – HASHES (103)Creating Hashes (103)Hash Built-in Methods (104)16. RUBY – DATE AND TIME (109)Getting Current Date and Time (109)Getting Components of a Date & Time (109)Time.utc,Time.gm and Time.local Functions (110)Timezones and Daylight Savings Time (112)Formatting Times and Dates (112)Time Formatting Directives (113)Time Arithmetic (114)17. RUBY – RANGES (116)Ranges as Sequences (116)Ranges as Conditions (118)Ranges as Intervals (118)18. RUBY – ITERATORS (120)Ruby each Iterator (120)Ruby collect Iterator (121)vi19. RUBY – FILE I/O (123)The puts Statement (123)The gets Statement (123)The putc Statement (124)The print Statement (124)Opening and Closing Files (125)The File.new Method (125)The File.open Method (125)Reading and Writing Files (126)The sysread Method (126)The syswrite Method (127)The each_byte Method (127)The IO.readlines Method (128)The IO.foreach Method (128)Renaming and Deleting Files (128)File Modes and Ownership (129)File Inquiries (130)Directories in Ruby (132)Navigating Through Directories (132)Creating a Directory (132)Deleting a Directory (133)Creating Files & Temporary Directories (133)Built-in Functions (133)File Class and Methods (134)Directory Class and Methods (139)20. RUBY – EXCEPTIONS (142)viiUsing raise Statement (144)Using ensure Statement (146)Using else Statement (147)Catch and Throw (148)Class Exception (149)21. RUBY OBJECT ORIENTED (151)Ruby Class Definition (151)Define Ruby Objects (151)The initialize Method (151)The instance Variables (152)The accessor & setter Methods (152)The instance Methods (155)The class Methods and Variables (155)The to_s Method (156)Access Control (157)Class Inheritance (159)Methods Overriding (160)Operator Overloading (161)Freezing Objects (162)Class Constants (164)Create Object Using Allocate (165)Class Information (166)22. RUBY – REGULAR EXPRESSIONS (167)Regular-Expression Modifiers (167)Regular-Expression Patterns (168)viiiAnchors (173)Special Syntax with Parentheses (174)Search and Replace (174)23. RUBY – DBI (177)Architecture of a DBI Application (177)Prerequisites (178)Obtaining and Installing Ruby/DBI (178)Database Connection (179)INSERT Operation (180)Using do Statement (180)Using prepare and execute (181)READ Operation (183)Fetching the Result (184)Update Operation (190)DELETE Operation (191)Performing Transactions (192)COMMIT Operation (193)ROLLBACK Operation (193)Disconnecting Database (193)Handling Errors (194)Code Blocks with Methods (195)Driver-specific Functions and Attributes (196)24. RUBY – WEB APPLICATIONS (199)Writing CGI Scripts (199)Using cgi.rb (199)ixCreating Forms and HTML (201)Quoting Strings (203)Useful Methods in CGI Class (203)Ruby CGI (204)Cookies and Sessions (210)Ruby CGI Cookies (210)Ruby CGI Sessions (212)Web Hosting Servers (214)25. RUBY – SENDING EMAIL (215)Sending an HTML e-mail using Ruby (216)Sending Attachments as an e-mail (217)26. RUBY – SOCKET PROGRAMMING (220)What are Sockets? (220)A Simple Client (221)A Simple Server (221)Multi-Client TCP Servers (222)A Tiny Web Browser (223)Further Readings (224)27. RUBY – XML, XSLT, XPATH (225)What is XML? (225)XML Parser Architectures and APIs (225)Parsing and Creating XML using Ruby (225)DOM-like Parsing (227)SAX-like Parsing (228)XPath and Ruby (230)xFurther Reading (232)28. RUBY – WEB SERVICES (233)What is SOAP? (233)Installing SOAP4R (233)Writing SOAP4R Servers (233)Writing SOAP4R Clients (237)29. RUBY – TK GUIDE (240)Introduction (240)Installation (240)Simple Tk Application (240)Ruby/Tk Widget Classes (241)TkFrame (242)TkButton (245)TkLabel (248)TkEntry (251)TkCheckButton (256)TkRadioButton (261)TkListbox (265)TkComboBox (272)TkMenu (274)TkMenubutton (280)Tk.messageBox (284)TkScrollbar (286)TkCanvas (291)TkScale (300)xiTkToplevel (310)TkSpinbox (312)TkProgressBar (318)Dialog Box (321)Tk::Tile::Notebook (323)Tk::Tile::Paned (326)Tk::Tile::Separator (328)Ruby/Tk Font, Colors, and Images (330)Standard Configuration Options (334)Ruby/Tk Geometry Management (339)grid (339)Pack (340)Place (342)Ruby/Tk Event Handling (343)The configure Method (345)The cget Method (346)30. RUBY – LDAP (347)Ruby/LDAP Installation (347)Establish LDAP Connection (347)Adding an LDAP Entry (348)Modifying an LDAP Entry (350)Deleting an LDAP Entry (351)Modifying the Distinguished Name (352)Performing a Search (353)Handling Errors (355)xii31. RUBY – MULTITHREADING (356)Creating Ruby Threads (356)Thread Lifecycle (357)Threads and Exceptions (358)Thread Variables (358)Thread Priorities (359)Thread Exclusion (359)Handling Deadlock (361)Thread States (362)Thread Class Methods (363)Thread Instance Methods (365)32. RUBY – BUILT-IN FUNCTIONS (368)Functions for Numbers (374)Functions for Float (377)Functions for Math (378)Conversion Field Specifier (379)Test Function Arguments (381)33. RUBY – PREDEFINED VARIABLES (384)34. RUBY – PREDEFINED CONSTANTS (388)35. RUBY – ASSOCIATED TOOLS (390)Standard Ruby Tools (390)RubyGems (390)Ruby Debugger (394)Interactive Ruby (398)xiiiAdditional Ruby Tools (402)eRuby: Embeded Ruby (402)ri: Ruby Interactive Reference (403)xivRuby 1Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan.You can find the name Yukihiro Matsumoto on the Ruby mailing list at . Matsumoto is also known as Matz in the Ruby community. Ruby is "A Programmer's Best Friend".Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is a perfect object-oriented language. Using Ruby syntax is much easier than using Smalltalk syntax.Features of Ruby∙Ruby is an open-source and is freely available on the Web, but it is subject to a license. ∙Ruby is a general-purpose, interpreted programming language. ∙Ruby is a true object-oriented programming language. ∙Ruby is a server-side scripting language similar to Python and PERL. ∙Ruby can be used to write Common Gateway Interface (CGI) scripts. ∙Ruby can be embedded into Hypertext Markup Language (HTML). ∙Ruby has a clean and easy syntax that allows a new developer to learn very quickly and easily. ∙Ruby has similar syntax to that of many programming languages such as C++ and Perl. ∙Ruby is very much scalable and big programs written in Ruby are easily maintainable. ∙Ruby can be used for developing Internet and intranet applications. ∙Ruby can be installed in Windows and POSIX environments. ∙Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL. ∙Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase. ∙ Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.1. RUBY – OVERVIEWRubyT ools Y ou Will NeedFor performing the examples discussed in this tutorial, you will need a latest computer like Intel Core i3 or i5 with a minimum of 2GB of RAM (4GB of RAM recommended). You also will need the following software:∙Linux or Windows 95/98/2000/NT or Windows 7 operating system∙Apache 1.3.19-5 Web server∙Internet Explorer 5.0 or above Web browser∙Ruby 1.8.5This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Ruby. It also will talk about extending and embedding Ruby applications.What is Next?The next chapter guides you to where you can obtain Ruby and its documentation. Finally, it instructs you on how to install Ruby and prepare an environment to develop Ruby applications.2Ruby 3Try it Option OnlineWe already have set up Ruby Programming environment online, so that you can execute almost all the tutorial examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.Try the following example using the Try it option available on our website at the top right corner of the sample code box given below:#!/usr/bin/ruby -wputs "Hello, Ruby!";For most of the examples given in this tutorial, you will find a Try it option on our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.Local Environment SetupIf you are still willing to set up your environment for Ruby programming language, then let's proceed. This tutorial will teach you all the important topics related to environment setup. We would recommend you to go through the following topics first and then proceed further:∙Ruby Installation on Linux/Unix : If you are planning to have your development environment on Linux/Unix Machine, then go through this chapter. ∙Ruby Installation on Windows : If you are planning to have your development environment on Windows Machine, then go through this chapter. ∙Ruby Command Line Options : This chapter list out all the command line options, which you can use along with Ruby interpreter. ∙ Ruby Environment Variables : This chapter has a list of all the important environment variables to be set to make Ruby Interpreter works. Ruby Installation on Linux/UnixHere are the steps to be followed to install Ruby on a Unix machine: NOTE: Before proceeding, make sure you have root privilege.∙ Download a zipped file having latest version of Ruby. Follow Download Link .2. RUBY – ENVIRONMENT SETUP∙After having downloaded the Ruby archive, unpack it and change into the newly created directory:$ tar -xvzf ruby-1.6.7.tgz$ cd ruby-1.6.7∙Now, configure and compile the source code as follows:$ ./configure$ make∙Finally, install Ruby interpreter as follows:$ su -l root # become a root user$ make install$ exit # become the original user again∙After installation, make sure everything is working fine by issuing the following command on the command-line:$ruby -vruby 1.6.7 (2002-06-04) [i386-netbsd]∙If everything is fine, this should output the version of the installed Ruby interpreter as shown above. You may have installed different version, so it will display a different version.Using yum to Install RubyIf your computer is connected to the Internet, then the easiest way to install Ruby or any other other RPM is using the yum utility. Give the following command at the command prompt and you will find Ruby gets installed on your computer.$ yum install rubyRuby Installation on WindowsHere are the steps to install Ruby on a Windows machine.NOTE:You may have different versions available at the time of installation.∙Download a zipped file having latest version of Ruby. Follow Download Link.∙After having downloaded the Ruby archive, unpack it and change into the newly created directory:∙Double-click the Ruby1.6.7.exe file. The Ruby installation wizard starts.4∙Click Next to move to the Important Information page of the wizard and keep moving till Ruby installer completes installing Ruby.You may need to set some environment variables if your installation has not setup them appropriately.∙If you use Windows 9x, add the following lines to your c:\autoexec.bat: set PATH="D:\(ruby install directory)\bin;%PATH%"∙Windows NT/2000 users need to modify their registries.o Click Control Panel | System Properties | Environment Variables.o Under System Variables, select Path and click EDIT.o Add your Ruby directory to the end of the Variable Value list and click OK.o Under System Variables, select PATHEXT and click EDIT.o Add .RB and .RBW to the Variable Value list and click OK.∙After installation, make sure everything is working fine by issuing the following command on the command-line:$ruby -vruby 1.6.7∙If everything is fine, this should output the version of the installed Ruby interpreter as shown above. You may have installed different version, so it will display a different version.Ruby Command Line OptionsRuby is generally run from the command line in the following way:$ ruby [ options ] [.] [ programfile ] [ arguments ... ]The interpreter can be invoked with any of the following options to control the environment and behavior of the interpreter.Option Description-a Used with -n or -p to split each line. Check -n and -p options.-c Checks syntax only, without executing program.-C dir Changes directory before executing (equivalent to -X).-d Enables debug mode (equivalent to -debug).5-F pat Specifies pat as the default separator pattern ($;) used by split.-e prog Specifies prog as the program from the command line. Specify multiple -e options for multiline programs.-h Displays an overview of command-line options.-i [ ext] Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file isdeleted.-I dir Adds dir as the directory for loading libraries.-K [ kcode] Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF-8; and a, A, n, orN for ASCII).-l Enables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines.-n Places code within an input loop (as in while gets; ... end).-0[ octal] Sets default record separator ($/) as an octal. Defaults to \0 if octal not specified.-p Places code within an input loop. Writes $_ for each iteration.-r lib Uses require to load lib as a library before executing.-s Interprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines thecorresponding variable.-T [level] Sets the level for tainting checks (1 if level not specified).-v Displays version and enables verbose mode-w Enables verbose mode. If program file not specified, reads from STDIN. -x [dir] Strips text before #!ruby line. Changes directory to dir before executing if dir is specified.-X dir Changes directory before executing (equivalent to -C).-y Enables parser debug mode.--copyright Displays copyright notice.--debug Enables debug mode (equivalent to -d).--help Displays an overview of command-line options (equivalent to -h).--version Displays version.--verbose Enables verbose mode (equivalent to -v). Sets $VERBOSE to true.--yydebug Enables parser debug mode (equivalent to -y).Single character command-line options can be combined. The following two lines express the same meaning:$ruby -ne 'print if /Ruby/' /usr/share/bin$ruby -n -e 'print if /Ruby/' /usr/share/binRuby Environment V ariablesRuby interpreter uses the following environment variables to control its behavior. The ENV object contains a list of all the current environment variables set.Variable DescriptionDLN_LIBRARY_PATH Search path for dynamically loaded modules.HOME Directory moved to when no argument is passed toDir::chdir. Also used by File::expand_path to expand "~". LOGDIR Directory moved to when no arguments are passed to7Dir::chdir and environment variable HOME isn't set.PATH Search path for executing subprocesses and searching forRuby programs with the -S option. Separate each path with acolon (semicolon in DOS and Windows).RUBYLIB Search path for libraries. Separate each path with a colon(semicolon in DOS and Windows).RUBYLIB_PREFIX Used to modify the RUBYLIB search path by replacing prefixof library path1 with path2 using the format path1;path2 orpath1path2.RUBYOPT Command-line options passed to Ruby interpreter. Ignored intaint mode (Where $SAFE is greater than 0).RUBYPATH With -S option, search path for Ruby programs. Takesprecedence over PATH. Ignored in taint mode (where $SAFEis greater than 0).RUBYSHELL Specifies shell for spawned processes. If not set, SHELL orCOMSPEC are checked.For Unix, use env command to see a list of all the environment variables.HOSTNAME=RUBYPATH=/usr/binSHELL=/bin/bashTERM=xtermHISTSIZE=1000SSH_CLIENT=122.169.131.179 1742 22SSH_TTY=/dev/pts/1USER=amroodJRE_HOME=/usr/java/jdk/jreJ2RE_HOME=/usr/java/jdk/jrePATH=/usr/local/bin:/bin:/usr/bin:/home/guest/binMAIL=/var/spool/mail/guestPWD=/home/amroodINPUTRC=/etc/inputrc8JAVA_HOME=/usr/java/jdkLANG=CHOME=/rootSHLVL=2JDK_HOME=/usr/java/jdkLOGDIR=/usr/log/rubyLOGNAME=amroodSSH_CONNECTION=122.169.131.179 1742 72.167.112.17 22LESSOPEN=|/usr/bin/lesspipe.sh %sRUBYLIB=/usr/lib/rubyG_BROKEN_FILENAMES=1_=/bin/envPopular Ruby EditorsTo write your Ruby programs, you will need an editor:∙If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus.∙VIM(Vi IMproved) is a very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise, your can use your favorite vi editor to write Ruby programs.∙RubyWin is a Ruby Integrated Development Environment (IDE) for Windows.∙Ruby Development Environment(RDE)is also a very good IDE for windows users.Interactive Ruby (IRb)Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line.This tool comes along with Ruby installation so you have nothing to do extra to have IRb working.Just type irb at your command prompt and an Interactive Ruby Session will start as given below:$irbirb 0.6.1(99/09/16)irb(main):001:0> def helloirb(main):002:1> out = "Hello World"irb(main):003:1> puts out9irb(main):004:1> endnilirb(main):005:0> helloHello Worldnilirb(main):006:0>Do not worry about what we did here. You will learn all these steps in subsequent chapters.What is Next?We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs.10End of ebook previewIf you liked what you saw…Buy it from our store @ https://11。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Sensitivity analyses:a brief tutorial with Rpackage pse,version0.1.2Chalom,A.;Mandai,C.Y.&Prado,P.I.K.L.October15,2013This document presents a brief practical tutorial about the use of sensitivity analyses tools in the study of ecological models.To read about the underlying theory,please refer to our work in[1].We presume for this tutorial that you are already familiar with the R programing environment and with your chosen model.We will illustrate the techniques using a simple model of population growth.You should have installed R1along with an interface and text editor of your lik-ing,the packages“sensitivity”,“Hmisc”and“ks”,and have downloaded the functions available on our package“pse”available onp.br/let/doku.php?id=engl:tutorials:rcode1Input parametersThefirst thing that must be done is to determine exactly what are the input pa-rameters to your model.You should list which parameters should be investigated, what are the probability distribution functions(PDFs)from which the parameter values will be calculated,and what are the arguments to these PDFs.In the examples,we will use a simple model of logistical population growth,in which a population has an intrinsic rate of growth r,a carrying capacity of K and a starting population of X0.In each time step,the population may grow or diminish after the following expression:X t+1=X t+rX t(1−X t/K)(1) We are insterested in studying the effects of the parameters r,K and X0on the final population.After researching on our databases,we have decided that,for our species of interest,r and K follow a normal distribution with known parameters. However,we could not reliably determine what the initial population should be, so we have used an uniform distribution covering all the reasonable values.The following table summarizes this:1This tutorial was written and tested with R version3.0.2,but it should work with newer versionsParameter Distribution Argumentsr normalµ=1.7,σ=0.15K normalµ=40,σ=1X0uniform min=1,max=50We next translate this table to three R objects that will be used in the sensitivity analyses,containing the names of the parameters,the distribution functions,and a list containing the lists with all the parameters to the distribution functions:>factors<-c("r","K","X0")>q<-c("qnorm","qnorm","qunif")>q.arg<-list(list(mean=1.7,sd=0.15),list(mean=40,sd=1),+list(min=1,max=50))A fundamental question in this stage is to determine whether,inside the as-cribed parameter ranges,every parameter combination is meaningful.See the next examples on this:Example1:We would like to run a model for a species abundance distribution(SAD),and we decided to examine the effect of N,the total number of individuals in the community,and S,the total number of species.We can run the model with N=100 and S=50or with N=15and S=3,so there is nothing wrong with these values. However,the combination N=15,S=50is meaningless,as it would imply that there are more species than individuals.One solution to this problem is to run the models with the parameters modified as following:N is the total number of individuals,andˆs is the average number of individuals for each species.So,ˆs∗N=S,and now every combination of N andˆs is meaningful.Example2:In a model of structured population growth,we have estimated independently two parameters for each class:S,the probability that a given individual survives and does not move into the next size class,and G,the probability that a given individual survives and grows into the next class.We can run the model with S=0.2and G=0.7,or S=0.8and G=0.1.However,if we try to run the model with S=0.8and G=0.7,we arrive at the conclusion that,for every individual in the original size class,in the next time step we will have0.8individuals in the same class and more0.7in the next,giving a total of1.5individuals!The problem is that the sum of S and G must be smaller than1.One way to solve this is to define new parametersˆs andˆg such thatˆs is the survival probability,independently of the individual growing,andˆg is the growth probability for each surviving individual. We can relate these parameters to the former ones,as G=ˆs∗ˆg and S=ˆs∗(1−ˆg). 2Your modelThe model that you wish to analyse must be formulated as an R function that receives a data.frame,in which every column represent a different parameter,andevery line represents a different combination of values for those parameters.The function must return an array with the same number of elements as there were linesin the original data frame,and each entry in the array should correspond to the result of running the model with the corresponding parameter combination.Wewill cover the case in which a model outputs more than a single number in section4.If your model is already written in R,and accepts a single combination of values,it is easy to write a“wrapper”using the function mapply to your model.In the example below,the function oneRun receives three numbers,corresponding to r,K and X0,and returns a single value corresponding to thefinal population.The function modelRun encapsulates this function,in a manner to receive a data.frame containing all parameter combinations and returning the results in one array.Make SURE that the order in which the parameters are defined above is the same in which they are being passed to the function.>oneRun<-function(r,K,Xo){+X<-Xo+for(i in0:20){+X<-X+r*X*(1-X/K)+}+return(X)+}>modelRun<-function(my.data){+return(mapply(oneRun,my.data[,1],my.data[,2],my.data[,3])) +}If your model is written in a different language,as C or Fortran,it is possible to write an interface with R by compiling your model as a shared library,and dynam-ically loading this library[2].Also,you should consider uncoupling the simulation and the analyses(see section5).3Uncertainty and sensibility analysesWefirst use the LHS function to generate a hypercube for your model.The manda-tory arguments for this function are:model,the function that represents your model; factors,an array with the parameter names;N,the number of parameter combina-tions to be generated;q,the names of the PDF functions to generate the parameter values2;and q.arg,a list with the arguments of each pdf.We have already con-structed suitable objects to pass to this function above,so now we simply call the LHS function:2Which can be one of the the built-in quantile functions as qnorm for normal,qbinom for binomial,qpois for poison,qunif for uniform,etc;truncated normal distribution can be foundon package“msm”,and the quantiles of an empirical data set can be used by creating a wrapper function for the quantile function:>my.quantile<-function(p,data)quantile(x=data,probs=p)>library(pse)>myLHS<-LHS(modelRun,factors,200,q,q.arg,nboot=50) The extra parameter nboot is used to bootstrap the correlation coefficients(see below).To access the values of the parameters used in the model,use the function get.data(myLHS).To access the results,use get.results(myLHS).With the object returned by the function LHS,we will exemplify in this section four techniques that can be used:the uncertainty analysis using the ecdf,scatter-plots of the correlation between each parameter and the result using the function corPlot,partial rank correlation using the function plotprcc and agreement be-tween different hypercube sizes with the function sbma.3.1ECDFThe ecdf,short for empirical cumulative distribution function,may be used to illustrate the distribution of the model results,in our case the final population.With this graph,we can see that the final population for our species is,with high probability,between 35and 45.>plotecdf(myLHS)323436384042440.00.20.40.60.81.0LHS$res[, index.res]P r o p o r t i o n <=xn:200 m:03.2ScatterplotsHere,we can see a scatterplot of the result as a function of each parameter.As all the parameters are being changed for each run of the model,the scatterplots look like they were randomly generated,even if the underlying model is deterministic.This weird behaviour with larger values of r is an example of a bifurcation,and will ultimately lead to chaotic solutions [3].>corPlot(myLHS)1.41.61.82.032343638404244r V13738394041424332343638404244KV1010********32343638404244X0V13.3Partial correlationThe partial (rank)correlation coefficient (pcc or prcc)measures how strong are the linear associations between the result and each input parameter,after removing the linear effect of the other parameters.The confidence intervals shown in this plot were generated by bootstraping.>plotprcc(myLHS)O1rK X0−1.0−0.50.00.51.0In the ecological literature,it is usual to refer to the partial derivatives of the model response in respect to each parameter as “the sensitivity”of the model re-sponse in respect to each parameter.One analog measure in stochastic models is the Partial Inclination Coefficient (pic)of the model response in respect to each parameter.Please note that in the current version of the package,the pic function only works for models with one response variable,and should be considered in beta :>p <-pic(myLHS)>print(p$pic)V1r -1.521785833K 0.982111569X00.0018788913.4Agreement between runsIn order to decide whether our sample size was adequate or insufficient,we calculate the Symmetric Blest Measure of Agreement(SBMA)between the PRCC coeffients of two runs with different sample sizes.>newLHS<-LHS(modelRun,factors,300,q,q.arg)>(mySbma<-sbma(myLHS,newLHS))[1]0.375A value of-1indicates complete disagreement between the runs,and a value of 1indicates total agreement.As the SBMA seldom reaches1for realistic models, some criterion must be used to indicate when the agreement should be considered good enough.4Multiple response variablesIn the previous section,we have examined a model that returned a single number, namely,thefinal population.However,we might be interested in examining the effects of the parameters in several distinct responses from the model.In our exam-ple,we are interested in determining the effect of the parameters to the population in each of thefirst6time steps.The theory and tools for this analysis remain mostly the same.We will write our model to return an array now,as:>factors<-c("r","K","X0")>q<-c("qnorm","qnorm","qunif")>q.arg<-list(list(mean=1.7,sd=0.15),list(mean=40,sd=1),+list(min=1,max=50))>Time<-6>oneRun<-function(r,K,Xo){+X<-array();+X[1]<-Xo;#Caution,Xo gets overwritten+for(i in1:Time){+Xl<-X[length(X)]+X[i]<-Xl+r*Xl*(1-Xl/K)+}+return(X)+}>modelRun<-function(dados){+mapply(oneRun,dados[,1],dados[,2],dados[,3])+}The hypercube is generated exactly in the same way.However,now we have the option to give names(which will be used in the plots below)to each response variable.>s<-paste("Time",1:Time)>myLHS<-LHS(modelRun,factors,100,q,q.arg,s,nboot=50)4.1ECDFThe first plot we will produce will,again,be the ECDF.We may produce several plots using the parameter “stack=FALSE”,or stack all the plots in the same graph,using “stack=TRUE”:>plotecdf(myLHS,stack=TRUE)10203040500.00.20.40.60.81.0datP r o p o r t i o n <= xn:600 m:0123456We may notice that the population values are spread over a wider range in the first time steps,but converge to a narrow distribution on time 6.4.2ScatterplotsNext,we investigate the correlation plots for the variables with each input parame-ter.To reduce the number of plots,we will present results just for the time steps 1,3and 6,using the “index.res”parameter,and supress the linear model from being ploted with the parameter “add.lm”:>corPlot(myLHS,index.res=c(1,3,6),add.lm=FALSE)1.4 1.61.82.010203040rT i m e 11.41.61.82.0202530354045rT i m e 31.41.61.82.036404448rT i m e 638394041421020304KT i m e 13839404142202530354045KT i m e 3383940414236404448KT i m e 6010********1020304X0T i m e 11020304050202530354045X0T i m e 3102030405036404448X0T i m e 64.3Partial correlationThe partial correlation plots also accept the “index.res”argument:>plotprcc(myLHS,index.res=c(1,3,6))Time 1r K X0−1.0−0.50.00.51.Time 3r K X0−1.0−0.50.00.51.Time 6rK X0−1.0−0.50.00.51.4.4Agreement between runsWe have seen how the function sbma measures the agreement between two runs in the previous section.Now,we will use the function target.sbma to run several hypercubes until a pair of runs provides us with an agreement equal to or better than a limit specified in itsfirst argument.>targetLHS<-target.sbma(target=0.3,modelRun,factors,+q,q.arg,s,FUN=min)[1]"INFO:initial run..."[1]"INFO:LHS with N=105"[1]"sbma of0.375(target0.3)"As the SBMA is calculated for each response variable independently,we must decide how to combine these values.The argument“FUN=min”is telling the function to consider only the minimum value.5Uncoupling simulation and analysisIn many scenarios,it is necessary to run the simulation and the analyses at different times,and even in different computers.It may be the case,for example,that your lab computer is not fast enough to run the simulations,but that the high-performance cluster in which the simulations are to be run do not have R installed. In order to do this,however,you must generate the Latin Hypercube in the lab computer,transfer this information to the cluster,run the simulations there,transfer the results back to the lab computer,and then run the analyses.In order to generate the samples without running a model,use the function LHS with the parameter model=NULL and save the samples in the desired format:>uncoupledLHS<-LHS(model=NULL,factors,50,q,q.arg)>write.csv(get.data(uncoupledLHS),file="mydata.csv") Then run the model using the data.To incorporate the results into the LHS object,use the function tell:>coupledLHS<-tell(uncoupledLHS,myresults)Then you may proceed with the analyses using prcc,ecdf,etc.References[1]A.Chalom and P.I.K.L.Prado,Parameter space exploration of ecological models,arXiv:1210.6278[q-bio.QM],2012.[2]C.Geyer,Calling C and Fortran from R,/geyer/rc/[3]J.D.Murray,Mathematical Biology I:An Introduction,vol.17of Interdisci-plinary Applied Mathematics,Springer,New York,NY,USA,2002.。