def update_project(project_id):
    new_project = request.get_json()
    try:
        project = Project.get(Project.id == project_id)
    except models.DoesNotExist:
        return jsonify({ 'message': 'Project not found' }), 400
    if new_project['id'] != project.id:
        return jsonify({ 'message': 'Cannot update project at this url' }), 400
    try:
        if new_project['markerOptions']:
            marker_options = new_project['markerOptions']
            for marker_name in marker_options:
                try:
                    marker_option = MarkerOption.get(MarkerOption.name == marker_name)
                    ProjectMarkerOption.get(ProjectMarkerOption.project == project.id,
                                            ProjectMarkerOption.marker_option == marker_option.id)
                except models.DoesNotExist:
                    ProjectMarkerOption.create(project = project, marker_option = marker_option)
        if new_project['users']:
            users = new_project['users']
            for user in users:
                try:
                    project_user = ProjectUser.get(ProjectUser.app_user == user['id'],
                                                    ProjectUser.project == project)
                except models.DoesNotExist:
                    ProjectUser.create(app_user = user['id'], project = project)
        if new_project['stacks']:
            stacks = new_project['stacks']
            with db.atomic():
                for stack in stacks:
                    try:
                        project_stack = ProjectStack.get(ProjectStack.stack == stack['id'],
                                                        ProjectStack.project == project)
                    except models.DoesNotExist:
                        project_stack = ProjectStack.create(project=project, stack = stack['id'])
                        probe_setting = stack['probeSettings']
                        probe_position = json.loads(probe_setting['position'])
                        ProbeSetting.create(x_offset=int(probe_position['xOffset']),
                                            y_offset=int(probe_position['yOffset']),
                                            project_stack=project_stack,
                                            label=probe_position['label']
                                        )
        message = "Project updated"
    except Exception as ex:
        print ex
    project = Project.get(Project.id == project_id)
    return jsonify({ 'message': 'Project updated', 'project': project.deep_serialized() }), 200
def project_stack_images(project_id, stack_id):
    first_image = Image.select().join(StackImage).where(StackImage.stack == stack_id).get().key
    last_underscore = first_image.rfind('_')
    stack_title = first_image[:last_underscore]
    project_stack = ProjectStack.get(ProjectStack.project == project_id, ProjectStack.stack == stack_id)
    project_stack_user_data = project_stack.project_stack_data.where(ProjectStackDatum.user == g.user_id)
    probe_type = project_stack.project.probe_type
    probe_settings = project_stack.probe_setting.get()
    images = (Image.select().join(StackImage).where(StackImage.stack == stack_id)
                .order_by(Image.name))
    project_stacks = Stack.select().join(ProjectStack).where(ProjectStack.project == project_id).order_by(Stack.id)
    marker_options = MarkerOption.select().join(ProjectMarkerOption).where(ProjectMarkerOption.project == project_id)
    return jsonify({ 'images': [image.stack_image_serialized for image in images],
                     'data': [d.serialized for d in project_stack_user_data],
                     'probeSettings': probe_settings.serialized,
                     'stackTitle': stack_title,
                     'probeType': probe_type,
                     'markerOptions': [marker_option.name for marker_option in marker_options],
                     'projectStackIds': [stack.id for stack in project_stacks]
                    })
def projects():
    req = request.get_json()
    message = ""
    try:
        page = req['page']
        page_size = req['pageSize']
    except (TypeError, KeyError):
        page = 1
        page_size = 20
    if request.method == 'POST':
        try:
            request_error = False
            title = req['title']
            comments = req['comments']
            stacks = req['stacks']
            probe_type = req['probeType']
        except KeyError:
            request_error = True
        if request_error:
            return jsonify({ 'message': 'Insufficient information to create project' }), 400
        try:
            project = Project.create(title=title, comments=comments, probe_type=probe_type)
            if req['markerOptions']:
                marker_options = req['markerOptions']
                for marker_name in marker_options:
                    try:
                        marker_option = MarkerOption.get(MarkerOption.name == marker_name)
                        ProjectMarkerOption.create(project = project, marker_option = marker_option)
                    except Exception as ex:
                        print("line 74")
                        print ex
            if req['users']:
                users = req['users']
                for user in users:
                    try:
                        ProjectUser.create(app_user = user['id'], project = project)
                    except Exception as ex:
                        print ex
            for stack in stacks:
                try:
                    project_stack = ProjectStack.create(project=project, stack = stack['stackId'])
                    probe_setting = stack['probeSettings']
                    probe_position = json.loads(probe_setting['position'])
                    ProbeSetting.create(x_offset=int(probe_position['xOffset']),
                                        y_offset=int(probe_position['yOffset']),
                                        project_stack=project_stack,
                                        label=probe_position['label']
                                    )
                except Exception as ex:
                    print ex
            message = "Project created"
        except Exception as ex:
            print ex
    projects = (Project.select()
        .order_by(Project.created_date.desc()))
        # .paginate(page, page_size))
    return jsonify({ 
        'message': message,
        'projects': [project.serialized for project in projects],
        'projectCount': SelectQuery(models.Project).count()
    }), 201
