def test_double_conversion(): """Test double conversion.""" assert System.Double.MaxValue == 1.7976931348623157e308 assert System.Double.MinValue == -1.7976931348623157e308 ob = ConversionTest() assert ob.DoubleField == 0.0 ob.DoubleField = 1.7976931348623157e308 assert ob.DoubleField == 1.7976931348623157e308 ob.DoubleField = -1.7976931348623157e308 assert ob.DoubleField == -1.7976931348623157e308 ob.DoubleField = System.Double(1.7976931348623157e308) assert ob.DoubleField == 1.7976931348623157e308 ob.DoubleField = System.Double(-1.7976931348623157e308) assert ob.DoubleField == -1.7976931348623157e308 with pytest.raises(TypeError): ConversionTest().DoubleField = "spam" with pytest.raises(TypeError): ConversionTest().DoubleField = None
def testDoubleConversion(self): """Test double conversion.""" self.failUnless(System.Double.MaxValue == 1.7976931348623157e308) self.failUnless(System.Double.MinValue == -1.7976931348623157e308) object = ConversionTest() self.failUnless(object.DoubleField == 0.0) object.DoubleField = 1.7976931348623157e308 self.failUnless(object.DoubleField == 1.7976931348623157e308) object.DoubleField = -1.7976931348623157e308 self.failUnless(object.DoubleField == -1.7976931348623157e308) object.DoubleField = System.Double(1.7976931348623157e308) self.failUnless(object.DoubleField == 1.7976931348623157e308) object.DoubleField = System.Double(-1.7976931348623157e308) self.failUnless(object.DoubleField == -1.7976931348623157e308) def test(): ConversionTest().DoubleField = "spam" self.failUnlessRaises(TypeError, test) def test(): ConversionTest().DoubleField = None self.failUnlessRaises(TypeError, test) def test(): ConversionTest().DoubleField = 1.7976931348623159e308 self.failUnlessRaises(OverflowError, test) def test(): ConversionTest().DoubleField = -1.7976931348623159e308 self.failUnlessRaises(OverflowError, test) def test(): value = System.Double(1.7976931348623159e308) self.failUnlessRaises(OverflowError, test) def test(): value = System.Double(-1.7976931348623159e308) self.failUnlessRaises(OverflowError, test)
def create(sequence_path, target, parameters, debug, timeout): """ Creates an instance of niveristand.clientapi._sequencecallinfo._SequenceCallInfo class. Args: sequence_path (str): The file path of the sequence file to execute. target (str): The name of the target on which to execute the sequence. parameters (list[niveristand.clientapi._sequenceparameterassignmentinfo._SequenceParameterAssignmentInfo]): The parameter assignments for the sequence. debug (bool): Whether the sequence executes in debug mode. timeout (float): The timeout in milliseconds within which the sequence must complete each time step. Returns: niveristand.clientapi._sequencecallinfo._SequenceCallInfo: Newly created instance. """ if target is None: target = "" target = System.String(target) sequence_path = System.String(sequence_path) debug = System.Boolean(debug) timeout = System.Double(timeout) parameters_dot_net = [ parameter.dot_net_instance for parameter in parameters ] parameters_dot_net_array = System.Array[ SequenceParameterAssignmentInfo](parameters_dot_net) sequence_call_info_dot_net = \ SequenceCallInfoDotNet(sequence_path, target, parameters_dot_net_array, debug, timeout) sequence_call_info = _SequenceCallInfo(sequence_call_info_dot_net) return sequence_call_info
def Evaluate(self, sched): sum = 0 for eit in sched.AllStates.Events: for assetTask in eit.Tasks: task = assetTask.Value sum += task.Target.Value if(task.Type == TaskType.COMM): callKey = "EvalfromSSDR" + "." + assetTask.Key.Name foo = self.Dependencies.GetDependencyFunc(callKey) sum += System.Double(foo(eit)) return sum
def move_absolute(self, new_position): '''Moves stage to the given position in range of +/- 150 mm ''' time_to_sleep=(abs(self.position_current-new_position))/self.velocity if (new_position<self.position_max)and(new_position<self.position_min): self.myXPS.GroupMoveAbsolute(System.String(self.StageName),[System.Double(new_position)],System.Int32(1),System.String("")) self.position_current=new_position time.sleep(time_to_sleep) print('Stage was moved to '+str(new_position)) else: print('position is out of range')
def write(self, filename, data): """Writes data to the pre-created dfs0 file. filename --> file path to existing dfs0 file. data --> numpy matrix with data. """ if not path.exists(filename): raise Warning("filename - File does not Exist %s", filename) try: dfs = DfsFileFactory.DfsGenericOpenEdit(filename) except IOError: print('cannot open', filename) delete_value = dfs.FileInfo.DeleteValueFloat n_items = len(dfs.ItemInfo) nt = dfs.FileInfo.TimeAxis.NumberOfTimeSteps if len(np.shape(data)) == 1: data = data.reshape(len(data), 1) # Makes sure the data to write to the file matches the dfs0 file if nt != data.shape[0]: print("Inconsistent data size. nt (row count) must be size" + str(nt)) # quit() if n_items != data.shape[1]: print( "Inconsistent data size. number of items (column count) must be size" + str(n_items)) data[np.isnan(data)] = delete_value d = Array.CreateInstance(System.Single, 1) # Get the date times in seconds (from start) t = [] for i in range(nt): itemData = dfs.ReadItemTimeStep(1, i) newTime = DfsExtensions.TimeInSeconds(itemData, dfs.FileInfo.TimeAxis) t.append(newTime) dfs.Reset() # COPY OVER THE DATA for it in range(dfs.FileInfo.TimeAxis.NumberOfTimeSteps): tit = System.Double(t[it]) for ii in range(len(dfs.ItemInfo)): d = Array[System.Single](np.array([[data[it, ii]]])) dfs.WriteItemTimeStepNext(tit, d) dfs.Close()
def getTxAtt_dBm(self,channel): att_dBm = 0 result = self.Link.Talise.GetRxTxEnable(0,0)#ironpython just has 2 return val rxstate = result[-2] txstate = result[-1] a = System.Double(0) self.Link.Talise.SetRxTxEnable(rxstate, self.Link.Talise.TxChannel.Tx1Tx2) if channel == 1: att_dBm = self.Link.Talise.GetTxAttenuation(self.Link.Talise.TxChannel.Tx1,a) elif channel == 2: att_dBm = self.Link.Talise.GetTxAttenuation(self.Link.Talise.TxChannel.Tx2,a) self.Link.Talise.SetRxTxEnable(rxstate, txstate) return att_dBm/1.e3
def DivDist2D(crv, dist): ## 以下を改造しました ## Hiroaki Saito : GH C#_Divide Distance With List ## https://openddl.com/post/166/ ## 閲覧:2021/6/2 pln = Plane.WorldXY points = [] paramList = [] if crv: tmpParam = 0. pt = crv.PointAtStart dummy_out = System.Double(0) tmpParam = crv.ClosestPoint(pt, dummy_out)[1] points.append(pt) paramList.append(tmpParam) for i in range(len(dist)): d = System.Double(dist[i]) circle = Circle(pln, points[i], d) tmpCrv = circle.ToNurbsCurve() ci = Intersection.CurveCurve(crv, tmpCrv, 0, 0) addCheck = False tmpList = sorted(ci, key=lambda x: x.ParameterA) for item in tmpList: tmpParam = item.ParameterA if tmpParam > paramList[i]: points.append(item.PointA) paramList.append(tmpParam) addCheck = True break if not addCheck: break pt = crv.PointAtEnd points.append(pt) return points
def test_wrong_overload(): """Test regression in which implicit conversion caused the wrong types to be used. See #131 for issue. Fixed by #137, #151""" # Used to return `50L` res = System.Math.Abs(50.5) assert res == 50.5 assert type(res) == float res = System.Math.Abs(-50.5) assert res == 50.5 assert type(res) == float res = System.Math.Max(50.5, 50.1) assert res == 50.5 assert type(res) == float res = System.Math.Max(System.Double(10.5), System.Double(50.5)) assert res == 50.5 assert type(res) == float # Should it return a System.Double? res = System.Math.Max(System.Double(50.5), 50.1) assert res == 50.5 assert type(res) == float
def NurbCrv(P, W, K): n = 3 P_ = List[Point3d]() for p in P: P_.Add(Point3d(p[0], p[1], p[1])) nc = NurbsCurve.Create(False, n, P_) for i in range(len(P)): # cp = ControlPoint() # cp.X = P[i][0] # cp.Y = P[i][1] # cp.Z = P[i][2] # cp.W = W[i] w = System.Double(W[i]) cp = ControlPoint(P[i][0], P[i][1], P[i][2], w) nc.Points[i] = cp for i in range(nc.Knots.Count): nc.Knots[i] = K[i] C = nc return C
def add_steps_to_ts(plist, ts_path): tmgr = app.Modules.Get('Time series Manager') ts = tmgr.TimeSeriesList.Fetch(ts_path) timestepts = ts.FetchAll() if(timestepts.Count > 0): lastTimestep = timestepts[timestepts.Count - 1].XValue else: lastTimestep = DateTime.MinValue count = 0 for x, y in plist: date = x if date > lastTimestep: value = System.Double(y) step = ts.CreateNew() step.XValue = date step.YValue = value ts.Add(step) count+=1 tmgr.TimeSeriesList.Update(ts)
def position_get(self): pos=self.myXPS.GetCurrentPosition(System.Double(0),System.Double(0),System.Int32(1),System.Int32(1),System.Int32(1),System.Int32(1),System.String(self.StageName)) return pos
def setTxAtt_dBm(self,channel,att_dBm): if channel == 1 or channel== 3: self.Link.Talise.SetTxAttenuation(self.Link.Talise.TxChannel.Tx1,System.Double(att_dBm)) if channel == 2 or channel== 3: self.Link.Talise.SetTxAttenuation(self.Link.Talise.TxChannel.Tx2,System.Double(att_dBm))
def test(): value = System.Double(-1.7976931348623159e308)
def ImportFromSentekIrrimaxWeb(spreadsheetpath): """ <Script> <Author>ARE</Author> <Description>This will import measurements of Sentek agricultural probes from vendors online platform (www.irrimaxlive.com). All Settings and further description are provided through the configuration spreadsheet </Description> <Parameters> <Parameter name="spreadsheetpath" type="String">path to config spreadsheet</Parameter> </Parameters> <ReturnValue type="IType">None</ReturnValue> </Script> """ # write your code here # In[ ]: # get Settings from Spreadsheet print("reading settings from {}:".format(spreadsheetpath)) sheetName = "Configuration" sheetMgr = app.Modules.Get("Spreadsheet Manager") importSheetConfig = sheetMgr.OpenSpreadsheet(spreadsheetpath) api_key = sheetMgr.GetCellValue(importSheetConfig, sheetName, 2, 1) print("\tusing API Key: "+api_key) from_time_d = sheetMgr.GetCellValue(importSheetConfig, sheetName, 3, 1) from_time = DateTime(1899,12,30).AddDays(from_time_d) print("\tabsolute import period starts {} ".format(from_time)) to_time_d = sheetMgr.GetCellValue(importSheetConfig, sheetName, 4, 1) to_time = DateTime(1899,12,30).AddDays(to_time_d) print("\tabsolute import period ends {}".format(to_time)) basepath = sheetMgr.GetCellValue(importSheetConfig, sheetName, 5, 1) print("\troot folder for import "+basepath) relative_to_now = sheetMgr.GetCellValue(importSheetConfig, sheetName, 6, 1) print("\timport interval relative to current time: {}".format(relative_to_now)) relative_interval = sheetMgr.GetCellValue(importSheetConfig, sheetName, 7, 1) print("\trelative import period {} h".format(relative_interval)) if relative_to_now: from_time = System.DateTime.Now.AddHours(-relative_interval) to_time = System.DateTime.Now.AddDays(1) print("Importing data for last {} h + 1 day lead time ({} to {}).".format(relative_interval, from_time, to_time)) else: print("Importing all available data between {} and {}".format(from_time, to_time)) # In[ ]: # get list of loggers from API url_getloggers = "http://www.irrimaxlive.com/api/?cmd=getloggers&key="+api_key print("reading " + url_getloggers) xml_string = urllib2.urlopen(url_getloggers).read() # remove encoded characters printable = set(string.printable) xml_string = filter(lambda x: x in printable, xml_string) # parse string to XML object xml_tree = etree.ElementTree(etree.fromstring(xml_string)) # In[ ]: # print all loggers for logger in xml_tree.iter("Logger"): print("found logger {} (id={})".format(logger.attrib["name"], logger.attrib["id"])) # In[ ]: datetimeformat = "{:04d}{:02d}{:02d}{:02d}{:02d}{:02d}" from_str = datetimeformat.format(from_time.Year, from_time.Month, from_time.Day, from_time.Hour, from_time.Minute, from_time.Second) to_str = datetimeformat.format(to_time.Year, to_time.Month, to_time.Day, to_time.Hour, to_time.Minute, to_time.Second) url_getreadings_byid = "http://www.irrimaxlive.com/api/?cmd=getreadings&key={}&id={}&from={}&to={}" # In[ ]: def timeseries_exists(path): tsmgr = app.Modules.Get('Time series Manager') if tsmgr is None: raise NameError('Could not load time series manager') if tsmgr.TimeSeriesList.Fetch(path) is None: return False else: return True # In[ ]: print(System.Double(1.)) # In[ ]: def CreateTimeSeries(timeSeries, unitType, unitVariable, valueType): """ <Script> <Author>jga/are</Author> <Description>Create time series</Description> <Parameters> <Parameter name="timeSeries" type="string">destination time series name</Parameter> <Parameter name="unitType" type="string">unit type</Parameter> <Parameter name="unitVariable" type="string">Variable type</Parameter> <Parameter name="valueType" type="string">"Instantaneous", "Accumulated", "Step Accumulated" or "Reverse Mean Step Accumulated"</Parameter> </Parameters> </Script> """ timeSeriesManager = app.Modules.Get('Time series Manager') if timeSeriesManager is None: raise NameError('Could not load time series manager') dataSeries = GetDataSeries(timeSeries) if dataSeries is None: dataSeries = timeSeriesManager.TimeSeriesList.CreateNew(timeSeries) dataSeries.YAxisVariable = unitType # for Rainfall Depth time series, create as Accumulated, Rainfall Step Accumulated others default to Instantaneous if valueType == "Instantaneous": dataSeries.ValueType = DataSeriesValueType.Instantaneous elif valueType == "Accumulated": dataSeries.ValueType = DataSeriesValueType.Accumulated elif valueType == "Step Accumulated": dataSeries.ValueType = DataSeriesValueType.Step_Accumulated elif valueType == "Reverse Mean Step Accumulated": dataSeries.ValueType = DataSeriesValueType.Reverse_Mean_Step_Accumulated elif type(valueType) == DataSeriesValueType: # if dataseries value type has been provided, assign it dataSeries.ValueType = valueType try: dataSeries.SetYAxisUnit(unitVariable, False) # robustness againast unit name change between MIKE 2014 -> 2016 except System.Exception as e: if unitVariable == "m^3/day": # 2014 unit unitVariable = "m^3/d" # 2016 unit dataSeries.SetYAxisUnit(unitVariable, False) elif unitVariable == "m^3/d": # 2016 unit unitVariable = "m^3/day" # 2014 unit dataSeries.SetYAxisUnit(unitVariable, False) else: raise e # something else is wrong timeSeriesManager.TimeSeriesList.Add(dataSeries) else: dataSeries.DeleteAll() dataSeries.ClearData() del dataSeries # In[ ]: def timeseries_exists(path): tsmgr = app.Modules.Get('Time series Manager') if tsmgr is None: raise NameError('Could not load time series manager') if tsmgr.TimeSeriesList.Fetch(path) is None: return False else: return True # In[ ]: def GetDataSeries(timeSeries): """ <Script> <Author>admin</Author> <Description>write python list to time series</Description> <Parameters> <Parameter name="timeSeries" type="string">destination time series path</Parameter> </Parameters> </Script> """ timeSeriesManager = app.Modules.Get('Time series Manager') if timeSeriesManager is None: raise NameError('Could not load time series manager') dataSeries = timeSeriesManager.TimeSeriesList.Fetch(timeSeries) return dataSeries # In[ ]: def add_steps_to_ts(plist, ts_path): tmgr = app.Modules.Get('Time series Manager') ts = tmgr.TimeSeriesList.Fetch(ts_path) timestepts = ts.FetchAll() if(timestepts.Count > 0): lastTimestep = timestepts[timestepts.Count - 1].XValue else: lastTimestep = DateTime.MinValue count = 0 for x, y in plist: date = x if date > lastTimestep: value = System.Double(y) step = ts.CreateNew() step.XValue = date step.YValue = value ts.Add(step) count+=1 tmgr.TimeSeriesList.Update(ts) # In[ ]: # iterate all loggers: for logger in xml_tree.iter("Logger"): print("logger {} (id={})".format(logger.attrib["name"], logger.attrib["id"])) # download logger data logger_id = logger.attrib["id"] url_request = url_getreadings_byid.format(api_key, logger_id , from_str, to_str) print("reading data from "+url_request) csv_string = urllib2.urlopen(url_request).read() # create dictionary {header name: column number} headers = StringIO(csv_string).readline().split(",") header_of = {headers[i].split("(")[0]:i for i in range(len(headers))} # iterate over sites > probes > sensors for site in logger.iter("Site"): print("\tsite {}".format(site.attrib["name"])) for probe in site.iter("Probe"): print("\t\tprobe {}".format(probe.attrib["name"])) for sensor in probe.iter("Sensor"): print("\t\t\tsensor {}: {} ({})".format(sensor.attrib["name"], sensor.attrib["type"], sensor.attrib["unit"])) column = header_of[sensor.attrib["name"]] # sensor logics sensor_variable = None sensor_unit = None sensor_factor = 1. sensor_comment = "" if sensor.attrib["type"] == "Voltage": sensor_variable = "Voltage" sensor_comment = sensor.attrib["description"] if sensor.attrib["unit"] == "V": sensor_unit = "V" if sensor.attrib["type"] == "Soil Water Content": sensor_variable = "Volumetric Water Content" sensor_comment = "{} cm".format(sensor.attrib["depth_cm"]) if sensor.attrib["unit"] == "mm": sensor_unit = "%" if sensor.attrib["type"] == "V.I.C.": sensor_variable = "Undefined" sensor_comment = "{} cm".format(sensor.attrib["depth_cm"]) if sensor.attrib["unit"] == "VIC": sensor_unit = "-" if sensor.attrib["type"] == "Temperature": sensor_variable = "Temperature" sensor_comment = "{} cm".format(sensor.attrib["depth_cm"]) if sensor.attrib["unit"] == "C": sensor_unit = "deg C" if sensor_variable is None: print("unknown sensor type "+sensor.attrib["type"]) if sensor_unit is None: print("unknow sensor unit "+sensor.attrib["unit"]) if sensor_variable is None or sensor_unit is None: print("skipped.") continue # set path of time series ts_path = basepath+"/{}/{}/{}/{}({})".format(logger.attrib["name"], site.attrib["name"], probe.attrib["name"], sensor.attrib["name"], sensor_comment) # check if TS exists and create if necessary if not timeseries_exists(ts_path): print("\t\t\t\tCreating Time Series "+str(ts_path)) CreateTimeSeries(ts_path, sensor_variable, sensor_unit, "Instantaneous") # Add new measurements to time series # create data list [(DateTime, float)] from column in csv ts = [] csv = StringIO(csv_string) csv.readline() # discard headers while True: line = csv.readline() if line == "": break words = line.split(',') # parse string to DateTime (via datetime) dt = datetime.datetime.strptime(words[0], "%Y/%m/%d %H:%M:%S") DT = DateTime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) # parse string to float ts.append((DT, float(words[column]))) if len(ts) == 0: print("\t\t\t\tNo new measurements found.") else: print("\t\t\t\tAdding {} measurments to {} ".format(len(ts), ts_path)) add_steps_to_ts(ts, ts_path)
def SetSingleParameterValue(self, target, name, value): """Sets the value of the parameter you specify.""" _RaiseException_( self.modmgr.SetSingleParameterValue(target, name, System.Double(value)))
def GetSingleParameterValue(self, target, name): """Acquires the value of the parameter you specify.""" data = self.modmgr.GetSingleParameterValue(target, name, System.Double(0)) _RaiseException_(data[0]) return data[1]
clr.AddReference("NationalInstruments.VeriStand.RealTimeSequenceDefinitionApi") from NationalInstruments.VeriStand.StimulusProfileDefinitionApi import StimulusProfile from NationalInstruments.VeriStand.ClientAPI import Factory #Instance of Class Factory provides access to the NI VeriStand system fac = Factory() print(fac) #Interface to perform basic workspace operations facWork = fac.GetIWorkspace2('localhost') print(facWork) #Create StimulusProfile object and execute profile asynchronously. stimProfile = StimulusProfile("c:\\Users\\Public\\Documents\\National Instruments\\NI VeriStand 2017\\Examples\\Stimulus Profile\\Engine Demo\\Stimulus Profiles\\Basic Engine Demo\\Engine Demo Basics.nivsstimprof") stimProfile.ExecuteAsync('localhost','000') #define in out parameters chan = System.String("Targets/Controller/Simulation Models/Models/Engine Demo/Outports/RPM") out = System.Double(0) error, out = facWork.GetSingleChannelValue(chan, out) print("") print("Error code:") print(error.get_Code()) print("Channel name:") print(chan) print("Channel Value:") print(out)
def test_pep3141(): ''' This is already well covered by CPython's test_abstract_numbers.py. Just check a few .NET interop cases as well to see what happens. ''' import System from numbers import Complex, Real, Rational, Integral, Number #--Complex for x in [ System.Double(9), System.Int32(4), System.Boolean(1), ]: Assert(isinstance(x, Complex)) for x in [ #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=23147 System.Char.MaxValue, System.Single(8), System.Decimal(10), System.SByte(0), System.Byte(1), System.Int16(2), System.UInt16(3), System.UInt32(5), System.Int64(6), System.UInt64(7), ]: Assert(not isinstance(x, Complex), x) #--Real for x in [ System.Double(9), System.Int32(4), System.Boolean(1), ]: Assert(isinstance(x, Real)) for x in [ #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=23147 System.Char.MaxValue, System.Single(8), System.Decimal(10), System.SByte(0), System.Byte(1), System.Int16(2), System.UInt16(3), System.UInt32(5), System.Int64(6), System.UInt64(7), ]: Assert(not isinstance(x, Real)) #--Rational for x in [ System.Int32(4), System.Boolean(1), ]: Assert(isinstance(x, Rational)) for x in [ System.Double(9), #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=23147 System.Char.MaxValue, System.Single(8), System.Decimal(10), System.SByte(0), System.Byte(1), System.Int16(2), System.UInt16(3), System.UInt32(5), System.Int64(6), System.UInt64(7), ]: Assert(not isinstance(x, Rational)) #--Integral for x in [ System.Int32(4), System.Boolean(1), ]: Assert(isinstance(x, Integral)) for x in [ System.Double(9), #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=23147 System.Char.MaxValue, System.Single(8), System.Decimal(10), System.SByte(0), System.Byte(1), System.Int16(2), System.UInt16(3), System.UInt32(5), System.Int64(6), System.UInt64(7), ]: Assert(not isinstance(x, Integral)) #--Number for x in [ System.Double(9), System.Int32(4), System.Boolean(1), ]: Assert(isinstance(x, Number)) for x in [ #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=23147 System.Char.MaxValue, System.Single(8), System.Decimal(10), System.SByte(0), System.Byte(1), System.Int16(2), System.UInt16(3), System.UInt32(5), System.Int64(6), System.UInt64(7), ]: Assert(not isinstance(x, Number))