def make_predictions(pkg, prediction_model, previous_numbers): """Iterates over predictions until we get enough of them. Make predictions for a given sequence. Args: pkg(jpype object): common root of the java package from which we load the classes we need. prediction_model(jpype object): CPT+ java object trained, used here to make predictions. previous_numbers(list): number sequence for which we want a prediction. Returns: list: the predictions. A list of 5 numbers for the balls or a list of 2 for the stars. """ # Loading the java classes we need and instantiating the objects we will use sequence_numbers = prepare_prediction_request(pkg, previous_numbers) sequence_class = pkg.database.Sequence item_class = pkg.database.Item integer_class = jpype.JClass('java.lang.Integer') # For emphasis, we tell the user when there is no prediction (prediction set to zero) nbtype = 'balls' if len(previous_numbers) > 2 else 'stars' numbers_set = set() for i in range(1, len(previous_numbers) + 1): old_len = len(numbers_set) new_len = 0 # set() garanties no duplicates. # Keep on predicting until something is added to set or tree clueless while old_len >= new_len: prediction = prediction_model.Predict(sequence_numbers) try: p = int(str(prediction.get(jpype.JInt(0)))) except jpype.JavaException: msg = f"CPT+ has no more prediction for this branch, prediction set to zero "\ f"for {nbtype}_{str(i)}" numbers_set.add(0) break integer = integer_class( jpype.JInt(p)) # Add last prediction p to input seq item = item_class(integer) sequence_numbers.addItem(item) prediction = sequence_class( jpype.JInt(0)) # Re-initialize prediction numbers_set.add(p) new_len = len(numbers_set) try: tqdm.write(colorama.Fore.RED + msg + colorama.Style.RESET_ALL) except BaseException: pass return list(numbers_set)
def match_amp_first_to_second(u1, u2, dt, res_match_obj): #MAKES ASSUMPTION THAT INTERPOLATION HAS BEEN DONE PRIOR TO ENTERING THIS ROUTINE, SO THAT THE SHAPES OF THE ARRAYS ARE EQUAL #By default will normalize u1 to u2. #Enter u1 and u2 as 2D arrays in normal form: nt rows and nr receivers. All transposes and dtype changes will happen in this routine (nt, nr) = u1.shape assert ((nt, nr) == u2.shape) u1_transposed_and_float32 = u1.astype('float32').transpose() u2_transposed_and_float32 = u2.astype('float32').transpose() udmatch_transposed_and_float32 = np.zeros((nr, nt), dtype='float32') u1_float_java = jpype.JArray(jpype.JFloat, u1_transposed_and_float32.ndim)( u1_transposed_and_float32.tolist()) u2_float_java = jpype.JArray(jpype.JFloat, u2_transposed_and_float32.ndim)( u2_transposed_and_float32.tolist()) udmatch_java = jpype.JArray(jpype.JFloat, udmatch_transposed_and_float32.ndim)( udmatch_transposed_and_float32.tolist()) nrLiveSyn_java = jpype.JInt(nr) #each row is receiver nt_java = jpype.JInt(nt) #each column is a timestep dt_java = jpype.JFloat(dt) #This routine below normalizes its first entry to its second. res_match_obj.match(u1_float_java, u2_float_java, udmatch_java, nt_java, dt_java, nrLiveSyn_java) #I'm not really sure how to efficiently transfer jpype array back. Can't find documentation for that. for i in xrange(nr): #not efficient, but dont know how to do else temp_arr = udmatch_java[i][:] nan_index = np.isnan( temp_arr ) #when values in windows entirely 0 (before arrival), nan can be the result inf_index = np.isinf( temp_arr ) #when values in windows entirely 0 (before arrival), inf can be the result temp_arr[nan_index] = 1.0 #convert nan values to 1.0 temp_arr[inf_index] = 1.0 #convert inf values to 1.0 udmatch_transposed_and_float32[i, :] = temp_arr u1_modified_transposed_and_float32 = copy.deepcopy( u1_transposed_and_float32 ) * udmatch_transposed_and_float32 #Quite sure I don't really need to copy, since the dtype change in line 12 probably already resulted in addressing a different piece of memory u1_modified = u1_modified_transposed_and_float32.transpose().astype( 'float64' ) #rest of program works with float64. Not sure how type differences would propagate to influence final result. return u1_modified
def testSyncronizedFail(self): with self.assertRaisesRegex(TypeError, "Java object is required"): with jpype.synchronized(object()): pass with self.assertRaisesRegex(TypeError, "Java primitives cannot be used"): with jpype.synchronized(jpype.JInt(1)): pass
def testPrivitiveToBoxed(self): jpype.java.lang.Boolean(jpype.JBoolean(0)) jpype.java.lang.Byte(jpype.JByte(0)) jpype.java.lang.Short(jpype.JShort(0)) jpype.java.lang.Integer(jpype.JInt(0)) jpype.java.lang.Long(jpype.JLong(0)) jpype.java.lang.Float(jpype.JFloat(0)) jpype.java.lang.Double(jpype.JDouble(0))
def prepare_prediction_request(pkg, numbers): """Turns a python list into a java sequence, in order to query for a prediction. Args: pkg(jpype object): common root of the java package from which we load the classes we need. numbers(list): the sequence of numbers to use as a query/arg for the prediction. Returns: jpype object: sequence of numbers in their java format. """ # Loading the java classes we need and instantiating the objects we will use. sequence_class = pkg.database.Sequence sequence = sequence_class(jpype.JInt(0)) item_class = pkg.database.Item integer_class = jpype.JClass('java.lang.Integer') for number in numbers: integer = integer_class(jpype.JInt(number)) item = item_class(integer) sequence.addItem(item) return sequence
def polyline(self, points, closed=True, **kwargs): polygon_name = kwargs["name"] layer = kwargs["layer"] for i in range(len(points)): if isinstance(points[i], tuple) and len(points[i]) == 2: points[i] += (0, ) elif isinstance(points[i], list) and len(points[i]) == 2: points[i].append(0) points = parse_entry(points) wp = self._set_workplane(layer, polygon_name) pol = wp.geom().create(polygon_name, "Polygon") pol.set("source", "table") if closed: pol.set("type", "solid") else: pol.set("type", "open") for ii, point in enumerate(points): #pol.setIndex("table", self._sympy_to_comsol_str(point[0]), ii, 0) #pol.setIndex("table", self._sympy_to_comsol_str(point[1]), ii, 1) import jpype pol.setIndex("table", self._sympy_to_comsol_str(point[0])[0], jpype.JInt(ii), 0) pol.setIndex("table", self._sympy_to_comsol_str(point[1])[0], jpype.JInt(ii), 1) print('Polygon {} created'.format(polygon_name)) return polygon_name
def select(self, sql): '''选取数据''' result_list = [] try: # 执行sql并获取列数 preStat = self.connector.prepareStatement(sql) query_result = preStat.executeQuery() columnCounts = query_result.getMetaData().getColumnCount() # 循环获取数据 while columnCounts > 0 and query_result.next(): result_list.append([query_result.getString(jpype.JInt(i + 1)) for i in range(columnCounts)]) except JavaException as e: _logger.error("Oracle Driver: SQL Error in Query Select") log_java_exception(e) self.close() raise e else: return result_list
def load_training_set(pkg, path, numbers=[]): """Loads the training set file of training sequences. Either simply load a training set file (in the tree) as is, or load a training set file appended with an additional sequence. Args: pkg(jpype object): common root of the java package from which we load the classes we need. path(str): filepath to the training file to load. numbers(list): optional, number sequence(s) to append to training file. Returns: jpype object: training set object. """ # Loading the java classes we need and instantiating the objects we will use # Training Set: this is the file we feed to the tree training_set_class = pkg.database.SequenceDatabase training_set = training_set_class() if numbers: with tempfile.NamedTemporaryFile(mode='w+') as tmpf: with open(path, 'r') as file: tmpf.write(file.read()) new_line = ' -1 '.join(map( str, numbers)) + ' -1 -2\n' # SPMF format tmpf.write(new_line) tmpf.seek(0) training_set.loadFileSPMFFormat(jpype.JString(tmpf.name), jpype.JInt(99999), jpype.JInt(0), jpype.JInt(99999)) else: training_set.loadFileSPMFFormat(jpype.JString(path), jpype.JInt(99999), jpype.JInt(0), jpype.JInt(99999)) return training_set
def testIntFromIntWrapper(self): self.Fields.intField = jpype.JInt(5) self.assertEquals(self.Fields.intField,5)
def testMonitorOnPrim(self): value = jpype.JInt(1) with self.assertRaises(TypeError): _jpype._JMonitor(value)
def hashCode(self): return jpype.JInt(hash(self.what) & 0x7FFFFFFF)
def testObjectInteger(self): self.Fields.objectField = jpype.JInt(2) self.assertEqual(self.Fields.objectField, 2) self.assertIsInstance(self.Fields.objectField, jpype.JClass('java.lang.Integer'))
def insert(self, table_name, columns, datalist): """向表中插入数据 位置参数:表名,列名列表,数据表格(二维列表) """ # 测试请求数据库 testSql = 'select {cols} from "{table_name}" where rownum = 1'.format( cols=', '.join(columns), table_name=table_name ) # 获取目标表的列定义 try: preStat = self.connector.prepareStatement(testSql) testResult = preStat.executeQuery() # 列表生成式:获取列类型码的列表 columnsTypeList = [testResult.getMetaData().getColumnType(jpype.JInt(i + 1)) for i in range(len(columns))] except JavaException as e: _logger.error('Oracle Driver: Error In Execute Test SQL') log_java_exception(e) self.close() raise e # 生成SQL模板 insert_sql_template = 'insert into "{table_name}" ({cols}) values ({placeholders})'.format( table_name=table_name, cols=', '.join(columns), placeholders=', '.join(['? ' for i in range(len(columns))]) ) result = 0 try: # 按行循环数据集合 for row in datalist: # 准备执行sql模版 preStat = self.connector.prepareStatement(insert_sql_template) paramList = [] # 按列循环数据行 for i, data in enumerate(row): # 如果数据为空则设置一个null参数 if data == None: preStat.setNull(jpype.JInt(i + 1), columnsTypeList[i]) paramList.append('None') # 否则判断列的值类型,动态调用set方法 else: param_pyclass = self.__switchType(columnsTypeList[i]) # 根据sql类型获取java类型 param = self.__prepareParam(param_pyclass, data) # 根据java类型为数据转型 # 如果java类型为整型包装类,则调整方法名为setInt if param_pyclass.class_.getSimpleName() == "Integer": methodName = 'setInt' # 否则动态设置方法名 else: methodName = 'set' + param_pyclass.class_.getSimpleName() # 根据方法名动态查找方法并调用 getattr(preStat, methodName)(jpype.JInt(i + 1), param) paramList.append(str(param._pyv if hasattr(param, '_pyv') else param)) _logger.info("\nExecute: " + insert_sql_template + "\nParams: " + ', '.join(paramList)) # 执行sql result = result + preStat.executeUpdate() except JavaException as e: _logger.error("Oracle Driver: SQL Error in execute insert") log_java_exception(e) self.connector.rollback() self.close() raise e else: self.connector.commit() _logger.info("Oracle Driver: Insert %d rows into %s" % (result, table_name))