def init_from_nums(cls, fnum, expnum=0, drootpath="./data/CASCADE"): """ Alternative constructor from experiment- and filenumber -------------------------------------------------- Arguments: ---------- expnum : int : number of the experiment/proposal fnum : int : number of the file drootpath : str : path to the data directory, default './data/CASCADE' Return: ---------- obj : DataFrame_NICOS : DataFrame_NICOS object associated with the given file. Makes metadata and raw CASCADE output accessible with python """ return cls(utils.gen_filename(expnum, fnum), drootpath)
def test_break(pool_physics, plot_motion_timelapse, plot_energy, gl_rendering): physics = pool_physics ball_positions = physics.eval_positions(0.0) r_c = ball_positions[0].copy() r_c[2] += physics.ball_radius V = np.array((-0.01, 0.0, -1.6), dtype=np.float64) M = 0.54 outname = gen_filename('test_break.%s' % git_head_hash(), 'pstats', directory=os.path.join(_here, 'pstats')) from time import perf_counter import cProfile pr = cProfile.Profile() pr.enable() t0 = perf_counter() events = physics.strike_ball(0.0, 0, ball_positions[0], r_c, V, M) t1 = perf_counter() pr.dump_stats(outname) _logger.info('...dumped stats to "%s"', outname) _logger.info('evaluation time: %s', t1 - t0) _logger.info('strike on %d resulted in %d events', 0, len(events))
def main_loop(config_file): retcode, config_json = utils.gen_config(config_file) print 'mask_jon:', config_json while True: print( '---------------------------------------------------------------') t1 = time.time() f1 = utils.gen_filename(INPUT_FILE, t1) duration = config_json['duration'] # create folder for img storing if os.path.exists('./img') == False: os.system('mkdir img') # call cap function to capture picture print 'f1:', f1 ret, w, h = cap.cap(f1, 640, 480) if ret == -1: print 'capture image fail!' else: retcode = 0 if config_json['cloud'] == 'oss': # upload file ... retcode = myoss.upload_file_to_oss(config_json['oss'], f1) elif config_json['cloud'] == 'bos': retcode = mybos.file_upload_bos(config_json['bos'], f1) else: print('no cloud defined, no file uploaded') print 'upload retcode:', retcode while (time.time() - t1) < duration: time.sleep(1)
def log_detect_package(request): """Пакетная обработка детекторов видеоаналитики""" answer = dict() answer["status"] = False try: # Получение запроса из файла import settings if os.path.exists(os.path.join(settings.PROJECT_ROOT, 'query.txt')): import settings f = open(os.path.join(settings.PROJECT_ROOT, 'query.txt'), 'r+b') query_str = f.read() f.close() # TODO убрать и сделать проверку из request else: # получение запроса из request if 'data' not in request.REQUEST: answer["error"] = "data not found" return JsonResponse(answer) query_str = request.REQUEST["data"] # обработка запроса query = json.loads(query_str) # проверки полей if not check_field('detects', query): answer["error"] = "detects not found" return JsonResponse(answer) detects = query['detects'] if check_field('size', query) and query['size'] != len(detects): answer["error"] = "size not equal len of detects" return JsonResponse(answer) # загрузка настроек from videoclient import utils #default_coeff = float(utils.get_value_defaultparams(journalBoundCoeff)) # инициализация переменных answer["detects"] = [] names = ['dt_detect', 'frame', 'preview', 'camera_id', 'detector_type_id', 'json_data'] items = [] # инициализация базы данных from django.db import connection, transaction cursor = connection.cursor() all_cameras = dict() all_sub_types = dict() # обработка детектов for detect in detects: answer_detect = dict() answer_detect["status"] = False other_data = dict() try: # Индекс детекта в пакете, # необходимо в ответе вернуть такой же if check_field("index", detect): answer_detect["index"] = detect["index"] # Проверка и обработка времени детекта if check_field("alertTime", detect): alertTime = float(detect["alertTime"])/1000 else: alertTime = time.time() alertTime = datetime.datetime.fromtimestamp(alertTime) alertTime_str = alertTime.strftime("%Y-%m-%d %H:%M:%S") time_update = alertTime_str other_data["dt_detect"] = alertTime_str # Проверки на наличие cameraIp и cameraType # обработка этих параметров идет ниже if not check_field("cameraIp", detect): answer_detect["error"] = "cameraIp not found" answer["detects"].append(answer_detect) continue if not check_field("cameraType", detect): answer_detect["error"] = "cameraType not found" answer["detects"].append(answer_detect) continue if not check_field("cameraUuid", detect): answer_detect["error"] = "cameraUuid is not found" answer["detects"].append(answer_detect) continue # Обработка параметров камеры cameraIp = detect["cameraIp"] cameraType = detect["cameraType"] cameraUUID = detect["cameraUuid"] if cameraUUID in all_cameras: camera = all_cameras[cameraUUID] else: camera, create = models.Camera.objects.get_or_create(uuid=cameraUUID) cam = camera cam.ip = cameraIp cam.type = cameraType cam.save() if cameraUUID not in all_cameras: all_cameras[cameraUUID] = dict() all_cameras[cameraUUID] = camera other_data["camera_id"] = camera.id # Проверка типа детектора if not check_field("alertSubType", detect): answer_detect["error"] = "alertSubType not found" answer["detects"].append(answer_detect) continue alertSubType = detect["alertSubType"] # Получаем ID ветектора в случае # если нет такого детектора то создаем if alertSubType in all_sub_types: subType = all_sub_types[alertSubType] else: subType, create = vanModels.Detector.objects.get_or_create(dtype = alertSubType) if create: subType.name = alertSubType subType.save() all_sub_types[alertSubType] = subType other_data["detector_type_id"] = subType.id # Проверка и сохранение кадра host_ip = request.get_host() detect["host_ip"] = host_ip url_prefix = "http://%s" % host_ip filename = get_journal_path(gen_filename()) temp_data = getDataSavedPhoto('frame', filename, detect, url_prefix) answer_detect.update(temp_data["answer"]) other_data.update(temp_data["other_data"]) other_data['preview'] = other_data['frame'] if check_field('originalPicture', detect): del detect['originalPicture'] other_data['json_data'] = json.dumps(detect) answer_detect["addNew"] = True item = [] for name in names: if name in other_data and other_data[name] is not None and other_data[name] != 'NULL': item.append("'%s'" %other_data[name]) else: item.append("NULL") items.append("(%s)" %(', '.join(item)) ) answer_detect["status"] = True except: logging.exception(str(sys.exc_info())) answer_detect["exception"] = str(sys.exc_info()) answer["detects"].append(answer_detect) if len(items) > 0: sql = 'insert into videoanalytics_detectorlog (%s) values %s' %(', '.join(names), ', '.join(items)) cursor.execute(sql) transaction.commit_unless_managed() answer["status"] = True except: logging.exception(str(sys.exc_info())) answer["exception"] = str(sys.exc_info()) if 'detects' in answer: for detect in answer["detects"]: detect["addNew"] = False logging.info(str(answer)) return JsonResponse(answer)