PP Scripts Notes

语法

赋值

A > B ? A : B;

替换

options
g:做 "全局 "匹配(匹配所有出现的模式)。如果不指定,则只匹配字符串中的第一次出现。
i:进行不区分大小写的模式匹配
m:将字符串视为多行。
s:将字符串作为单行处理
x:通过允许空白和注释来扩展模式的可读性。

rsubst(Source, '替换前', '替换后', options)

拼接

d := '''Hello''';
e := 'SELECT * FROM Table WHERE Table.Name='. d . ' Order By ID DESC';

print(SELECT * FROM Table WHERE Table.Name='Hello' Order By ID DESC)

Quoted String					Interpretation
'Hello'							Hello
'''Hello'''						'Hello'
'"Hello"'						"Hello"
'Isn''t this fun'				Isn’t this fun
'This isn''t C\n'				This isn’t C\n
"This is a C-style string\nwith an embedded newline"	This is a C-style string with an embedded newline

Initial Expression / Expression / Final Expression

#i := 0;  // #i 是局部变量, 在同一个组件内中都可以使用,在同一个组件外不可以使用

获取层级结构数据

rename("id","taskid");
#specid:=nodegetfirstChild(dataroot(),'specificationMethod');
SpecificationMethod:=nodeproperty(#specid,'id');
keep('taskid','SpecificationMethod');
@taskId:=taskid;

时间

format := DateProposeFormat('2021-12-31');
date := "05/12/2021 15:42";
DateSetFormat(date, format);
dateString := DateText(date);

print: 2021-05-12

For 循环

// 1
For #i in 1 ... ArrayNumRows(data) Loop
    pass;
End Loop;

// 2
Expand(';',uris);
@CISProServerRoot := uris[1]; //default 
for #i in 1 .. ArrayNumRows(uris) loop
	if uris[#i] rlike '^http://' then // if https available
		@CISProServerRoot := uris[#i]; 
		break;
	end if;
end loop;

// 3
#names := Array('class', 'containerId', 'name', 'instanceName', 'templateName');
forEach #name in #names loop
	if Property(#name) is not defined then
		Property(#name) := '';
	end if;
end loop;

Property List

IthProperty		// 根据下标取值
IthPropertyName		// 根据下标取Name
Keep			// 保留指定字段
LocalProperty		// 局部变量
MetaDataProperties	//
MetaDataProperty
NumProperties		// 当前所有的字段
Property		// 通过Name进行操作字段
Remove			// 移除指定字段
RemoveAll		// 移除所有字段
RemoveMetaData
Rename			// 重命名
Reorder			// 字段显示顺序
RKeep			// 正则表达式保留字段
RPropertyNames		// 正则达表示获取一组字段
RRemove			// 正则表达式移除字段
SearchAll		// 查询字段是否存在

for #i in 1 .. NumProperties() loop
    #propertyName := IthPropertyName(#i);
    if isNull(IthProperty(#i)) then // is ith property null?
        IthProperty(#i) := '';
    end if;
end loop;

调用Protocol

Results := RunProtocol('Protocol/A/b.pp', "HttpStatus", "...")

Property Type

Boolean
ChangePropertyType
	BitFingerprint \ BitFingerprintArray \ Bitset \ BitsetArray \ Boolean \ BooleanArray
	 \ Byte \ ByteArray \ DateTime \ Double \ DoubleArray \ DoubleFingerprint \ Integer
	  \ IntegerArray \ IntegerFingerprint \ Missing \ NDimensionalArray \ NDimensionalaValueArray
	   \ Null \ NullArray \ String \ StringArray \ StringFingerprint \ ValueArray \ DefineProperty  // newvar := DefineProperty('IntegerFingerprint');
Double
GetPropertyType
Integer
IsDate
IsInteger
IsNull
IsNumber
String

Statistics Function

BinomialCDF		// 二项式累积分布函数pbinom(x, n, p)  BinomialCDF(2, 3, 0.5) returns 0.875 
BinomialPDF		// 二项式概率密度函数dbinom(x, n, p)  BinomialPDF(2, 3, 0.5) returns 0.375 
ChisqCDF		// 返回自由度为df的分布在x点的卡方累积分布函数pchisq(x, df)  ChisqCDF(1.0, 2) returns 0.393469
Finverse		// F分布的倒数。等于自由度df1和df2时,在显著性水平p下拒绝无效假设所需的F统计量的阈值。所有参数必须是非负数,p必须小于或等于1。相当于R函数调用qf(1.0 - p, df1, df2)。 Finverse(0.05, 10, 10) returns 2.9782
GaussianCDF		// 返回x点的高斯(正态)累积分布函数pnorm(x, mean=mean, sd=sd)  GaussianCDF(0.0, 1.0, 0.0) returns 0.5
GaussianPDF		// 返回x点的高斯(正态)概率密度函数dnorm(x, mean=mean, sd=sd)  GaussianPDF(0.0, 1.0, 0.0) returns 0.39894 (that is, 1/sqrt(2*pi))
IncompleteBeta		// 返回参数a和b在x点的正则化不完全β函数pbeta(x, a, b)  IncompleteBeta(0.5, 1, 2) returns 0.75

Array Function

Resize(A, 0);
Append(A, 'Apple');
Append(A, 'Banana');
Append(A, 'Cherry');
Append(A, 'Dutch');

B := Array('Apple', 'Banana', 'Carrot');

C := ArrayGetDimensions(B);  // 返回数组长度

Resize(arr, 24, 16, 3);
D := ArrayNumColumns(arr);  // 返回数组第二维的长度
//Append(arr, 'Apple', 'Apple');

E := ArrayNumDimensions(arr);  // 返回数组最后一维的长度
//Append(arr, 'Apple', 'Apple');

F := ArrayNumRows(arr);  // 返回一个数组的第一位的长度

G := ArrayNumValues(arr); // 返回一个数组中元素总数

ArrayResize(H, 3);  // 强制将属性newArray转化为一个数组
Append(H, 'Banana');
Append(H, 'Cherry');
Append(H, 'Dutch');

clear(H);  // 清空

I := Contains(A, 'Dutch');  // 在数组中找值

JString := 'Apple; Cherry; Dutch';
Expand('; ', JString);  // 切割str为数组
J := JString;
Contract('-', JString);  // 合并数组为str
K := JString;

InsertValue(A, 'Each', 1);  // 数组中插入值
InsertValue(A, 'Face', 1);  // print: Face Each Apple Banana Cherry Dutch

L := Array(1231,234,765,6723);
NumberSort(L);  // 排序

resize(@a, 3);
@a[1] := 1; 
@a[2] := 2; 
@a[3] := 3;
M := 0; 
FOR #i IN 1 .. numvalues(@a)  // 3 返回数组属性var或数组arr的尺寸。大多数标量返回1。空值则返回0。
LOOP 
	M := M + @a[#i]; 
END LOOP; 

Resize(N, 8);
N[1] := 'Aardvark';
N[2] := 'Hamster';
N[3] := 'AardvaRK';
N[4] := 'Hamster';
N[5] := 'banana';
N[6] := 'Banana';
REMOVEDUPLICATES(N);  // 去重(只区分大小写)  print:Aardvark Hamster AardvaRK 10

RemoveValue(N, 2);  // 删除  print:Aardvark AardvaRK 10

Sort(N);  // 排序(区分大小写,先大后小)

Resize(Name, 3);
Resize(Phone, 3);
Name[1] := 'Sue';
Phone[1] := '555-1234';
Name[2] := 'Anne';
Phone[2] := '555-5678';
Name[3] := 'Terese';
Phone[3] := '555-9012';
SORTN(Name, Phone);  // 根据Name同步排序Name和Phone

Property List Functions // 列表

IthProperty // 值
IthPropertyName // 下标
keep
LocalProperty

@name := 'a';
LocalProperty('a') := 10;
LocalProperty(@name) += 10;
b := #a;
print:   a=20, b=20

MetaDataProperties // 返回给定属性上存在的所有元数据属性的数组
MetaDataProperty

This example tests whether the 'Currency' metadata property is defined. If not, it is added and set to 'USD'.

IF (MetaDataProperty(Price, 'Currency') IS NOT DEFINED) THEN
  MetaDataProperty(Price, 'Currency') := 'USD';
END IF;
The script below shows an example of adding metadata to a global property.

MetaDataProperty(@NumRecords, 'Source') := 'F45';

NumProperties

Resize(@List, 0);
FOR #i in 1 .. NumProperties() LOOP
    APPEND(@List, IthPropertyName (#i));
END LOOP;

notes:Creates a global array @List containing the names of all properties on the data record.

Property // 深拷贝

@name := 'a';
Property('a') := 10;
Property(@name) += 10;
b := Property(@name);

print: a=20; b=20

RemoveMetaData // 字典删除

RemoveMetaData('Weight', 'Units');

notes:Removes the metadata 'Units' from the property 'Weight'.

Hash Table

HashValueCreate		创建		@Table := HashValueCreate();
HashAdd			由键添加值	HashAdd(@Table, 'Age', 10);	
HashAppendValue		由键插入值	HashAppendValue(@Table, 'Maxima', 10.1);
HashContains		是否包含		HashContains(@Table, Name)
HashFind			是否找到		HashFind(@Table, Name)
HashFindIndex		找下标		HashFindIndex(@Table, Name)
HashIthKey		下标找键		HashIthKey(@Table, #i)
HashIthValue		下标找值		HashIthValue(@Table, #i)
HashNumValues		返回长度		HashNumValues(@Table)
HashRemove		移除		HashRemove(@Table, Name);
HashClear		清空		HashClear(@Table);

Array 数组

Append					添加				Append(A, 'Apple');
Array					新建				#list := Array('Apple','Banana','Carrot');
ArrayGetDimensions		获取长度			dims := ArrayGetDimensions(oldArray);
ArrayNumColumns			获取第二维的长度	Resize(arr, 24, 16);
										#numColumns := ArrayNumColumns(arr);
ArrayNumDimensions		获取维数(几维)	Resize(arr, 24, 16, 3);
										#numDim := ArrayNumDimensions(arr);
ArrayNumRows			获取第一维长度		
ArrayNumValues			获取元素总数		Resize(arr, 24, 16);
										#numElements := ArrayNumValues(arr);	//384
ArrayResize				重置为#dims维		ArrayResize(newArray, #dims); 
Clear					清空
Contains				是否包含			Contains(Array, 'a') eq true
Expand					str->array		Expand(';', A);
Contract				array->str		Contract('-', A);
InsertValue				插入				InsertValue(A, 'Cherry', 2);
NumberSort				升序排序
numvalues				值的数量		numvalues(@a)
RemoveDuplicates		去重(分大小写)
RemoveValue				删元素				RemoveValue(A,2)
Resize					设置长度		Resize(A, 10)
Sort					升序排序
SortN					根据A排序		SORTN(A, B)  //A,B同时按照A排序

Control 控制

Assert					断言				Assert(#i == numValues, "Processing incomplete");
BlockPipeline			break				BlockPipeline()
DataSetPort				覆盖返回当前数据记录的标准端口
Error					抛出异常(如果组件没处理)	Error('Hello World')
HaltProtocol			终止当前Component运行
TerminatePipeline		终止当条数据流				DownStream-读所有数据进行过滤
												UpAndDownStream-每条数据都进行过滤
												Source-每条都过滤并只允许数据流至指定Port

Date and Time 时间

Date					创建一个日期				Date('23.07.1957','%d.%m.%Y');
DateCurrent				当前日期
DateFromYMD				通过年月日创建日期			DateFromYMD(1987, 7, 23);
DateProposeFormat		日期格式化					format_:=DateProposeFormat('2022-01-31');
												DateSetFormat(DateCurrent(), format_);
DateTime				创建一个日期+时间			DateTime('2022-02-27 02:03:04')
DateTimeCurrent			当前日期+时间
DateTimeFromYMDHMS		通过年月日时分秒创建
Time					创建一个时间
TimeCurrent				创建当前时间
TimeFromHMS				通过时分秒创建

DateFormat				查看时间的格式
DateTimeZone			返回当前时区				DateTime('July 10, 2006 11:10:00 GMT')
DateText				当前日期(英文)
DateYear				年
DateMonth				月
DateMonthText			月(英文)					DateMonthText(CurrentDate, False);
												True简/False全
DateDayOfMonth			这个月第几天
DateHour				今天第几个小时
DateMinute				分
DateSecond				秒
DateMilliseconds		毫秒
DateDayOfYear			今年的第几天
DateDayOfWeek			这周第几天
DateDayOfWeekText		周几(英文)
DateJulian				儒略日时间(天*24)
DateSecondsSince1970	自1970年以来的秒数


DateAddDays				加几天						DateAddDays(D, 4);
DateAddHours			加几小时					DateAddHours(D, 4);
DateAddMilliseconds		加毫秒
DateAddMinutes			加分
DateAddMonths			加月
DateAddSeconds			加秒
DateAddYears			加年
DateChangeTimeZone		改时区
DateSetDayOfMonth		改到这个月的某一天			DateSetDayOfMonth(D, 31);
DateSetFormat			格式化(不好用)
DateSetText				设日期+时间
DateSetJulian			设时间+日期(儒略)			DateSetJulian(D, 2453810.6159838);
DateSetSecondsSince1970	设时间(自1970年以来的秒)
DateSetYear				设年
DateSetMonth			设月
DateSetHour				设时
DateSetMinute			设分
DateSetSecond			设秒
DateSetMilliseconds		设毫秒
DateSetTimeZone			设时区

DateDaysBetween			时间间隔几天
DateDaysInMonth			这个月几天
DateFieldIsDefined		是否设置				1年2月3日4时5分6秒7毫秒
DateFillUndefined		自动填充未设置的日期+时间
												tt := datetimecurrent();
												datesetformat(tt, '%Y/%m/%d %H:%M');
												ss := DateText(tt);
DateIsDST				是否处于夏令时期间
DateIsLeapYear			年份是闰月
DateLocalToGMT			转格林威治时间所需的小时数	DateLocalToGMT();  // -8
DateSetFieldUndefined	使指定字段加密				1年2月3日4时5分6秒7毫秒
												DateSetFieldUndefined(T, 5);// 12:**:00
DateWeekOfYear			今年第几周
DateWeekOfYearYear		这周在哪年

将UTC转北京时间-lastUpdated
format := DateProposeFormat('29-Feb-2004 23:59:59')
datechangetimezone(lastUpdated, 'CCT');
d2 := Date(lastUpdated);
DateSetFormat(d2, format);
lastUpdated := DateText(d2);

将1970年以来的秒变时间
dataS := DateSecondsSince1970();
format_ := DateProposeFormat('2007-12-31 23:59:59');
D := DateTime('');
DateSetSecondsSince1970(D, dataS);
datechangeTimeZone(D, 'CCT');
DateSetFormat(D, format_);
ResultDate := DateText(D);

GetDate					获取日期				GetDate(True)
GetTime					获取时间				GetTime(True)

Debug

DebugBreak
DebugMessage
DebugMessageError

File

FileChecksum
FileDelete
FileExists
FileLastModified
FileOwner
FileRename
FileSize

Global Property List

GlobalProperty				创建
IthGlobalProperty			返回给定位置号的全局属性的一个值
IthGlobalPropertyName		返回全局属性列表中第i个全局属性的名称。
NumGlobalProperties			返回全局属性列表中全局属性的数量。
RemoveGlobal				移除
RenameGlobal				改名
RGlobalPropertyNames		正则匹配全局属性列表

Hierarchical Functions

AddChild				添加子节点		AddChild('/*/Molecule/', 'A', 'B'); 
DataRoot				返回数据记录的根节点的节点引用。
DataSetRoot				用一个新的节点替换当前的数据记录根节点。当前根节点的所有子节点也被移除,1-通过  2-失败 0-丢弃 -1使用默认端口						并被新节点的子节点替换
GlobalRoot				返回全局根节点的节点引用	
							#SavedDataRoot := NodeAppendChild(GlobalRoot(), DataRoot());
IsValidLocation			如果位置是有效的	IsValidLocation('/SciTegic.data.GroupNode/')
NodeAppendChild			将给定的节点追加到子节点列表的末尾	
								#newnode := NodeAppendChild(#ParentNode, "generic");
NodeDelete				从层次结构中删除给定的节点
NodeDeleteAllChildren	删除给定节点的所有子节点
NodeDeleteChild			从父节点中删除一个子节点	
								NodeDeleteChild(#ParentNode, #ChildNode);
NodeGetFirstChild		返回对指定类型的第一个子节点的引用如果没有指定节点类型,将返回第一个子节					点。在调用这个函数之前,请调用NodeHasChild()以确保一个合适的节点确实存在。
								#acmeNode = NodeGetFirstChild(GlobalRoot(), "acme");
NodeHasChild			确定一个节点是否有一个指定的子节点。
								NodeHasChild(GlobalRoot(), "acme")
NodeIsNull				节点是否为空		NodeIsNull(NodeParent(#node));
NodeIthChild			返回一个对第i个子节点的引用。		NodeIthChild(#Node, #i);
NodeIthProperty			获取节点的第i个属性。				NodeIthProperty(#root, #i); 
NodeIthPropertyName		返回节点上第i个属性的名称。			NodeIthPropertyName(#root, #i)
NodeMetaDataProperties	
NodeMetaDataProperty
NodeNumChildren
NodeNumProperties
NodeParent
NodePathLocation
NodeProperty
NodePropertyQuery
NodeQuery
NodeRemoveAll
NodeRemoveMetaData
NodeRemoveProperty
NodesEqual
NodeSerialize
NodeSetType
NodeType
NumChildren

Python(on Server)

props = data.getProperties()
globals = context.getGlobalProperties()
params = context.getComponentParameters()

props['myprop'] = 42
val = props['myprop']

props.defineIntProperty('myprop', 42)  # 类型转换
val = props.get('myprop').getValue().getInteger()

globals = context.getGlobalProperties()  # 获取全局属性
params = context.getComponentParameters()  # 获取组件参数
name = globals['username']  # 获取全局属性'username'

# 将数据发送给 Pass/Fail端口
if props['index'] < 5:
	data.routeTo(pilotpython.FAIL_PORT)
elif props['index'] > 10:
	data.routeTo(pilotpython.PASS_PORT)
else:
	data.routeTo(pilotpython.NO_PORT)

# Python 列表
defineXxxxArrayProperty()

# Python 列表 <=> PP Array
pythonListFromPPArray = props['index']
isList = isinstance(pythonListFromPPArray, list)
props['isList'] = isList
pythonList = [10, 9, 8]
props['PPArrayFromPythonList'] = pythonList

# debug
context.debugMessage('string')  # print
context.debugMessageError('oops')  #print
context.debugBreak('Breakpoint in onInitialize')  #alert

# 默认库
 NumPy
 SciPy
 Pandas
 Scikit-Learn
 Matplotlib

 Use Python’s importlib.reload() function to force a reload.

# 导入库: 对于简单的,如一个.py文件,使用PythonPath
Python Library Settings -> PythonPath : C:\python3\venv\myVenv\Lib\site-packages
# 导入库: 更复杂的库,可作为PP软件包安装
在软件包的.conf中
<python>
	pythonPath $(package)/data/python/testpackage1
    pythonPath $(package)/data/python/testpackage2
</python>
在组件上: Python Library Settings -> Use Pipeline Pilot Package : acme/makemybeer

中止指令

Block Pipeline();

等待指令

DataSetPort();

弹窗指令

error("Hello World!");

暂停指令

Halt Protocol();

强制终止

Terminate Pipeline();

去重组件

First Occurrence Filter 组件

Json获取下级数据

Detach Node

Json获取指定层级的数据

Detach Nodes

Json将所有层级数据显示在一层

Flatten Hierarchy

LES Script

summary("max",select("1.1-Area",where(parameter("Peak Name")=="Main Peak")))
parameter("1.2-实际录入值", "actual")>parameter("1.2-Spec", "actual")? "大于Spec":"小于Spec"
parameter("...", "...","formatted")
parameter("1.4-Formatted Value", "actual","formatted")>=5.0?"pass":"fail"

posted @ 2021-04-13 17:30  小小小光子  阅读(48)  评论(0编辑  收藏  举报