def get_marker_options():
    marker_options = MarkerOption.select().order_by(MarkerOption.name)
    return jsonify({ 'markerOptions': [marker_option.name for marker_option in marker_options] })
def json_to_excel_neuron_dimensions(report, project_id):
    xlsx_file = Workbook()
    ws = xlsx_file.active
    ws['A1'] = 'User'
    ws['B1'] = 'Case'
    ws['C1'] = 'Hemisphere'
    ws['D1'] = 'Stain'
    ws['E1'] = 'Region'
    ws['F1'] = 'Section'
    ws['G1'] = 'Probe'
    ws['H1'] = 'Z Value'
    ws['I1'] = 'Neuron Height'
    ws['J1'] = 'Neuron Width'

    micrometer_scale_length = 10 # will this ever change?
    row = 1
    column = 'K'
    marker_columns = {}
    marker_mappings = {
            'Neuron': 'neuron',
            'Oligodendrocyte': 'oligodendrocyte',
            'Astrocyte': 'astrocyte',
            'Pericyte': 'pericyte',
            'Marker 1': 'markerone',
            'Marker 2': 'markertwo',
            'Out of Focus': 'out-of-focus',
            'Length': 'length',
            'Blood Cell(s)': 'blood-cell',
            'Guard Zone': 'guard-zone'
            }

    marker_types = (MarkerOption.select()
                            .join(ProjectMarkerOption)
                            .where(ProjectMarkerOption.project == project_id)
                            .order_by(MarkerOption.name))
    for marker in marker_types:
        ws['{0}{1}'.format(column, row)] = marker.name
        marker_columns[marker_mappings[marker.name]] = column
        column = chr(ord(column) + 1)

    for project_stack in report:
        stack_info = project_stack.split('_')
        if len(stack_info) != 6:
            stack_info = ['a', 'b', 'c', 'd', 'e', 'f']
        for stack_image in report[project_stack]:
            for user in report[project_stack][stack_image]:
                for marker in report[project_stack][stack_image][user]:
                    if marker['markerType'] == 'neuron':
                        row += 1
                        ws['A{}'.format(row)] = user
                        ws['B{}'.format(row)] = stack_info[0]
                        ws['C{}'.format(row)] = stack_info[1]
                        ws['D{}'.format(row)] = stack_info[2]
                        ws['E{}'.format(row)] = stack_info[3]
                        ws['F{}'.format(row)] = stack_info[4]
                        ws['G{}'.format(row)] = stack_info[5]
                        ws['H{}'.format(row)] = stack_image
                        ws['I{}'.format(row)] = (float(marker['yCrosshairPercent']) / 100) * micrometer_scale_length * 2 # see Marker model
                        ws['J{}'.format(row)] = (float(marker['xCrosshairPercent']) / 100)* micrometer_scale_length * 2 # "
    
    return xlsx_file
def json_to_excel_stack_counts(report, project_id):
    xlsx_file = Workbook()
    ws = xlsx_file.active
    ws['A1'] = 'User'
    ws['B1'] = 'Case'
    ws['C1'] = 'Hemisphere'
    ws['D1'] = 'Stain'
    ws['E1'] = 'Region'
    ws['F1'] = 'Section'
    ws['G1'] = 'Probe'
    ws['H1'] = 'Z Value'

    row = 1
    column = 'I'
    marker_columns = {}
    marker_mappings = {
            'Neuron': 'neuron',
            'Oligodendrocyte': 'oligodendrocyte',
            'Astrocyte': 'astrocyte',
            'Pericyte': 'pericyte',
            'Marker 1': 'markerone',
            'Marker 2': 'markertwo',
            'Out of Focus': 'out-of-focus',
            'Length': 'length',
            'Blood Cell(s)': 'blood-cell',
            'Guard Zone': 'guard-zone'
            }

    marker_types = (MarkerOption.select()
                            .join(ProjectMarkerOption)
                            .where(ProjectMarkerOption.project == project_id)
                            .order_by(MarkerOption.name))
    for marker in marker_types:
        ws['{0}{1}'.format(column, row)] = marker.name
        marker_columns[marker_mappings[marker.name]] = column
        column = chr(ord(column) + 1)

    for project_stack in report:
        stack_info = project_stack.split('_')
        if len(stack_info) != 6:
            stack_info = ['a', 'b', 'c', 'd', 'e', 'f']
        for stack_image in report[project_stack]:
            for user in report[project_stack][stack_image]:
                row += 1
                ws['A{}'.format(row)] = user
                ws['B{}'.format(row)] = stack_info[0]
                ws['C{}'.format(row)] = stack_info[1]
                ws['D{}'.format(row)] = stack_info[2]
                ws['E{}'.format(row)] = stack_info[3]
                ws['F{}'.format(row)] = stack_info[4]
                ws['G{}'.format(row)] = stack_info[5]
                ws['H{}'.format(row)] = stack_image
                
                user_markers = {}
                for m in report[project_stack][stack_image][user]:
                    try:
                        user_markers[m['markerType']] = user_markers[m['markerType']] + 1
                    except KeyError:
                        user_markers[m['markerType']] = 1
                if user_markers:
                    for marker in user_markers:
                        ws['{0}{1}'.format(marker_columns[marker], row)] = user_markers[marker]
    
    return xlsx_file